__base__.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter database
  5. name:__base__.py
  6. author:rabin
  7. """
  8. import os
  9. import uuid
  10. import short_url
  11. import json
  12. import traceback
  13. import uuid
  14. import re
  15. import math
  16. from __sql__ import *
  17. from demeter import *
  18. class Base(object):
  19. __table__ = ''
  20. __comment__ = ''
  21. def __init__(self, type, db, config):
  22. self.db = db
  23. self._type = type
  24. self._config = config
  25. self._table = self._config['prefix'] + '_' + self.__table__
  26. self._set = ''
  27. self._bind = {}
  28. self._attr = {}
  29. self._key = {}
  30. self.create()
  31. def cur(self):
  32. return self.db.cursor()
  33. def query(self, sql, method='select', fetch='fetchall'):
  34. cur = self.cur()
  35. bind = []
  36. if self._set:
  37. for key in self._set:
  38. if self._set[key] == 'time':
  39. self._set[key] = self.time()
  40. elif self._set[key] == 'True':
  41. self._set[key] = True
  42. elif self._set[key] == 'False':
  43. self._set[key] = False
  44. elif 'date' in key:
  45. self._set[key] = self.mktime(self._set[key])
  46. bind.append(self._set[key])
  47. for value in self._key:
  48. if value[0] in self._bind and self._bind[value[0]] != None:
  49. val = self._bind[value[0]]
  50. self._attr[value[0]].unset()
  51. if type(val) == list and val:
  52. for i in val:
  53. bind.append(i)
  54. else:
  55. bind.append(val)
  56. if method == 'select' and ';' in sql:
  57. temp = sql.split(';')
  58. sql = temp[1]
  59. totalSql = temp[0]
  60. cur.execute(totalSql, bind)
  61. Demeter.config['page']['totalNum'] = self.fetch(cur, 'fetchone', 'count')
  62. Demeter.config['page']['total'] = math.ceil(round(float(Demeter.config['page']['totalNum'])/float(Demeter.config['page']['num']),2))
  63. cur.execute(sql, bind)
  64. if method == 'select':
  65. return self.fetch(cur, fetch)
  66. id = True
  67. if method == 'insert':
  68. id = cur.fetchone()[0]
  69. self.db.commit()
  70. self._set = {}
  71. return id
  72. """
  73. try:
  74. except Exception, e:
  75. print e.message
  76. os._exit(0)
  77. """
  78. def fetch(self, cur, type, method = ''):
  79. load = getattr(cur, type)
  80. rows = load()
  81. if type == 'fetchall':
  82. result = []
  83. if rows:
  84. for key in rows:
  85. row = {}
  86. i = 0
  87. for v in key:
  88. row[self._key[i][0]] = v
  89. i = i + 1
  90. result.append(row)
  91. elif method == 'count':
  92. return rows[0]
  93. else:
  94. result = {}
  95. i = 0
  96. if rows:
  97. for key in rows:
  98. if not key:
  99. key = ''
  100. result[self._key[i][0]] = key
  101. i = i + 1
  102. return result
  103. def attr(self, method):
  104. fields = vars(self.__class__)
  105. self._attr = {}
  106. self._bind = {}
  107. self._key = {}
  108. col = (int, str, long, float, unicode, bool, uuid.UUID)
  109. for field in fields:
  110. if isinstance(fields[field], Fields):
  111. self._attr[field] = fields[field]
  112. self._key[field] = self._attr[field].getKey()
  113. insert = (method == 'insert')
  114. if insert and self._attr[field].uuid:
  115. self.setUuid(field, col)
  116. bind = False
  117. val = self._attr[field].getArgv()
  118. if val:
  119. bind = True
  120. else:
  121. val = getattr(self, field)
  122. if isinstance(val, col):
  123. setattr(self, field, self._attr[field])
  124. bind = True
  125. elif insert and self._attr[field].default:
  126. val = self._attr[field].default
  127. bind = True
  128. if val == 'time':
  129. val = self.time()
  130. elif '.' in val:
  131. temp = val.split('.')
  132. val = Demeter.config[temp[0]][temp[1]]
  133. elif method == 'select' and self._attr[field].default and field == 'state':
  134. val = self._attr[field].default
  135. bind = True
  136. if bind and val:
  137. if type(val) == list:
  138. length = len(val)
  139. if length <= 1:
  140. val = val[0]
  141. if insert and self._attr[field].md5:
  142. val = self.createMd5(val)
  143. if self._attr[field].type == 'boolean' and isinstance(val, (str, unicode)):
  144. val = Demeter.bool(val)
  145. self.check(field, val, self._attr[field])
  146. self._bind[field] = val
  147. self._attr[field].val(self._bind[field])
  148. self._attr[field].bind('%s')
  149. self._key = sorted(self._key.items(), key=lambda d:d[1], reverse = False)
  150. Counter().unset()
  151. def check(self, field, val, attr):
  152. if attr.match == 'not':
  153. if not val:
  154. Demeter.error(field + ' not exists')
  155. elif attr.match:
  156. result = re.search(attr.match, val)
  157. if not result:
  158. Demeter.error(field + ' not match:' + attr.match)
  159. def time(self):
  160. module = __import__('time')
  161. time = getattr(module, 'time')
  162. return int(time())
  163. def mktime(self, value):
  164. return Demeter.mktime(value)
  165. def setUuid(self, field, col):
  166. id = getattr(self, self._attr[field].uuid)
  167. if isinstance(id, col):
  168. system = short_url.encode_url(id)
  169. else:
  170. system = self._attr[field].uuid
  171. name = system + '.' + self.__table__
  172. result = uuid.uuid5(uuid.uuid1(), name)
  173. result = str(result)
  174. setattr(self, field, result)
  175. def createMd5(self, value):
  176. return Demeter.md5(value, salt=True)
  177. def createState(self):
  178. create = Demeter.bool(self._config['create'])
  179. if create:
  180. return Demeter.runtime(self._type, self.__table__, json.dumps(self._key))
  181. return False
  182. def drop(self):
  183. return self.handle('drop')
  184. def create(self):
  185. return self.handle('create')
  186. def insert(self):
  187. return self.handle('insert')
  188. def update(self, *args, **kwargs):
  189. if args:
  190. self._set = args[0]
  191. else:
  192. self._set = kwargs
  193. return self.handle('update', set=self._set)
  194. def delete(self):
  195. return self.handle('delete')
  196. def select(self, type='fetchall',col = '*', order = 'cdate desc', group = '', limit = '0,100', page=False):
  197. pageConfig = {}
  198. if page and 'page' in Demeter.config:
  199. pageConfig['current'] = Demeter.config['page']['current']
  200. if page == True:
  201. pageConfig['num'] = 15
  202. elif 'num' in page:
  203. pageConfig['num'] = page['num']
  204. Demeter.config['page']['num'] = pageConfig['num']
  205. return self.handle('select', type=type, col=col, order=order, group=group, limit=limit, page=pageConfig)
  206. def manage(self):
  207. self.attr(method)
  208. return
  209. def handle(self, method='select', type='fetchall', col = '*', order = '', group = '', limit = '0,100', page=False, set = ''):
  210. self.attr(method)
  211. if method == 'create':
  212. create = self.createState()
  213. if create == False:
  214. return False
  215. if type == 'fetchone':
  216. limit = '0,1'
  217. load = getattr(Sql(self._type), method)
  218. return self.query(load(self._table, {'key':self._key, 'fields':self._attr, 'col':col, 'order':order, 'group':group, 'limit':limit, 'page':page, 'set':set, 'table_comment':self.__comment__}), method, type)