__init__.py 13 KB

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