__init__.py 15 KB

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