Debian Codegraph @

push_notifications/fields.py

raw
1 import re
2 import struct
3 from django import forms
4 from django.core.validators import MaxValueValidator, MinValueValidator, RegexValidator
5 from django.db import connection, models
6 from django.utils import six
7 from django.utils.translation import ugettext_lazy as _
8
9
10 __all__ = ["HexadecimalField", "HexIntegerField"]
11
12 UNSIGNED_64BIT_INT_MIN_VALUE = 0
13 UNSIGNED_64BIT_INT_MAX_VALUE = 2 ** 64 - 1
14
15
16 hex_re = re.compile(r"^(([0-9A-f])|(0x[0-9A-f]))+$")
17 signed_integer_engines = [
18 "django.db.backends.postgresql",
19 "django.db.backends.postgresql_psycopg2",
20 "django.contrib.gis.db.backends.postgis",
21 "django.db.backends.sqlite3"
22 ]
23
24
25 def _using_signed_storage():
26 return connection.settings_dict["ENGINE"] in signed_integer_engines
27
28
29 def _signed_to_unsigned_integer(value):
30 return struct.unpack("Q", struct.pack("q", value))[0]
31
32
33 def _unsigned_to_signed_integer(value):
34 return struct.unpack("q", struct.pack("Q", value))[0]
35
36
37 def _hex_string_to_unsigned_integer(value):
38 return int(value, 16)
39
40
41 def _unsigned_integer_to_hex_string(value):
42 return hex(value).rstrip("L")
43
44
45 class HexadecimalField(forms.CharField):
46 """
47 A form field that accepts only hexadecimal numbers
48 """
49 def __init__(self, *args, **kwargs):
50 self.default_validators = [
51 RegexValidator(hex_re, _("Enter a valid hexadecimal number"), "invalid")
52 ]
53 super(HexadecimalField, self).__init__(*args, **kwargs)
54
55 def prepare_value(self, value):
56 # converts bigint from db to hex before it is displayed in admin
57 if value and not isinstance(value, six.string_types) \
58 and connection.vendor in ("mysql", "sqlite"):
59 value = _unsigned_integer_to_hex_string(value)
60 return super(forms.CharField, self).prepare_value(value)
61
62
63 class HexIntegerField(models.BigIntegerField):
64 """
65 This field stores a hexadecimal *string* of up to 64 bits as an unsigned integer
66 on *all* backends including postgres.
67
68 Reasoning: Postgres only supports signed bigints. Since we don't care about
69 signedness, we store it as signed, and cast it to unsigned when we deal with
70 the actual value (with struct)
71
72 On sqlite and mysql, native unsigned bigint types are used. In all cases, the
73 value we deal with in python is always in hex.
74 """
75
76 validators = [
77 MinValueValidator(UNSIGNED_64BIT_INT_MIN_VALUE),
78 MaxValueValidator(UNSIGNED_64BIT_INT_MAX_VALUE)
79 ]
80
81 def db_type(self, connection):
82 engine = connection.settings_dict["ENGINE"]
83 if "mysql" in engine:
84 return "bigint unsigned"
85 elif "sqlite" in engine:
86 return "UNSIGNED BIG INT"
87 else:
88 return super(HexIntegerField, self).db_type(connection=connection)
89
90 def get_prep_value(self, value):
91 """ Return the integer value to be stored from the hex string """
92 if value is None or value == "":
93 return None
94 if isinstance(value, six.string_types):
95 value = _hex_string_to_unsigned_integer(value)
96 if _using_signed_storage():
97 value = _unsigned_to_signed_integer(value)
98 return value
99
100 def from_db_value(self, value, expression, connection, context):
101 """ Return an unsigned int representation from all db backends """
102 if value is None:
103 return value
104 if _using_signed_storage():
105 value = _signed_to_unsigned_integer(value)
106 return value
107
108 def to_python(self, value):
109 """ Return a str representation of the hexadecimal """
110 if isinstance(value, six.string_types):
111 return value
112 if value is None:
113 return value
114 return _unsigned_integer_to_hex_string(value)
115
116 def formfield(self, **kwargs):
117 defaults = {"form_class": HexadecimalField}
118 defaults.update(kwargs)
119 # yes, that super call is right
120 return super(models.IntegerField, self).formfield(**defaults)
121
122 def run_validators(self, value):
123 # make sure validation is performed on integer value not string value
124 value = _hex_string_to_unsigned_integer(value)
125 return super(models.BigIntegerField, self).run_validators(value)