__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import pytz
  4. import yaml
  5. import yaml.representer
  6. import datetime
  7. yaml.Dumper.add_representer(unicode, yaml.representer.SafeRepresenter.represent_unicode)
  8. yaml.Loader.add_constructor(
  9. u'tag:yaml.org,2002:str',
  10. lambda loader, node: unicode(loader.construct_scalar(node)),
  11. )
  12. def yaml_construct_timestamp(loader, node):
  13. loaded_dt = loader.construct_yaml_timestamp(node)
  14. if type(loaded_dt) is datetime.datetime and loaded_dt.tzinfo is None:
  15. timezone_match = re.search(
  16. ur'\+(?P<h>\d{2}):(?P<m>\d{2})$',
  17. loader.construct_python_unicode(node),
  18. )
  19. if timezone_match:
  20. loaded_dt = loaded_dt.replace(tzinfo = pytz.utc)
  21. return loaded_dt
  22. yaml.Loader.add_constructor(u'tag:yaml.org,2002:timestamp', yaml_construct_timestamp)
  23. class _YamlInitConstructor(yaml.YAMLObject):
  24. @classmethod
  25. def from_yaml(cls, loader, node):
  26. return cls(**loader.construct_mapping(node, deep = True))
  27. # return cls(**{
  28. # k: unicode(v) if isinstance(v, str) else v
  29. # for (k, v) in loader.construct_mapping(node, deep = True).items()
  30. # })
  31. class Figure(_YamlInitConstructor):
  32. yaml_tag = u"!figure"
  33. def __init__(self, value, unit):
  34. self.value = value
  35. self.unit = unit
  36. def get_value(self):
  37. return self._value
  38. def set_value(self, value):
  39. self._value = value
  40. """ use property() instead of decorator to enable overriding """
  41. value = property(get_value, set_value)
  42. def get_unit(self):
  43. return self._unit
  44. def set_unit(self, unit):
  45. assert type(unit) is unicode
  46. self._unit = unit
  47. """ use property() instead of decorator to enable overriding """
  48. unit = property(get_unit, set_unit)
  49. def __eq__(self, other):
  50. return type(self) == type(other) and self.value == other.value and self.unit == other.unit
  51. def __ne__(self, other):
  52. return not (self == other)
  53. @classmethod
  54. def to_yaml(cls, dumper, figure):
  55. return dumper.represent_mapping(
  56. cls.yaml_tag,
  57. {'unit': figure.get_unit(), 'value': figure.get_value()},
  58. )
  59. class ScalarFigure(Figure):
  60. yaml_tag = u'!scalar'
  61. def get_value(self):
  62. return super(ScalarFigure, self).get_value()
  63. def set_value(self, value):
  64. assert type(value) is float
  65. super(ScalarFigure, self).set_value(value)
  66. """ use property() instead of decorator to enable overriding """
  67. value = property(get_value, set_value)
  68. @classmethod
  69. def from_yaml(cls, loader, node):
  70. attr = loader.construct_scalar(node).split(' ')
  71. return cls(
  72. value = float(attr[0]),
  73. unit = attr[1],
  74. )
  75. @classmethod
  76. def to_yaml(cls, dumper, s):
  77. return dumper.represent_scalar(
  78. cls.yaml_tag,
  79. '%s %s' % (repr(s.value), s.unit),
  80. )
  81. class Distance(ScalarFigure):
  82. yaml_tag = u'!distance'
  83. @property
  84. def metres(self):
  85. if self.unit == 'km':
  86. return self.value * 1000
  87. else:
  88. raise Exception()
  89. class Sum(ScalarFigure):
  90. yaml_tag = u'!sum'
  91. def __init__(self, value, currency):
  92. super(Sum, self).__init__(value, currency)
  93. @property
  94. def currency(self):
  95. return self.unit
  96. def get_unit(self):
  97. return super(Sum, self).get_unit()
  98. def set_unit(self, currency):
  99. if currency == u'€':
  100. currency = u'EUR'
  101. if currency == u'US$':
  102. currency = u'USD'
  103. assert type(currency) is unicode
  104. assert currency in [u'EUR', u'USD']
  105. super(Sum, self).set_unit(currency)
  106. """ use property() instead of decorator to enable overriding """
  107. unit = property(get_unit, set_unit)
  108. @classmethod
  109. def from_yaml(cls, loader, node):
  110. attr = loader.construct_scalar(node).split(' ')
  111. return cls(
  112. value = float(attr[0]),
  113. currency = attr[1],
  114. )
  115. class Discount(yaml.YAMLObject):
  116. yaml_tag = u'!discount'
  117. def __init__(
  118. self,
  119. name = None,
  120. amount = None,
  121. ):
  122. assert type(name) is unicode
  123. self.name = name
  124. assert type(amount) is Sum
  125. assert amount.value >= 0
  126. self.amount = amount
  127. def dict_repr(self):
  128. return {
  129. 'name': self.name,
  130. 'value': self.amount.value,
  131. 'value_currency': self.amount.currency,
  132. }
  133. @staticmethod
  134. def from_dict(attr):
  135. return Discount(
  136. name = attr['name'],
  137. amount = Sum(attr['value'], attr['value_currency']),
  138. )
  139. def __eq__(self, other):
  140. return (type(self) == type(other)
  141. and vars(self) == vars(other))
  142. def __ne__(self, other):
  143. return not (self == other)
  144. class Order(_YamlInitConstructor):
  145. yaml_tag = u'!order'
  146. def __init__(self, platform, order_id, order_date,
  147. customer_id = None,
  148. items = None,
  149. discounts = None,
  150. ):
  151. assert type(platform) is unicode
  152. self.platform = platform
  153. if type(order_id) in [int]:
  154. order_id = unicode(order_id)
  155. assert type(order_id) is unicode
  156. self.order_id = order_id
  157. if type(order_date) is datetime.datetime:
  158. order_date = order_date.date()
  159. assert type(order_date) is datetime.date
  160. self.order_date = order_date
  161. if customer_id is not None:
  162. assert type(customer_id) is unicode
  163. self.customer_id = customer_id
  164. if items is None:
  165. self.items = []
  166. else:
  167. assert type(items) is list
  168. assert all([isinstance(i, Item) for i in items])
  169. self.items = items
  170. if discounts is None:
  171. self.discounts = []
  172. else:
  173. assert type(discounts) is list
  174. assert all([isinstance(d, Discount) for d in discounts])
  175. self.discounts = discounts
  176. def __eq__(self, other):
  177. return (type(self) == type(other)
  178. and vars(self) == vars(other))
  179. def __ne__(self, other):
  180. return not (self == other)
  181. class Item(_YamlInitConstructor):
  182. yaml_tag = u'!item'
  183. def __init__(
  184. self,
  185. name = None,
  186. price_brutto = None,
  187. ):
  188. assert type(name) is unicode
  189. self.name = name
  190. assert type(price_brutto) is Sum
  191. self.price_brutto = price_brutto
  192. def __eq__(self, other):
  193. return (type(self) == type(other)
  194. and vars(self) == vars(other))
  195. def __ne__(self, other):
  196. return not (self == other)
  197. class Article(Item):
  198. yaml_tag = u'!article'
  199. def __init__(
  200. self,
  201. authors = None,
  202. color = None,
  203. delivery_date = None,
  204. depth = None,
  205. features = None,
  206. height = None,
  207. maximum_load = None,
  208. option = None,
  209. product_id = None,
  210. quantity = None,
  211. reseller = None,
  212. shipper = None,
  213. size = None,
  214. state = None,
  215. width = None,
  216. **kwargs
  217. ):
  218. super(Article, self).__init__(**kwargs)
  219. assert type(quantity) is int
  220. self.quantity = quantity
  221. if authors is not None:
  222. assert type(authors) is list
  223. self.authors = authors
  224. if state is not None:
  225. assert type(state) is unicode
  226. self.state = state
  227. if reseller is not None:
  228. assert type(reseller) is unicode
  229. self.reseller = reseller
  230. if shipper is not None:
  231. assert type(shipper) is unicode
  232. self.shipper = shipper
  233. if product_id is not None:
  234. if type(product_id) in [int]:
  235. product_id = unicode(product_id)
  236. assert type(product_id) is unicode
  237. self.product_id = product_id
  238. if option is not None:
  239. assert type(option) is unicode
  240. self.option = option
  241. if color is not None:
  242. assert type(color) is unicode
  243. self.color = color
  244. if size is not None:
  245. assert type(size) is unicode
  246. self.size = size
  247. if width is not None:
  248. assert type(width) is ScalarFigure
  249. self.width = width
  250. if depth is not None:
  251. assert type(depth) is ScalarFigure
  252. self.depth = depth
  253. if height is not None:
  254. assert type(height) is ScalarFigure
  255. self.height = height
  256. if maximum_load is not None:
  257. assert type(maximum_load) is ScalarFigure
  258. self.maximum_load = maximum_load
  259. if features is not None:
  260. assert type(features) is unicode
  261. self.features = features
  262. assert delivery_date is None or type(delivery_date) is datetime.date
  263. self.delivery_date = delivery_date
  264. class Transportation(Item):
  265. yaml_tag = u'!transportation'
  266. def __init__(
  267. self,
  268. departure_point = None,
  269. destination_point = None,
  270. distance = None,
  271. passenger = None,
  272. route_map = None,
  273. ticket_url = None,
  274. valid_from = None,
  275. valid_until = None,
  276. **kwargs
  277. ):
  278. super(Transportation, self).__init__(**kwargs)
  279. if departure_point is not None:
  280. assert type(departure_point) is unicode
  281. self.departure_point = departure_point
  282. if destination_point is not None:
  283. assert type(destination_point) is unicode
  284. self.destination_point = destination_point
  285. if distance is not None:
  286. assert type(distance) is Distance
  287. self.distance = distance
  288. if route_map is not None:
  289. assert type(route_map) is str
  290. self.route_map = route_map
  291. if passenger is not None:
  292. assert type(passenger) is Person
  293. self.passenger = passenger
  294. if valid_from is not None:
  295. assert type(valid_from) is datetime.datetime
  296. assert not valid_from.tzinfo is None
  297. self.valid_from = valid_from
  298. if valid_until is not None:
  299. assert type(valid_until) is datetime.datetime
  300. assert not valid_until.tzinfo is None
  301. self.valid_until = valid_until
  302. if ticket_url is not None:
  303. assert type(ticket_url) is unicode
  304. self.ticket_url = ticket_url
  305. def dict_repr(self):
  306. attr = super(Transportation, self).dict_repr()
  307. attr.update({
  308. 'departure_point': self.departure_point,
  309. 'destination_point': self.destination_point,
  310. 'distance_metres': self.distance.metres if self.distance else None,
  311. 'route_map': self.route_map,
  312. })
  313. return attr
  314. class TaxiRide(Transportation):
  315. yaml_tag = u'!taxi-ride'
  316. def __init__(
  317. self,
  318. arrival_time = None,
  319. departure_time = None,
  320. driver = None,
  321. name = None,
  322. **kwargs
  323. ):
  324. if name is None:
  325. name = u'Taxi Ride'
  326. super(TaxiRide, self).__init__(name = name, **kwargs)
  327. assert type(driver) is unicode
  328. self.driver = driver
  329. assert arrival_time is None or type(arrival_time) is datetime.datetime
  330. self.arrival_time = arrival_time
  331. assert departure_time is None or type(departure_time) is datetime.datetime
  332. self.departure_time = departure_time
  333. def dict_repr(self):
  334. attr = super(TaxiRide, self).dict_repr()
  335. attr.update({
  336. 'arrival_time': self.arrival_time.strftime('%Y-%m-%d %H:%M') if self.arrival_time else None,
  337. 'departure_time': self.departure_time.strftime('%Y-%m-%d %H:%M') if self.departure_time else None,
  338. 'driver': self.driver,
  339. })
  340. return attr
  341. class OrderRegistry(yaml.YAMLObject):
  342. yaml_tag = u'!order-registry'
  343. def __init__(self):
  344. self.registry = {}
  345. def register(self, order):
  346. assert isinstance(order, Order)
  347. if not order.platform in self.registry:
  348. self.registry[order.platform] = {}
  349. self.registry[order.platform][order.order_id] = order
  350. @classmethod
  351. def to_yaml(cls, dumper, self):
  352. return dumper.represent_mapping(cls.yaml_tag, self.registry)
  353. @classmethod
  354. def from_yaml(cls, loader, node):
  355. self = cls()
  356. self.registry = loader.construct_mapping(node)
  357. return self
  358. def __eq__(self, other):
  359. return type(self) == type(other) and vars(self) == vars(other)
  360. def __ne__(self, other):
  361. return not self == other
  362. class Person(_YamlInitConstructor):
  363. yaml_tag = u'!person'
  364. def __init__(self, first_name = None, last_name = None):
  365. self.first_name = first_name
  366. self.last_name = last_name
  367. @property
  368. def first_name(self):
  369. return self._first_name
  370. @first_name.setter
  371. def first_name(self, first_name):
  372. assert first_name is None or type(first_name) is unicode
  373. self._first_name = first_name
  374. @property
  375. def last_name(self):
  376. return self._last_name
  377. @last_name.setter
  378. def last_name(self, last_name):
  379. assert last_name is None or type(last_name) is unicode
  380. self._last_name = last_name
  381. @classmethod
  382. def to_yaml(cls, dumper, person):
  383. return dumper.represent_mapping(cls.yaml_tag, {
  384. 'first_name': person.first_name,
  385. 'last_name': person.last_name,
  386. })
  387. def __eq__(self, other):
  388. return type(self) == type(other) and vars(self) == vars(other)
  389. def __ne__(self, other):
  390. return not self == other
  391. def __repr__(self):
  392. return self.__class__.__name__ + '(%s)' % ', '.join([
  393. '%s=%r' % (k, v) for k, v in vars(self).items()
  394. ])