__init__.py 14 KB

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