core.py 4.9 KB

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