core.py 4.9 KB

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