core.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. demeter core
  5. name:demeter.py
  6. author:rabin
  7. """
  8. import time
  9. import os
  10. import re
  11. import sys
  12. import getopt
  13. import json
  14. import ConfigParser
  15. import subprocess
  16. from tornado.web import Finish
  17. class Demeter(object):
  18. path = ''
  19. config = {}
  20. serviceObj = {}
  21. modelObj = {}
  22. web = ''
  23. request = False
  24. def __new__(self, *args, **kwargs):
  25. print 'error'
  26. sys.exit()
  27. def __init__(self):
  28. pass
  29. @staticmethod
  30. def isset(v):
  31. try :
  32. type (eval(v))
  33. except :
  34. return 0
  35. else :
  36. return 1
  37. @classmethod
  38. def initConfig(self):
  39. self.path = File.path()
  40. if self.config == {}:
  41. name = 'dev'
  42. if 'DEMETER_CONF' in os.environ:
  43. name = os.environ['DEMETER_CONF']
  44. filename = self.path + 'conf/'+name+'.conf'
  45. if File.exists(filename):
  46. config = ConfigParser.ConfigParser()
  47. config.read(filename)
  48. for item in config.sections():
  49. self.config[item] = self.readConfig(config, item)
  50. return True
  51. else:
  52. print filename + ' is not exists'
  53. sys.exit()
  54. @staticmethod
  55. def readConfig(config, type):
  56. value = config.options(type)
  57. result = {}
  58. for item in value:
  59. result[item] = config.get(type, item)
  60. return result
  61. @classmethod
  62. def temp(self, key='', name='', value=''):
  63. temp = Demeter.path + 'conf/temp.conf'
  64. if File.exists(temp):
  65. config = ConfigParser.ConfigParser()
  66. config.read(temp)
  67. if key and name:
  68. config.set(key, name, value)
  69. config.write(open(temp, 'w'))
  70. else:
  71. result = {}
  72. for item in config.sections():
  73. result[item] = self.readConfig(config, item)
  74. return result
  75. @classmethod
  76. def echo(self, args):
  77. module = self.getObject('pprint')
  78. module.pprint(args)
  79. @classmethod
  80. def record(self, key, value):
  81. # 记录日志
  82. # self.log(key, value)
  83. service = self.service('record')
  84. service.push(key, value)
  85. @classmethod
  86. def service(self, name):
  87. if name not in self.serviceObj:
  88. path = 'service.'
  89. if name == 'common':
  90. path = 'demeter.'
  91. name = 'service'
  92. service = self.getClass(name, path)
  93. self.serviceObj[name] = service()
  94. return self.serviceObj[name]
  95. @classmethod
  96. def model(self, table, name='rdb'):
  97. if table not in self.modelObj:
  98. name = self.config['db'][name]
  99. config = self.config[name]
  100. obj = self.getObject('db', 'demeter.')
  101. db = getattr(obj, name.capitalize())
  102. connect = db(config).get()
  103. model = self.getClass(table, 'model.')
  104. self.modelObj[table] = model(name, connect, config)
  105. return self.modelObj[table]
  106. @classmethod
  107. def getClass(self, name, path=''):
  108. obj = self.getObject(name, path)
  109. return getattr(obj, name.capitalize())
  110. @staticmethod
  111. def getObject(name, path = ''):
  112. module = __import__(path + name)
  113. return getattr(module, name)
  114. @staticmethod
  115. def bool(value):
  116. return value == str(True)
  117. @classmethod
  118. def runtime(self, path, file, content=''):
  119. path = self.path + 'runtime/' + path + '/'
  120. File.mkdir(path)
  121. file = path + file
  122. if File.exists(file):
  123. return False
  124. else:
  125. File.write(file, content)
  126. return True
  127. @classmethod
  128. def webstart(self, name):
  129. self.web = name
  130. self.webPath = self.path + self.web + '/'
  131. self.getObject('main', name + '.')
  132. @classmethod
  133. def md5(self, value, salt=False):
  134. module = __import__('md5')
  135. md5 = getattr(module, 'new')
  136. md5_obj = md5()
  137. if salt:
  138. if salt == True:
  139. salt = self.rand()
  140. md5_obj.update(value + salt)
  141. return md5_obj.hexdigest() + '_' + salt
  142. else:
  143. md5_obj.update(value)
  144. return md5_obj.hexdigest()
  145. @staticmethod
  146. def rand(length = 4):
  147. module = __import__('random')
  148. rand = getattr(module, 'randint')
  149. salt = ''
  150. chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
  151. len_chars = len(chars) - 1
  152. for i in xrange(length):
  153. salt += chars[rand(0, len_chars)]
  154. return salt
  155. @staticmethod
  156. def hour(value):
  157. if value < 10:
  158. return '0' + str(value)
  159. return value
  160. @staticmethod
  161. def time():
  162. return int(time.time())
  163. @staticmethod
  164. def mktime(value, string='%Y-%m-%d %H:%M:%S'):
  165. if ' ' in string and ' ' not in value:
  166. value = value + ' 00:00:00'
  167. return int(time.mktime(time.strptime(value,string)))
  168. @staticmethod
  169. def date(value, string='%Y-%m-%d %H:%M:%S'):
  170. module = __import__('datetime')
  171. datetime = getattr(module, 'datetime')
  172. fromtimestamp = getattr(datetime, 'fromtimestamp')
  173. return str(fromtimestamp(value).strftime(string))
  174. @staticmethod
  175. def isJson(value):
  176. result = False
  177. try:
  178. result = json.loads(value)
  179. except ValueError:
  180. return result
  181. return result
  182. @staticmethod
  183. def compressUuid(value):
  184. row = value.replace('-', '')
  185. code = ''
  186. hash = [x for x in "0123456789-abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
  187. for i in xrange(10):
  188. enbin = "%012d" % int(bin(int(row[i * 3] + row[i * 3 + 1] + row[i * 3 + 2], 16))[2:], 10)
  189. code += (hash[int(enbin[0:6], 2)] + hash[int(enbin[6:12], 2)])
  190. return code
  191. @staticmethod
  192. def checkMobile(request):
  193. userAgent = request.headers['User-Agent']
  194. # userAgent = env.get('HTTP_USER_AGENT')
  195. _long_matches = r'googlebot-mobile|android|avantgo|blackberry|blazer|elaine|hiptop|ip(hone|od)|kindle|midp|mmp|mobile|o2|opera mini|palm( os)?|pda|plucker|pocket|psp|smartphone|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce; (iemobile|ppc)|xiino|maemo|fennec'
  196. _long_matches = re.compile(_long_matches, re.IGNORECASE)
  197. _short_matches = r'1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-'
  198. _short_matches = re.compile(_short_matches, re.IGNORECASE)
  199. if _long_matches.search(userAgent) != None:
  200. return True
  201. user_agent = userAgent[0:4]
  202. if _short_matches.search(user_agent) != None:
  203. return True
  204. return False
  205. @classmethod
  206. def error(self, string):
  207. if self.request:
  208. self.request.out(string)
  209. #self.request.finish()
  210. raise Finish()
  211. else:
  212. print string
  213. os._exit(0)
  214. class File(object):
  215. @staticmethod
  216. def write(file, content):
  217. handle = open(file, 'w')
  218. handle.write(content)
  219. handle.close()
  220. Shell.popen('chmod +x ' + file)
  221. @staticmethod
  222. def read(path, name):
  223. handle = open(path + name, 'r')
  224. content = handle.read()
  225. handle.close()
  226. return content
  227. @staticmethod
  228. def cur_path():
  229. return os.path.split(os.path.realpath(__file__))[0] + '/'
  230. @staticmethod
  231. def path():
  232. return os.sys.path[0] + '/'
  233. @staticmethod
  234. def exists(name):
  235. return os.path.exists(name)
  236. @staticmethod
  237. def rename(old, new):
  238. return os.rename(old, new)
  239. @staticmethod
  240. def remove(file):
  241. return os.remove(file)
  242. @staticmethod
  243. def mkdir(path):
  244. if File.exists(path) == False:
  245. os.mkdir(path)
  246. return path
  247. @staticmethod
  248. def mkdirs(path):
  249. if File.exists(path) == False:
  250. os.makedirs(path)
  251. return path
  252. class Shell(object):
  253. @staticmethod
  254. def popen(command, sub=False, bg=False):
  255. string = command
  256. if bg == True:
  257. command = command + ' 1>/dev/null 2>&1 &'
  258. if sub == False:
  259. process = os.popen(command)
  260. output = process.read()
  261. process.close()
  262. return output
  263. else:
  264. popen = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
  265. output = ''
  266. print string
  267. while True:
  268. output = popen.stdout.readline()
  269. print output
  270. if popen.poll() is not None:
  271. break
  272. return output
  273. class Check(object):
  274. @staticmethod
  275. def match(rule, value):
  276. if not rule.match(value):
  277. return False
  278. return True
  279. @staticmethod
  280. def mobile(value):
  281. rule = re.compile(r'1\d{10}')
  282. return Check.match(rule, value)
  283. @staticmethod
  284. def number(value):
  285. try:
  286. int(value)
  287. return True
  288. except ValueError:
  289. return False
  290. Demeter.initConfig()