core.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 sys
  11. import getopt
  12. import json
  13. import ConfigParser
  14. import subprocess
  15. class Demeter(object):
  16. path = ''
  17. config = {}
  18. serviceObj = {}
  19. modelObj = {}
  20. web = ''
  21. def __new__(self, *args, **kwargs):
  22. print 'error'
  23. sys.exit()
  24. def __init__(self):
  25. pass
  26. @staticmethod
  27. def isset(v):
  28. try :
  29. type (eval(v))
  30. except :
  31. return 0
  32. else :
  33. return 1
  34. @classmethod
  35. def initConfig(self):
  36. self.path = File.path()
  37. if self.config == {}:
  38. name = 'dev'
  39. if 'DEMETER_CONF' in os.environ:
  40. name = os.environ['DEMETER_CONF']
  41. filename = self.path + 'conf/'+name+'.conf'
  42. if File.exists(filename):
  43. config = ConfigParser.ConfigParser()
  44. config.read(filename)
  45. for item in config.sections():
  46. self.config[item] = self.readConfig(config, item)
  47. return True
  48. else:
  49. print filename + ' is not exists'
  50. sys.exit()
  51. @staticmethod
  52. def readConfig(config, type):
  53. value = config.options(type)
  54. result = {}
  55. for item in value:
  56. result[item] = config.get(type, item)
  57. return result
  58. @classmethod
  59. def temp(self, key='', name='', value=''):
  60. temp = Demeter.path + 'conf/temp.conf'
  61. if File.exists(temp):
  62. config = ConfigParser.ConfigParser()
  63. config.read(temp)
  64. if key and name:
  65. config.set(key, name, value)
  66. config.write(open(temp, 'w'))
  67. else:
  68. result = {}
  69. for item in config.sections():
  70. result[item] = self.readConfig(config, item)
  71. return result
  72. @classmethod
  73. def echo(self, args):
  74. module = self.getObject('pprint')
  75. module.pprint(args)
  76. @classmethod
  77. def record(self, key, value):
  78. # 记录日志
  79. # self.log(key, value)
  80. service = self.service('record')
  81. service.push(key, value)
  82. @classmethod
  83. def service(self, name):
  84. if name not in self.serviceObj:
  85. path = 'service.'
  86. if name == 'common':
  87. path = 'demeter.'
  88. name = 'service'
  89. service = self.getClass(name, path)
  90. self.serviceObj[name] = service()
  91. return self.serviceObj[name]
  92. @classmethod
  93. def model(self, table, name='rdb'):
  94. if table not in self.modelObj:
  95. name = self.config['db'][name]
  96. config = self.config[name]
  97. obj = self.getObject('db', 'demeter.')
  98. db = getattr(obj, name.capitalize())
  99. connect = db(config).get()
  100. model = self.getClass(table, 'model.')
  101. self.modelObj[table] = model(name, connect, config)
  102. return self.modelObj[table]
  103. @classmethod
  104. def getClass(self, name, path=''):
  105. obj = self.getObject(name, path)
  106. return getattr(obj, name.capitalize())
  107. @staticmethod
  108. def getObject(name, path = ''):
  109. module = __import__(path + name)
  110. return getattr(module, name)
  111. @staticmethod
  112. def bool(value):
  113. return value == str(True)
  114. @classmethod
  115. def runtime(self, path, file, content=''):
  116. path = self.path + 'runtime/' + path + '/'
  117. File.mkdir(path)
  118. file = path + file
  119. if File.exists(file):
  120. return False
  121. else:
  122. File.write(file, content)
  123. return True
  124. @classmethod
  125. def webstart(self, name):
  126. self.web = name
  127. self.webPath = self.path + self.web + '/'
  128. self.getObject('main', name + '.')
  129. @classmethod
  130. def md5(self, value, salt=False):
  131. module = __import__('md5')
  132. md5 = getattr(module, 'new')
  133. md5_obj = md5()
  134. if salt:
  135. if salt == True:
  136. salt = self.rand()
  137. md5_obj.update(value + salt)
  138. return md5_obj.hexdigest() + '_' + salt
  139. else:
  140. md5_obj.update(value)
  141. return md5_obj.hexdigest()
  142. @staticmethod
  143. def rand(length = 4):
  144. module = __import__('random')
  145. rand = getattr(module, 'randint')
  146. salt = ''
  147. chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
  148. len_chars = len(chars) - 1
  149. for i in xrange(length):
  150. salt += chars[rand(0, len_chars)]
  151. return salt
  152. @staticmethod
  153. def hour(value):
  154. if value < 10:
  155. return '0' + str(value)
  156. return value
  157. @staticmethod
  158. def time():
  159. return int(time.time())
  160. @staticmethod
  161. def mktime(value, string='%Y-%m-%d %H:%M:%S'):
  162. if ' ' in string and ' ' not in value:
  163. value = value + ' 00:00:00'
  164. return int(time.mktime(time.strptime(value,string)))
  165. @staticmethod
  166. def date(value, string='%Y-%m-%d %H:%M:%S'):
  167. module = __import__('datetime')
  168. datetime = getattr(module, 'datetime')
  169. fromtimestamp = getattr(datetime, 'fromtimestamp')
  170. return str(fromtimestamp(value).strftime(string))
  171. @staticmethod
  172. def isJson(value):
  173. result = False
  174. try:
  175. result = json.loads(value)
  176. except ValueError:
  177. return result
  178. return result
  179. @staticmethod
  180. def compressUuid(value):
  181. row = value.replace('-', '')
  182. code = ''
  183. hash = [x for x in "0123456789-abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
  184. for i in xrange(10):
  185. enbin = "%012d" % int(bin(int(row[i * 3] + row[i * 3 + 1] + row[i * 3 + 2], 16))[2:], 10)
  186. code += (hash[int(enbin[0:6], 2)] + hash[int(enbin[6:12], 2)])
  187. return code
  188. @staticmethod
  189. def error(string):
  190. print string
  191. os._exit(0)
  192. class File(object):
  193. @staticmethod
  194. def write(file, content):
  195. handle = open(file, 'w')
  196. handle.write(content)
  197. handle.close()
  198. Shell.popen('chmod +x ' + file)
  199. @staticmethod
  200. def read(path, name):
  201. handle = open(path + name, 'r')
  202. content = handle.read()
  203. handle.close()
  204. return content
  205. @staticmethod
  206. def cur_path():
  207. return os.path.split(os.path.realpath(__file__))[0] + '/'
  208. @staticmethod
  209. def path():
  210. return os.sys.path[0] + '/'
  211. @staticmethod
  212. def exists(name):
  213. return os.path.exists(name)
  214. @staticmethod
  215. def rename(old, new):
  216. return os.rename(old, new)
  217. @staticmethod
  218. def remove(file):
  219. return os.remove(file)
  220. @staticmethod
  221. def mkdir(path):
  222. if File.exists(path) == False:
  223. os.mkdir(path)
  224. return path
  225. @staticmethod
  226. def mkdirs(path):
  227. if File.exists(path) == False:
  228. os.makedirs(path)
  229. return path
  230. class Shell(object):
  231. @staticmethod
  232. def popen(command, sub=False, bg=False):
  233. string = command
  234. if bg == True:
  235. command = command + ' 1>/dev/null 2>&1 &'
  236. if sub == False:
  237. process = os.popen(command)
  238. output = process.read()
  239. process.close()
  240. return output
  241. else:
  242. popen = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
  243. output = ''
  244. print string
  245. while True:
  246. output = popen.stdout.readline()
  247. print output
  248. if popen.poll() is not None:
  249. break
  250. return output
  251. Demeter.initConfig()