demeter.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. service = cls.getClass(name, 'service.')
  67. cls.serviceObj[name] = service()
  68. return cls.serviceObj[name]
  69. @classmethod
  70. def model(cls, table, type='rdb'):
  71. if table not in cls.modelObj:
  72. type = cls.config['db'][type]
  73. config = cls.config[type]
  74. db = cls.getClass(type, 'db.')
  75. connect = db(config).get()
  76. model = cls.getClass(table, 'model.')
  77. cls.modelObj[table] = model(type, 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 path():
  158. return os.path.split(os.path.realpath(__file__))[0] + '/'
  159. @staticmethod
  160. def exists(name):
  161. return os.path.exists(name)
  162. @staticmethod
  163. def rename(old, new):
  164. return os.rename(old, new)
  165. @staticmethod
  166. def remove(file):
  167. return os.remove(file)
  168. @staticmethod
  169. def mkdir(path):
  170. if File.exists(path) == False:
  171. os.mkdir(path)
  172. return path
  173. @staticmethod
  174. def mkdirs(path):
  175. if File.exists(path) == False:
  176. os.makedirs(path)
  177. return path
  178. class Shell(object):
  179. @staticmethod
  180. def popen(command, sub=False, bg=False):
  181. string = command
  182. if bg == True:
  183. command = command + ' 1>/dev/null 2>&1 &'
  184. if sub == False:
  185. process = os.popen(command)
  186. output = process.read()
  187. process.close()
  188. return output
  189. else:
  190. popen = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
  191. output = ''
  192. print string
  193. while True:
  194. output = popen.stdout.readline()
  195. print output
  196. if popen.poll() is not None:
  197. break
  198. return output
  199. Demeter.initConfig()