__init__.py 13 KB

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