__init__.py 15 KB

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