core.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 hour(value):
  146. if value < 10:
  147. return '0' + str(value)
  148. return value
  149. @staticmethod
  150. def time():
  151. return int(time.time())
  152. @staticmethod
  153. def mktime(value, string='%Y-%m-%d %H:%M:%S'):
  154. return int(time.mktime(time.strptime(value,string)))
  155. @staticmethod
  156. def date(value, string='%Y-%m-%d %H:%M:%S'):
  157. module = __import__('datetime')
  158. datetime = getattr(module, 'datetime')
  159. fromtimestamp = getattr(datetime, 'fromtimestamp')
  160. return str(fromtimestamp(value).strftime(string))
  161. @staticmethod
  162. def isJson(value):
  163. result = False
  164. try:
  165. result = json.loads(value)
  166. except ValueError:
  167. return result
  168. return result
  169. @staticmethod
  170. def error(string):
  171. print string
  172. os._exit(0)
  173. class File(object):
  174. @staticmethod
  175. def write(file, content):
  176. handle = open(file, 'w')
  177. handle.write(content)
  178. handle.close()
  179. Shell.popen('chmod +x ' + file)
  180. @staticmethod
  181. def read(path, name):
  182. handle = open(path + name, 'r')
  183. content = handle.read()
  184. handle.close()
  185. return content
  186. @staticmethod
  187. def cur_path():
  188. return os.path.split(os.path.realpath(__file__))[0] + '/'
  189. @staticmethod
  190. def path():
  191. return os.sys.path[0] + '/'
  192. @staticmethod
  193. def exists(name):
  194. return os.path.exists(name)
  195. @staticmethod
  196. def rename(old, new):
  197. return os.rename(old, new)
  198. @staticmethod
  199. def remove(file):
  200. return os.remove(file)
  201. @staticmethod
  202. def mkdir(path):
  203. if File.exists(path) == False:
  204. os.mkdir(path)
  205. return path
  206. @staticmethod
  207. def mkdirs(path):
  208. if File.exists(path) == False:
  209. os.makedirs(path)
  210. return path
  211. class Shell(object):
  212. @staticmethod
  213. def popen(command, sub=False, bg=False):
  214. string = command
  215. if bg == True:
  216. command = command + ' 1>/dev/null 2>&1 &'
  217. if sub == False:
  218. process = os.popen(command)
  219. output = process.read()
  220. process.close()
  221. return output
  222. else:
  223. popen = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
  224. output = ''
  225. print string
  226. while True:
  227. output = popen.stdout.readline()
  228. print output
  229. if popen.poll() is not None:
  230. break
  231. return output
  232. Demeter.initConfig()