__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. # -*- coding: utf-8 -*-
  2. import yaml
  3. import yaml.representer
  4. import datetime
  5. yaml.Dumper.add_representer(unicode, yaml.representer.SafeRepresenter.represent_unicode)
  6. class _YamlUnicodeConstruct(yaml.YAMLObject):
  7. @classmethod
  8. def from_yaml(cls, loader, node):
  9. return cls(**{
  10. k: unicode(v) if isinstance(v, str) else v
  11. for (k, v) in loader.construct_mapping(node, deep = True).items()
  12. })
  13. class Figure(_YamlUnicodeConstruct):
  14. yaml_tag = u"!figure"
  15. def __init__(self, value, unit):
  16. self.value = value
  17. self.unit = unit
  18. def get_value(self):
  19. return self._value
  20. def set_value(self, value):
  21. self._value = value
  22. """ use property() instead of decorator to enable overriding """
  23. value = property(get_value, set_value)
  24. def get_unit(self):
  25. return self._unit
  26. def set_unit(self, unit):
  27. assert type(unit) is unicode
  28. self._unit = unit
  29. """ use property() instead of decorator to enable overriding """
  30. unit = property(get_unit, set_unit)
  31. def __eq__(self, other):
  32. return type(self) == type(other) and self.value == other.value and self.unit == other.unit
  33. def __ne__(self, other):
  34. return not (self == other)
  35. @classmethod
  36. def to_yaml(cls, dumper, figure):
  37. return dumper.represent_mapping(
  38. cls.yaml_tag,
  39. {'unit': figure.get_unit(), 'value': figure.get_value()},
  40. )
  41. class ScalarFigure(Figure):
  42. yaml_tag = u'!scalar'
  43. def get_value(self):
  44. return super(ScalarFigure, self).get_value()
  45. def set_value(self, value):
  46. assert type(value) is float
  47. super(ScalarFigure, self).set_value(value)
  48. """ use property() instead of decorator to enable overriding """
  49. value = property(get_value, set_value)
  50. @classmethod
  51. def from_yaml(cls, loader, node):
  52. attr = loader.construct_scalar(node).split(' ')
  53. return cls(
  54. value = float(attr[0]),
  55. unit = attr[1],
  56. )
  57. @classmethod
  58. def to_yaml(cls, dumper, s):
  59. return dumper.represent_scalar(
  60. cls.yaml_tag,
  61. '%s %s' % (repr(s.value), s.unit),
  62. )
  63. class Distance(ScalarFigure):
  64. yaml_tag = u'!distance'
  65. @property
  66. def metres(self):
  67. if self.unit == 'km':
  68. return self.value * 1000
  69. else:
  70. raise Exception()
  71. class Sum(ScalarFigure):
  72. yaml_tag = u'!sum'
  73. def __init__(self, value, currency):
  74. super(Sum, self).__init__(value, currency)
  75. @property
  76. def currency(self):
  77. return self.unit
  78. def get_unit(self):
  79. return super(Sum, self).get_unit()
  80. def set_unit(self, currency):
  81. if currency == u'€':
  82. currency = u'EUR'
  83. assert type(currency) is unicode
  84. assert currency in [u'EUR']
  85. super(Sum, self).set_unit(currency)
  86. """ use property() instead of decorator to enable overriding """
  87. unit = property(get_unit, set_unit)
  88. @classmethod
  89. def from_yaml(cls, loader, node):
  90. attr = loader.construct_scalar(node).split(' ')
  91. return cls(
  92. value = float(attr[0]),
  93. currency = attr[1],
  94. )
  95. class Discount(yaml.YAMLObject):
  96. yaml_tag = u'!discount'
  97. def __init__(
  98. self,
  99. name = None,
  100. amount = None,
  101. ):
  102. assert type(name) is unicode
  103. self.name = name
  104. assert type(amount) is Sum
  105. assert amount.value >= 0
  106. self.amount = amount
  107. def dict_repr(self):
  108. return {
  109. 'name': self.name,
  110. 'value': self.amount.value,
  111. 'value_currency': self.amount.currency,
  112. }
  113. @staticmethod
  114. def from_dict(attr):
  115. return Discount(
  116. name = attr['name'],
  117. amount = Sum(attr['value'], attr['value_currency']),
  118. )
  119. def __eq__(self, other):
  120. return type(self) == type(other) and self.name == other.name and self.amount == other.amount
  121. def __ne__(self, other):
  122. return not (self == other)
  123. yaml.SafeDumper.add_representer(Discount, lambda dumper, discount: dumper.represent_dict(discount.dict_repr()))
  124. class Order(_YamlUnicodeConstruct):
  125. yaml_tag = u'!order'
  126. def __init__(self, platform, order_id, order_date,
  127. customer_id = None,
  128. items = None,
  129. discounts = None,
  130. ):
  131. assert type(platform) is unicode
  132. self.platform = platform
  133. assert type(order_id) is unicode
  134. self.order_id = order_id
  135. if type(order_date) is datetime.datetime:
  136. order_date = order_date.date()
  137. assert type(order_date) is datetime.date
  138. self.order_date = order_date
  139. assert customer_id is None or type(customer_id) is unicode
  140. self.customer_id = customer_id
  141. if items is None:
  142. items = []
  143. assert type(items) is list
  144. self.items = items
  145. if discounts is None:
  146. discounts = []
  147. assert type(discounts) is list
  148. self.discounts = discounts
  149. def dict_repr(self):
  150. return {k: v for (k, v) in {
  151. 'articles': self.items,
  152. 'customer_id': self.customer_id,
  153. 'discounts': self.discounts,
  154. 'order_date': self.order_date.strftime('%Y-%m-%d'),
  155. 'order_id': self.order_id,
  156. 'platform': self.platform,
  157. }.items() if v is not None}
  158. @staticmethod
  159. def from_dict(attr):
  160. order = Order(
  161. platform = attr['platform'],
  162. order_id = attr['order_id'],
  163. order_date = datetime.datetime.strptime(attr['order_date'], '%Y-%m-%d'),
  164. )
  165. if 'customer_id' in attr:
  166. order.customer_id = attr['customer_id']
  167. for item in attr['articles']:
  168. if type(item) is dict:
  169. item = Item.from_dict(item)
  170. assert isinstance(item, Item)
  171. order.items.append(item)
  172. for discount in attr['discounts']:
  173. if type(discount) is dict:
  174. discount = Discount.from_dict(discount)
  175. assert isinstance(discount, Discount)
  176. order.discounts.append(discount)
  177. return order
  178. def __eq__(self, other):
  179. return (type(self) == type(other)
  180. and vars(self) == vars(other))
  181. def __ne__(self, other):
  182. return not (self == other)
  183. yaml.SafeDumper.add_representer(Order, lambda dumper, order: dumper.represent_dict(order.dict_repr()))
  184. class Item(_YamlUnicodeConstruct):
  185. yaml_tag = u'!item'
  186. def __init__(
  187. self,
  188. name = None,
  189. price_brutto = None,
  190. ):
  191. assert type(name) is unicode
  192. self.name = name
  193. assert type(price_brutto) is Sum
  194. self.price_brutto = price_brutto
  195. def dict_repr(self):
  196. return {
  197. 'name': self.name,
  198. 'price_brutto': self.price_brutto.value,
  199. 'price_brutto_currency': self.price_brutto.currency,
  200. }
  201. @staticmethod
  202. def from_dict(attr):
  203. return Item(
  204. name = attr['name'],
  205. price_brutto = Sum(attr['price_brutto'], attr['price_brutto_currency']),
  206. )
  207. def __eq__(self, other):
  208. return (type(self) == type(other)
  209. and vars(self) == vars(other))
  210. def __ne__(self, other):
  211. return not (self == other)
  212. yaml.SafeDumper.add_representer(Item, lambda dumper, item: dumper.represent_dict(item.dict_repr()))
  213. class Article(Item):
  214. yaml_tag = u'!article'
  215. def __init__(
  216. self,
  217. authors = [],
  218. delivery_date = None,
  219. quantity = None,
  220. reseller = None,
  221. shipper = None,
  222. state = None,
  223. **kwargs
  224. ):
  225. super(Article, self).__init__(**kwargs)
  226. assert type(quantity) is int
  227. self.quantity = quantity
  228. assert type(authors) is list
  229. self.authors = authors
  230. assert state is None or type(state) is unicode
  231. self.state = state
  232. assert reseller is None or type(reseller) is unicode
  233. self.reseller = reseller
  234. assert shipper is None or type(shipper) is unicode
  235. self.shipper = shipper
  236. assert delivery_date is None or type(delivery_date) is datetime.date
  237. self.delivery_date = delivery_date
  238. def dict_repr(self):
  239. attr = super(Article, self).dict_repr()
  240. attr.update({
  241. 'delivery_date': self.delivery_date,
  242. 'quantity': self.quantity,
  243. 'reseller': self.reseller,
  244. 'shipper': self.shipper,
  245. 'state': self.state,
  246. })
  247. if len(self.authors) > 0:
  248. attr['authors'] = self.authors
  249. return attr
  250. yaml.SafeDumper.add_representer(Article, lambda dumper, article: dumper.represent_dict(article.dict_repr()))
  251. class Transportation(Item):
  252. def __init__(
  253. self,
  254. departure_point = None,
  255. destination_point = None,
  256. distance = None,
  257. route_map = None,
  258. **kwargs
  259. ):
  260. super(Transportation, self).__init__(**kwargs)
  261. assert type(departure_point) is unicode
  262. self.departure_point = departure_point
  263. assert type(destination_point) is unicode
  264. self.destination_point = destination_point
  265. assert distance is None or type(distance) is Distance
  266. self.distance = distance
  267. assert route_map is None or type(route_map) is str
  268. self.route_map = route_map
  269. def dict_repr(self):
  270. attr = super(Transportation, self).dict_repr()
  271. attr.update({
  272. 'departure_point': self.departure_point,
  273. 'destination_point': self.destination_point,
  274. 'distance_metres': self.distance.metres if self.distance else None,
  275. 'route_map': self.route_map,
  276. })
  277. return attr
  278. yaml.SafeDumper.add_representer(Transportation, lambda dumper, transportation: dumper.represent_dict(transportation.dict_repr()))
  279. class TaxiRide(Transportation):
  280. def __init__(self, name = None, driver = None, arrival_time = None, departure_time = None, **kwargs):
  281. if name is None:
  282. name = u'Taxi Ride'
  283. super(TaxiRide, self).__init__(name = name, **kwargs)
  284. assert type(driver) is unicode
  285. self.driver = driver
  286. assert arrival_time is None or type(arrival_time) is datetime.datetime
  287. self.arrival_time = arrival_time
  288. assert departure_time is None or type(departure_time) is datetime.datetime
  289. self.departure_time = departure_time
  290. def dict_repr(self):
  291. attr = super(TaxiRide, self).dict_repr()
  292. attr.update({
  293. 'arrival_time': self.arrival_time.strftime('%Y-%m-%d %H:%M') if self.arrival_time else None,
  294. 'departure_time': self.departure_time.strftime('%Y-%m-%d %H:%M') if self.departure_time else None,
  295. 'driver': self.driver,
  296. })
  297. return attr
  298. yaml.SafeDumper.add_representer(TaxiRide, lambda dumper, taxi_ride: dumper.represent_dict(taxi_ride.dict_repr()))