-
Notifications
You must be signed in to change notification settings - Fork 10
/
schemas.py
296 lines (193 loc) · 7.21 KB
/
schemas.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, print_function
import re
import itertools
from datetime import datetime, date
from dateutil.parser import parse as parse_date
import six
import pytz
from schematics.models import Model
from schematics.transforms import Role
from schematics.types import (
StringType, DateTimeType as SchematicsDateTimeType, IntType, FloatType, URLType, GeoPointType, BooleanType,
DateType as SchematicsDateType
)
from schematics.types.compound import ListType as SchematicsListType, ModelType, DictType
from schematics.exceptions import (
ValidationError as SchematicsValidationError, DataError as SchematicsDataError, ConversionError
)
from schematics.types.serializable import serializable
class DateTimeType(SchematicsDateTimeType):
def to_native(self, value, context=None):
if isinstance(value, datetime):
return value
return parse_date(value)
class DateType(SchematicsDateType):
def to_native(self, value, context=None):
if isinstance(value, date):
return value
return parse_date(value).date()
class StringModelType(ModelType):
def _convert(self, value, context):
if isinstance(value, six.string_types):
return self.model_class._convert(value, context=context)
else:
return super(StringModelType, self)._convert(value, context=context)
class StringModel(Model):
@property
def import_format(self): # pragma: nocover
raise NotImplementedError()
@property
def export_format(self): # pragma: nocover
raise NotImplementedError()
def convert(self, raw_data, **kw):
if isinstance(raw_data, six.string_types):
try:
raw_data = re.match(self.import_format, six.text_type(raw_data)).groupdict()
except AttributeError:
raise SchematicsValidationError("'{}' is not a valid format for {}".format(raw_data, self.__class__.__name__))
return super(StringModel, self).convert(raw_data, **kw)
def export(self, *args, **kwargs):
return self.export_format.format(**super(StringModel, self).export(*args, **kwargs))
class StringListType(SchematicsListType):
def __init__(self, field, separator=" ", **kwargs):
self.separator = separator
super(StringListType, self).__init__(field, **kwargs)
def _coerce(self, value):
if isinstance(value, six.string_types):
return value.split(self.separator)
elif isinstance(value, dict):
return [value]
else:
return super(StringListType, self)._coerce(value)
def _export(self, *args, **kwargs):
data = super(StringListType, self)._export(*args, **kwargs)
return self.separator.join(map(six.text_type, data))
class ListType(SchematicsListType):
def _coerce(self, value):
if not isinstance(value, (list, tuple)):
return [value]
else:
return super(ListType, self)._coerce(value)
class GeoJSONPointType(GeoPointType):
def _normalize(self, value):
return tuple(reversed(super(GeoJSONPointType, self)._normalize(value)))
class Area(StringModel):
import_format = r'(?P<radius>\d+(k?m|ft|mi))@(?P<latitude>-?\d+(\.\d+)?),(?P<longitude>-?\d+(\.\d+)?)'
export_format = "{radius}@{latitude},{longitude}"
radius = StringType(regex='\d+(k?m|ft|mi)', required=True)
latitude = FloatType(required=True)
longitude = FloatType(required=True)
class Location(StringModel):
import_format = r'@(?P<latitude>-?\d+(\.\d+)?),(?P<longitude>-?\d+(\.\d+)?)'
export_format = "@{latitude},{longitude}"
latitude = FloatType(required=True)
longitude = FloatType(required=True)
class Place(Model):
class Options:
serialize_when_none = False
scope = ListType(StringType)
exact = ListType(StringType)
class Signal(Model):
class Options:
serialize_when_none = False
id = StringType(required=True)
analysis_from = DateTimeType()
analysis_to = DateTimeType()
analysis_tz = StringType(choices=pytz.all_timezones)
significance = FloatType(min_value=0, max_value=100)
metric = StringType(choices=('demand', 'lead', 'span'))
explain = DateType()
class DateAround(Model):
class Options:
serialize_when_none = False
origin = DateType(required=True)
offset = StringType(regex='\d+d')
scale = StringType(regex='\d+d')
decay = FloatType()
class LocationAround(Model):
class Options:
serialize_when_none = False
origin = StringType(regex='(-?\d+(\.\d+)?),(-?\d+(\.\d+)?)', required=True)
offset = StringType(regex='\d+(\.\d+)?(cm|m|km|in|ft|mi)')
scale = StringType(regex='\d+(\.\d+)?(cm|m|km|in|ft|mi)')
decay = FloatType()
class DateTimeRange(Model):
class Options:
serialize_when_none = False
gt = DateTimeType()
gte = DateTimeType()
lt = DateTimeType()
lte = DateTimeType()
tz = StringType(choices=pytz.all_timezones)
class FloatRange(Model):
class Options:
serialize_when_none = False
gt = FloatType()
gte = FloatType()
lt = FloatType()
lte = FloatType()
class IntRange(Model):
class Options:
serialize_when_none = False
gt = IntType()
gte = IntType()
lt = IntType()
lte = IntType()
class BrandUnsafe(Model):
class Options:
serialize_when_none = False
exclude = BooleanType()
class Entity(Model):
class Options:
serialize_when_none = False
id = StringType()
class LimitMixin(Model):
limit = IntType(min_value=1)
class OffsetMixin(Model):
offset = IntType(min_value=0)
class PaginatedMixin(LimitMixin, OffsetMixin):
pass
class SortableMixin(Model):
sort = ListType(StringType())
class ResultSet(Model):
count = IntType()
previous = URLType()
next = URLType()
@property
def results(self): # pragma: nocover
raise NotImplementedError()
def _parse_params(self, url):
return dict(six.moves.urllib.parse.parse_qsl(six.moves.urllib.parse.urlparse(url).query))
def has_previous(self):
return self.previous is not None
def has_next(self):
return self.next is not None
def get_next(self):
if not self.has_next() or not hasattr(self, '_more'):
return
params = self._parse_params(self.next)
return self._more(**params)
def get_previous(self):
if not self.has_previous() or not hasattr(self, '_more'):
return
params = self._parse_params(self.previous)
return self._more(**params)
def iter_pages(self):
next_page = self
while next_page.has_next():
next_page = next_page.get_next()
yield next_page
def iter_items(self):
return iter(self.results)
def iter_all(self):
for item in self.iter_items():
yield item
for page in self.iter_pages():
for item in page.iter_items():
yield item
def __iter__(self):
return self.iter_items()
class ResultType(SchematicsListType):
def __init__(self, field, *args, **kwargs):
super(ResultType, self).__init__(ModelType(field), *args, **kwargs)