core.py 5.0 KB

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