core.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. # -*- coding: utf-8 -*-
  2. """
  3. demeter
  4. name:core.py
  5. author:rabin
  6. """
  7. import time
  8. import os
  9. import signal
  10. import re
  11. import sys
  12. import json
  13. import subprocess
  14. import importlib
  15. class Demeter(object):
  16. path = ''
  17. root = ''
  18. config = {}
  19. option = {}
  20. web = ''
  21. request = False
  22. route = []
  23. def __new__(self, *args, **kwargs):
  24. sys.exit()
  25. def __init__(self):
  26. pass
  27. @staticmethod
  28. def checkPy3():
  29. if sys.version > '3':
  30. state = True
  31. else:
  32. state = False
  33. return state
  34. @classmethod
  35. def getConfig(self):
  36. state = self.checkPy3()
  37. if state:
  38. import configparser
  39. return configparser.ConfigParser()
  40. else:
  41. import ConfigParser
  42. return ConfigParser.ConfigParser()
  43. @staticmethod
  44. def isset(v):
  45. try :
  46. type (eval(v))
  47. except :
  48. return 0
  49. else :
  50. return 1
  51. @classmethod
  52. def initConfig(self):
  53. self.path = File.path()
  54. self.root = File.cur_path()
  55. if self.config == {}:
  56. filename = self.path + 'conf/'+self.getConfigName()+'.conf'
  57. if File.exists(filename):
  58. config = self.getConfig()
  59. config.read(filename)
  60. for item in config.sections():
  61. self.config[item] = self.readConfig(config, item)
  62. return True
  63. else:
  64. Demeter.echo(filename + ' is not exists')
  65. sys.exit()
  66. @classmethod
  67. def getConfigName(self):
  68. name = 'dev'
  69. if 'DEMETER_CONF' in os.environ:
  70. name = os.environ['DEMETER_CONF']
  71. param = {}
  72. param['config'] = 'c'
  73. self.getopt(param)
  74. if 'config' in self.option and self.option['config']:
  75. name = self.option['config']
  76. return name
  77. @staticmethod
  78. def readConfig(config, type):
  79. value = config.options(type)
  80. result = {}
  81. for item in value:
  82. result[item] = config.get(type, item)
  83. return result
  84. @classmethod
  85. def getopt(self, param = {}):
  86. import getopt
  87. param['help'] = 'h'
  88. shortopts = ''
  89. longopts = []
  90. check = []
  91. for k,v in param.items():
  92. if k == 'help':
  93. shortopts = shortopts + v
  94. else:
  95. shortopts = shortopts + v + ':'
  96. longopts.append(k)
  97. try:
  98. options, args = getopt.getopt(sys.argv[1:], shortopts, longopts)
  99. for name, value in options:
  100. for k,v in param.items():
  101. if name in ('-' + v, '--' + k):
  102. if k == 'help':
  103. self.usage()
  104. else:
  105. self.option[k] = value
  106. except getopt.GetoptError:
  107. #self.usage()
  108. return
  109. @classmethod
  110. def usage(self, name = 'usage'):
  111. file = self.path + name
  112. if not File.exists(file):
  113. file = self.root + name
  114. self.echo(File.read(file))
  115. sys.exit()
  116. @classmethod
  117. def temp(self, key='', name='', value=''):
  118. temp = Demeter.path + 'conf/temp.conf'
  119. if File.exists(temp):
  120. config = self.getConfig()
  121. config.read(temp)
  122. if key and name:
  123. config.set(key, name, value)
  124. config.write(open(temp, 'w'))
  125. else:
  126. result = {}
  127. for item in config.sections():
  128. result[item] = self.readConfig(config, item)
  129. return result
  130. @classmethod
  131. def echo(self, args):
  132. import pprint
  133. pprint.pprint(args)
  134. @classmethod
  135. def record(self, key, value):
  136. # 记录日志
  137. # self.log(key, value)
  138. service = self.service('record')
  139. service.push(key, value)
  140. @classmethod
  141. def service(self, name):
  142. self.initConfig()
  143. path = 'service.'
  144. if name == 'common':
  145. path = 'demeter.'
  146. name = 'service'
  147. service = self.getClass(name, path)
  148. return service()
  149. @classmethod
  150. def adminModel(self, table):
  151. self.initConfig()
  152. config = ('manage_admin', 'manage_log', 'manage_role')
  153. if table in config:
  154. return self.getClass(table, 'demeter.admin.model.')
  155. return False
  156. @classmethod
  157. def model(self, table, name='rdb'):
  158. self.initConfig()
  159. name = self.config['db'][name]
  160. config = self.config[name]
  161. obj = self.getObject('db', 'demeter.')
  162. db = getattr(obj, name.capitalize())
  163. connect = db(config).get()
  164. model = self.adminModel(table)
  165. if not model:
  166. model = self.getClass(table, 'model.')
  167. return model(name, connect, config)
  168. @classmethod
  169. def getMethod(self, module):
  170. import inspect
  171. return inspect.getmembers(module, callable)
  172. @classmethod
  173. def getPackage(self, package):
  174. import pkgutil
  175. for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__, prefix=package.__name__ + '.', onerror=lambda x: None):
  176. yield modname
  177. @staticmethod
  178. def getObject(name, path = ''):
  179. return importlib.import_module(path + name)
  180. """
  181. @classmethod
  182. def getObject(self, name, path = ''):
  183. module = __import__(path + name)
  184. return getattr(module, name)
  185. """
  186. @classmethod
  187. def getClass(self, name, path=''):
  188. obj = self.getObject(name, path)
  189. return getattr(obj, name.capitalize())
  190. @staticmethod
  191. def bool(value, type = 'db'):
  192. if type == 'mysql':
  193. value = value == str(True)
  194. if value == True:
  195. return '1'
  196. else:
  197. return '2'
  198. else:
  199. return value == str(True)
  200. @classmethod
  201. def runtime(self, path, file, content=''):
  202. path = self.path + 'runtime/' + path + '/'
  203. File.mkdir(path)
  204. file = path + file
  205. if File.exists(file):
  206. return False
  207. else:
  208. File.write(file, content)
  209. return True
  210. @classmethod
  211. def webInit(self, name):
  212. self.initConfig()
  213. self.web = name
  214. self.webPath = self.path + self.web + '/'
  215. if self.web == 'admin':
  216. self.webPath = self.root + self.web + '/'
  217. self.getObject('main', name + '.')
  218. @classmethod
  219. def md5(self, value, salt=False):
  220. import hashlib
  221. if salt:
  222. if salt == True:
  223. salt = self.rand()
  224. value = value + salt
  225. return hashlib.md5(value.encode("utf-8")).hexdigest() + '_' + salt
  226. else:
  227. return hashlib.md5(value.encode("utf-8")).hexdigest()
  228. @classmethod
  229. def sha1(self, value, salt=False):
  230. import hashlib
  231. if salt:
  232. if salt == True:
  233. salt = self.rand()
  234. value = value + salt
  235. return hashlib.sha1(value.encode("utf-8")).hexdigest() + '_' + salt
  236. else:
  237. return hashlib.sha1(value.encode("utf-8")).hexdigest()
  238. @classmethod
  239. def rand(self, length = 4):
  240. module = self.getObject('random')
  241. rand = getattr(module, 'randint')
  242. salt = ''
  243. chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
  244. len_chars = len(chars) - 1
  245. for i in range(length):
  246. salt += chars[rand(0, len_chars)]
  247. return salt
  248. @staticmethod
  249. def hour(value):
  250. if value < 10:
  251. return '0' + str(value)
  252. return value
  253. @staticmethod
  254. def time():
  255. return int(time.time())
  256. @staticmethod
  257. def mktime(value, string='%Y-%m-%d %H:%M:%S'):
  258. if ' ' in string and ' ' not in value:
  259. value = value + ' 00:00:00'
  260. return int(time.mktime(time.strptime(value,string)))
  261. @classmethod
  262. def date(self, value, string='%Y-%m-%d %H:%M:%S'):
  263. module = self.getObject('datetime')
  264. datetime = getattr(module, 'datetime')
  265. fromtimestamp = getattr(datetime, 'fromtimestamp')
  266. return str(fromtimestamp(value).strftime(string))
  267. @staticmethod
  268. def isJson(value):
  269. result = False
  270. try:
  271. result = json.loads(value)
  272. except ValueError:
  273. return result
  274. return result
  275. @staticmethod
  276. def compressUuid(value):
  277. row = value.replace('-', '')
  278. code = ''
  279. hash = [x for x in "0123456789-abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
  280. for i in xrange(10):
  281. enbin = "%012d" % int(bin(int(row[i * 3] + row[i * 3 + 1] + row[i * 3 + 2], 16))[2:], 10)
  282. code += (hash[int(enbin[0:6], 2)] + hash[int(enbin[6:12], 2)])
  283. return code
  284. @staticmethod
  285. def checkMobile(request):
  286. if 'Demeter-Mobile' in request.headers:
  287. return True
  288. userAgent = request.headers['User-Agent']
  289. # userAgent = env.get('HTTP_USER_AGENT')
  290. _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'
  291. _long_matches = re.compile(_long_matches, re.IGNORECASE)
  292. _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\-'
  293. _short_matches = re.compile(_short_matches, re.IGNORECASE)
  294. if _long_matches.search(userAgent) != None:
  295. return True
  296. user_agent = userAgent[0:4]
  297. if _short_matches.search(user_agent) != None:
  298. return True
  299. return False
  300. @staticmethod
  301. def exp(exp, value):
  302. if exp:
  303. exp = exp.replace('{n}', value)
  304. value = str(eval(exp))
  305. return value
  306. @classmethod
  307. def curl(self, url = '', param={}, method = 'get'):
  308. import requests
  309. if method == 'get':
  310. req = requests.get(url, params=param)
  311. else:
  312. req = requests.post(url, params=param)
  313. result = req.text
  314. return result
  315. @classmethod
  316. def out(self, msg='', data={}, code=0, callback='', function=''):
  317. if data:
  318. if 'page' in data and data['page']['total'] <= 0:
  319. del data['page']
  320. if 'update' in data and not data['update']:
  321. del data['update']
  322. if 'search' in data and not data['search']:
  323. del data['search']
  324. result = ''
  325. send = {}
  326. send['status'] = 1
  327. send['msg'] = msg
  328. send['data'] = data
  329. send['code'] = code
  330. if not send['data']:
  331. send['status'] = 2
  332. result = json.dumps(send)
  333. if callback:
  334. result = callback + '(' + result + ')'
  335. elif function:
  336. result = '<script>parent.' + function + '(' + result + ')' + '</script>';
  337. return result
  338. @classmethod
  339. def error(self, string):
  340. if self.request:
  341. self.request.out(string)
  342. else:
  343. self.echo(string)
  344. #os._exit(0)
  345. @classmethod
  346. def redis(self):
  347. self.initConfig()
  348. import redis
  349. config = self.config['redis']
  350. pool = redis.ConnectionPool(host=config['host'], port=int(config['port']))
  351. return redis.Redis(connection_pool=pool)
  352. class File(object):
  353. @staticmethod
  354. def write(file, content):
  355. handle = open(file, 'w')
  356. handle.write(content)
  357. handle.close()
  358. Shell.popen('chmod +x ' + file)
  359. @staticmethod
  360. def read(path, name = ''):
  361. handle = open(path + name, 'r')
  362. content = handle.read()
  363. handle.close()
  364. return content
  365. @staticmethod
  366. def readContent(path, name = ''):
  367. content = ''
  368. handle = open(path + name, 'r')
  369. while True:
  370. line = handle.readline()
  371. if line:
  372. line = line.rstrip("\n")
  373. content = content + line
  374. else:
  375. break
  376. handle.close()
  377. return content
  378. @staticmethod
  379. def cur_path():
  380. return os.path.split(os.path.realpath(__file__))[0] + '/'
  381. @staticmethod
  382. def path():
  383. return os.sys.path[0] + '/'
  384. @staticmethod
  385. def exists(name):
  386. return os.path.exists(name)
  387. @staticmethod
  388. def rename(old, new):
  389. return os.rename(old, new)
  390. @staticmethod
  391. def remove(file):
  392. return os.remove(file)
  393. @staticmethod
  394. def mkdir(path):
  395. if File.exists(path) == False:
  396. os.mkdir(path)
  397. return path
  398. @staticmethod
  399. def mkdirs(path):
  400. if File.exists(path) == False:
  401. os.makedirs(path)
  402. return path
  403. @staticmethod
  404. def ext(path):
  405. return os.path.splitext(path)[1]
  406. class Shell(object):
  407. @staticmethod
  408. def popen(command, sub=False, bg=False, timeout=0):
  409. string = command
  410. if bg == True:
  411. command = command + ' 1>/dev/null 2>&1 &'
  412. if timeout > 0:
  413. proc = subprocess.Popen(command,bufsize=0,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True, close_fds=True, preexec_fn = os.setsid)
  414. poll_seconds = .250
  415. deadline = time.time() + timeout
  416. while time.time() < deadline and proc.poll() == None:
  417. time.sleep(poll_seconds)
  418. if proc.poll() == None:
  419. os.killpg(proc.pid, signal.SIGTERM)
  420. return 'timeout'
  421. stdout,stderr = proc.communicate()
  422. return stdout
  423. elif sub == False:
  424. process = os.popen(command)
  425. output = process.read()
  426. process.close()
  427. return output
  428. else:
  429. popen = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
  430. output = ''
  431. Demeter.echo(string)
  432. while True:
  433. output = popen.stdout.readline()
  434. Demeter.echo(output)
  435. if popen.poll() is not None:
  436. break
  437. return output
  438. class Check(object):
  439. @staticmethod
  440. def match(rule, value):
  441. if not rule.match(value):
  442. return False
  443. return True
  444. @staticmethod
  445. def mobile(value):
  446. rule = re.compile(r'1\d{10}')
  447. return Check.match(rule, value)
  448. @staticmethod
  449. def number(value):
  450. try:
  451. int(value)
  452. return True
  453. except ValueError:
  454. return False
  455. @staticmethod
  456. def numberFloat(value):
  457. try:
  458. float(value)
  459. return True
  460. except ValueError:
  461. return False