__init__.py 12 KB

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