core.py 15 KB

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