models.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # -*- coding: utf-8 -*-
  2. from decimal import Decimal
  3. import json
  4. from . import db
  5. from datetime import datetime
  6. from sqlalchemy.types import TypeDecorator, VARCHAR
  7. from sqlalchemy.ext.mutable import MutableDict
  8. class fakefloat(float):
  9. def __init__(self, value):
  10. self._value = value
  11. def __repr__(self):
  12. return str(self._value)
  13. def defaultencode(o):
  14. if isinstance(o, Decimal):
  15. # Subclass float with custom repr?
  16. return fakefloat(o)
  17. raise TypeError(repr(o) + " is not JSON serializable")
  18. class JSONEncodedDict(TypeDecorator):
  19. "Represents an immutable structure as a json-encoded string."
  20. impl = VARCHAR
  21. def process_bind_param(self, value, dialect):
  22. if value is not None:
  23. value = json.dumps(value, default=defaultencode)
  24. return value
  25. def process_result_value(self, value, dialect):
  26. if value is not None:
  27. value = json.loads(value)
  28. return value
  29. class ISP(db.Model):
  30. id = db.Column(db.Integer, primary_key=True)
  31. name = db.Column(db.String, nullable=False, index=True, unique=True)
  32. shortname = db.Column(db.String(12), index=True, unique=True)
  33. is_ffdn_member = db.Column(db.Boolean, default=False)
  34. is_disabled = db.Column(db.Boolean, default=False) # True = ISP will not appear
  35. url = db.Column(db.String)
  36. last_update_success = db.Column(db.DateTime)
  37. last_update_attempt = db.Column(db.DateTime)
  38. is_updatable = db.Column(db.Boolean, default=True) # set to False to disable JSON-URL updates
  39. tech_email = db.Column(db.String)
  40. cache_info = db.Column(db.Text)
  41. json = db.Column(MutableDict.as_mutable(JSONEncodedDict))
  42. def __init__(self, *args, **kwargs):
  43. super(ISP, self).__init__(*args, **kwargs)
  44. self.json={}
  45. def covered_areas_names(self):
  46. return [c['name'] for c in self.json.get('coveredAreas', [])]
  47. @staticmethod
  48. def str2date(_str):
  49. d=None
  50. try:
  51. d=datetime.strptime(_str, '%Y-%m-%d')
  52. except ValueError:
  53. pass
  54. if d is None:
  55. try:
  56. d=datetime.strptime(_str, '%Y-%m')
  57. except ValueError:
  58. pass
  59. return d
  60. def __repr__(self):
  61. return '<ISP %r>' % (self.shortname if self.shortname else self.name,)