__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. def __ne__(self, other):
  32. return not (self == other)
  33. class Figure(_YamlInitConstructor):
  34. yaml_tag = u"!figure"
  35. def __init__(self, value, unit):
  36. self.value = value
  37. self.unit = unit
  38. def get_value(self):
  39. return self._value
  40. def set_value(self, value):
  41. self._value = value
  42. """ use property() instead of decorator to enable overriding """
  43. value = property(get_value, set_value)
  44. def get_unit(self):
  45. return self._unit
  46. def set_unit(self, unit):
  47. assert type(unit) is unicode
  48. self._unit = unit
  49. """ use property() instead of decorator to enable overriding """
  50. unit = property(get_unit, set_unit)
  51. def __eq__(self, other):
  52. return type(self) == type(other) and self.value == other.value and self.unit == other.unit
  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(_YamlInitConstructor):
  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 __eq__(self, other):
  128. return (type(self) == type(other)
  129. and vars(self) == vars(other))
  130. class Order(_YamlInitConstructor):
  131. yaml_tag = u'!order'
  132. def __init__(self, platform, order_id, order_date,
  133. customer_id = None,
  134. items = None,
  135. discounts = None,
  136. ):
  137. assert type(platform) is unicode
  138. self.platform = platform
  139. if type(order_id) in [int]:
  140. order_id = unicode(order_id)
  141. assert type(order_id) is unicode
  142. self.order_id = order_id
  143. if type(order_date) is datetime.datetime:
  144. order_date = order_date.date()
  145. assert type(order_date) is datetime.date
  146. self.order_date = order_date
  147. if customer_id is not None:
  148. assert type(customer_id) is unicode
  149. self.customer_id = customer_id
  150. if items is None:
  151. self.items = []
  152. else:
  153. assert type(items) is list
  154. assert all([isinstance(i, Item) for i in items])
  155. self.items = items
  156. if discounts is None:
  157. self.discounts = []
  158. else:
  159. assert type(discounts) is list
  160. assert all([isinstance(d, Discount) for d in discounts])
  161. self.discounts = discounts
  162. def __eq__(self, other):
  163. return (type(self) == type(other)
  164. and vars(self) == vars(other))
  165. class Item(_YamlInitConstructor):
  166. yaml_tag = u'!item'
  167. def __init__(
  168. self,
  169. name = None,
  170. price_brutto = None,
  171. ):
  172. assert type(name) is unicode
  173. self.name = name
  174. assert type(price_brutto) is Sum
  175. self.price_brutto = price_brutto
  176. def __eq__(self, other):
  177. return (type(self) == type(other)
  178. and vars(self) == vars(other))
  179. class Article(Item):
  180. yaml_tag = u'!article'
  181. def __init__(
  182. self,
  183. authors = None,
  184. color = None,
  185. delivery_date = None,
  186. depth = None,
  187. features = None,
  188. height = None,
  189. maximum_load = None,
  190. option = None,
  191. product_id = None,
  192. quantity = None,
  193. reseller = None,
  194. shipper = None,
  195. size = None,
  196. state = None,
  197. width = None,
  198. **kwargs
  199. ):
  200. super(Article, self).__init__(**kwargs)
  201. assert type(quantity) is int
  202. self.quantity = quantity
  203. if authors is not None:
  204. assert type(authors) is list
  205. self.authors = authors
  206. if state is not None:
  207. assert type(state) is unicode
  208. self.state = state
  209. if reseller is not None:
  210. assert type(reseller) is unicode
  211. self.reseller = reseller
  212. if shipper is not None:
  213. assert type(shipper) is unicode
  214. self.shipper = shipper
  215. if product_id is not None:
  216. if type(product_id) in [int]:
  217. product_id = unicode(product_id)
  218. assert type(product_id) is unicode
  219. self.product_id = product_id
  220. if option is not None:
  221. assert type(option) is unicode
  222. self.option = option
  223. if color is not None:
  224. assert type(color) is unicode
  225. self.color = color
  226. if size is not None:
  227. assert type(size) is unicode
  228. self.size = size
  229. if width is not None:
  230. assert type(width) is ScalarFigure
  231. self.width = width
  232. if depth is not None:
  233. assert type(depth) is ScalarFigure
  234. self.depth = depth
  235. if height is not None:
  236. assert type(height) is ScalarFigure
  237. self.height = height
  238. if maximum_load is not None:
  239. assert type(maximum_load) is ScalarFigure
  240. self.maximum_load = maximum_load
  241. if features is not None:
  242. assert type(features) is unicode
  243. self.features = features
  244. assert delivery_date is None or type(delivery_date) is datetime.date
  245. self.delivery_date = delivery_date
  246. class Transportation(Item):
  247. yaml_tag = u'!transportation'
  248. def __init__(
  249. self,
  250. departure_point = None,
  251. destination_point = None,
  252. distance = None,
  253. passenger = None,
  254. route_map = None,
  255. ticket_url = None,
  256. valid_from = None,
  257. valid_until = None,
  258. **kwargs
  259. ):
  260. super(Transportation, self).__init__(**kwargs)
  261. if departure_point is not None:
  262. assert type(departure_point) is unicode
  263. self.departure_point = departure_point
  264. if destination_point is not None:
  265. assert type(destination_point) is unicode
  266. self.destination_point = destination_point
  267. if distance is not None:
  268. assert type(distance) is Distance
  269. self.distance = distance
  270. if route_map is not None:
  271. assert type(route_map) is str
  272. self.route_map = route_map
  273. if passenger is not None:
  274. assert type(passenger) is Person
  275. self.passenger = passenger
  276. if valid_from is not None:
  277. assert type(valid_from) is datetime.datetime
  278. assert not valid_from.tzinfo is None
  279. self.valid_from = valid_from
  280. if valid_until is not None:
  281. assert type(valid_until) is datetime.datetime
  282. assert not valid_until.tzinfo is None
  283. self.valid_until = valid_until
  284. if ticket_url is not None:
  285. assert type(ticket_url) is unicode
  286. self.ticket_url = ticket_url
  287. class TaxiRide(Transportation):
  288. yaml_tag = u'!taxi-ride'
  289. def __init__(
  290. self,
  291. arrival_time = None,
  292. departure_time = None,
  293. driver = None,
  294. name = None,
  295. **kwargs
  296. ):
  297. if name is None:
  298. name = u'Taxi Ride'
  299. super(TaxiRide, self).__init__(name = name, **kwargs)
  300. assert type(driver) is unicode
  301. self.driver = driver
  302. assert arrival_time is None or type(arrival_time) is datetime.datetime
  303. self.arrival_time = arrival_time
  304. assert departure_time is None or type(departure_time) is datetime.datetime
  305. self.departure_time = departure_time
  306. class OrderRegistry(yaml.YAMLObject):
  307. yaml_tag = u'!order-registry'
  308. def __init__(self):
  309. self.registry = {}
  310. def register(self, order):
  311. assert isinstance(order, Order)
  312. if not order.platform in self.registry:
  313. self.registry[order.platform] = {}
  314. self.registry[order.platform][order.order_id] = order
  315. @classmethod
  316. def to_yaml(cls, dumper, self):
  317. return dumper.represent_mapping(cls.yaml_tag, self.registry)
  318. @classmethod
  319. def from_yaml(cls, loader, node):
  320. self = cls()
  321. self.registry = loader.construct_mapping(node)
  322. return self
  323. def __eq__(self, other):
  324. return type(self) == type(other) and vars(self) == vars(other)
  325. class Person(_YamlInitConstructor):
  326. yaml_tag = u'!person'
  327. def __init__(self, first_name = None, last_name = None):
  328. self.first_name = first_name
  329. self.last_name = last_name
  330. @property
  331. def first_name(self):
  332. return self._first_name
  333. @first_name.setter
  334. def first_name(self, first_name):
  335. assert first_name is None or type(first_name) is unicode
  336. self._first_name = first_name
  337. @property
  338. def last_name(self):
  339. return self._last_name
  340. @last_name.setter
  341. def last_name(self, last_name):
  342. assert last_name is None or type(last_name) is unicode
  343. self._last_name = last_name
  344. @classmethod
  345. def to_yaml(cls, dumper, person):
  346. return dumper.represent_mapping(cls.yaml_tag, {
  347. 'first_name': person.first_name,
  348. 'last_name': person.last_name,
  349. })
  350. def __eq__(self, other):
  351. return type(self) == type(other) and vars(self) == vars(other)
  352. def __repr__(self):
  353. return self.__class__.__name__ + '(%s)' % ', '.join([
  354. '%s=%r' % (k, v) for k, v in vars(self).items()
  355. ])