storage.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # File : storage.py
  4. # Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
  5. # Date : 2022/9/6
  6. from base.database import db
  7. from functools import lru_cache
  8. class Storage(db.Model):
  9. __tablename__ = 'storage'
  10. id = db.Column(db.Integer, primary_key=True, autoincrement=True)
  11. key = db.Column(db.String(20), unique=True)
  12. value = db.Column(db.UnicodeText())
  13. # value = db.Column(db.Text())
  14. def __repr__(self):
  15. return "<Storage(key='%s', value='%s')>" % (
  16. self.key, self.value)
  17. @classmethod
  18. def setItem(self, key, value=None):
  19. res = db.session.query(self).filter(self.key == key).first()
  20. if res:
  21. res.value = value
  22. db.session.add(res)
  23. else:
  24. res = Storage(key=key, value=value)
  25. db.session.add(res)
  26. db.session.flush()
  27. try:
  28. db.session.commit()
  29. self.clearCache()
  30. return res.id
  31. except Exception as e:
  32. print(f'发生了错误:{e}')
  33. return None
  34. @classmethod
  35. @lru_cache(maxsize=200)
  36. def getItem(self, key, value=''):
  37. res = db.session.query(self).filter(self.key == key).first()
  38. if res:
  39. return res.value or value
  40. else:
  41. return value
  42. @classmethod
  43. @lru_cache(maxsize=200)
  44. def hasItem(self, key):
  45. exists = db.session.query(self).filter(self.key == key).scalar() is not None
  46. # res = db.session.query(self).filter(self.key == key).
  47. if exists:
  48. return True
  49. else:
  50. return False
  51. @classmethod
  52. def clearItem(self, key):
  53. self.clearCache()
  54. res = db.session.query(self).filter(self.key == key).first()
  55. if res:
  56. res.delete()
  57. ret = db.session.commit()
  58. self.clearCache()
  59. return ret
  60. else:
  61. return True
  62. @classmethod
  63. def clearCache(self):
  64. self.getItem.cache_clear()
  65. self.hasItem.cache_clear()