service.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter service
  5. name:service.py 通用业务
  6. author:rabin
  7. """
  8. from demeter.core import *
  9. class Service(object):
  10. # 获取某个model下的列表数据
  11. def list(self, name, state = True, search=None, page=False, order='cdate desc', limit = '0,100'):
  12. model = self.model(name)
  13. model.state = state
  14. if search:
  15. for key, value in search.items():
  16. if value or value == 0:
  17. if '-' in key:
  18. key = key.split('-')
  19. keyLen = len(key)
  20. if keyLen > 2 and key[2]:
  21. method = key[2]
  22. else:
  23. method = 'assgin'
  24. self.assgin(model, key[0], value, method)
  25. else:
  26. self.assgin(model, key, value)
  27. data = model.select(page=page, order=order, limit=limit)
  28. return data
  29. # 获取某个model下的数据
  30. def one(self, name, **kwd):
  31. model = self.model(name)
  32. if kwd:
  33. for key,value in kwd.items():
  34. self.assgin(model, key, value)
  35. data = model.select(type='fetchone')
  36. return data
  37. # 更新
  38. def update(self, name, id, data, cdate=True):
  39. model = self.model(name)
  40. if id:
  41. model.id = id
  42. if cdate == True and 'cdate' not in data:
  43. data['cdate'] = 'time'
  44. model.update(data)
  45. return id
  46. else:
  47. for key, value in data.items():
  48. method = 'assgin'
  49. if 'date' in key:
  50. method = 'time'
  51. self.assgin(model, key, value, method)
  52. return model.insert()
  53. # 删除
  54. def delete(self, name, id, state = False):
  55. model = self.model(name)
  56. model.id = id
  57. return model.update(state=state)
  58. # 物理删除
  59. def rDelete(self, name, id):
  60. model = self.model(name)
  61. model.id = id
  62. return model.delete()
  63. def model(self, name):
  64. return Demeter.model(name)
  65. def assgin(self, model, key, value, method='assgin'):
  66. if hasattr(model, key):
  67. attr = getattr(model, key)
  68. if hasattr(attr, method):
  69. call = getattr(attr, method)
  70. call(value)