core.py 5.5 KB

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