setup.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. # -*- coding: utf-8 -*-
  2. """
  3. demeter web
  4. name:application.py
  5. author:rabin
  6. """
  7. from gevent import monkey
  8. monkey.patch_all()
  9. import gevent
  10. import functools
  11. import os
  12. import json
  13. from demeter.core import *
  14. import tornado.web
  15. import tornado.web
  16. import tornado.ioloop
  17. import tornado.httpserver
  18. import tornado.httpclient
  19. import tornado.concurrent
  20. class Base(tornado.web.RequestHandler):
  21. def initialize(self):
  22. try:
  23. Demeter.request = self
  24. self.assign()
  25. self.page()
  26. self.cookie()
  27. self.setting()
  28. except Exception, e:
  29. return
  30. def get_current_user(self):
  31. return self.get_secure_cookie(self.KEYS[0])
  32. def assign(self):
  33. self.data = {}
  34. self.data['setting'] = Demeter.config['setting']
  35. self.data['base'] = Demeter.config['base']
  36. def cookie(self):
  37. for key in self.KEYS:
  38. cookie = None
  39. """
  40. if key in self.data['base']:
  41. cookie = self.data['base'][key]
  42. """
  43. if not cookie:
  44. cookie = self.get_secure_cookie(key)
  45. #cookie = self.get_cookie(key)
  46. if not cookie:
  47. value = self.input(key)
  48. if value:
  49. #self.set_secure_cookie(key, value)
  50. self.data['setting'][key] = value
  51. else:
  52. self.data['setting'][key] = 0
  53. else:
  54. self.data['setting'][key] = cookie
  55. def page(self):
  56. Demeter.config['page'] = {}
  57. page = self.input('page')
  58. if page:
  59. Demeter.config['page']['ajax'] = True
  60. else:
  61. Demeter.config['page']['ajax'] = False
  62. page = 1
  63. Demeter.config['page']['current'] = page
  64. Demeter.config['page']['total'] = 0
  65. self.data['page'] = Demeter.config['page']
  66. def search(self):
  67. data = self.request.arguments
  68. self.data['search'] = {}
  69. self.data['update'] = {}
  70. for key in data:
  71. if 'search_' in key:
  72. index = key.replace('search_', '')
  73. self.data['search'][index] = ",".join(data[key])
  74. if 'update_' in key:
  75. index = key.replace('update_', '')
  76. self.data['update'][index] = ",".join(data[key])
  77. def input(self, key, value=None):
  78. return self.get_argument(key, value)
  79. def inputs(self, key):
  80. return self.get_arguments(key)
  81. def service(self, name):
  82. return Demeter.service(name)
  83. def model(self, name):
  84. return Demeter.model(name)
  85. def common(self, **kwd):
  86. self.data['common'] = kwd
  87. self.data['common']['argvs'] = ''
  88. if 'farm' in self.data['setting'] and self.data['setting']['farm'] > 0:
  89. farm = str(self.data['setting']['farm'])
  90. self.data['common']['argvs'] = '&farm=' + farm + '&search_farm_id-select-=' + farm
  91. def commonView(self, name):
  92. self.view('common/'+name+'.html')
  93. def commonList(self, model, order = 'cdate desc'):
  94. self.data['state'] = self.input('state', True)
  95. self.data['list'] = self.service('common').list(model, state=self.data['state'], search=self.data['search'], page=True, order=order)
  96. def commonOne(self, model, **kwd):
  97. id = self.input('id')
  98. self.data['info'] = {}
  99. if id:
  100. kwd['id'] = id
  101. if kwd:
  102. self.data['info'] = self.service('common').one(model, **kwd)
  103. if not self.data['info'] and 'farm' in self.data['setting'] and self.data['setting']['farm'] > 0:
  104. self.data['info']['farm_id'] = self.data['setting']['farm']
  105. def commonUpdate(self, model, msg='', id=0, **kwd):
  106. if not self.data['auth']:
  107. self.auth()
  108. else:
  109. if id <= 0:
  110. id = self.input('id')
  111. if kwd:
  112. info = self.service('common').one(model, **kwd)
  113. if info and (id != info['id']):
  114. self.out(msg)
  115. return
  116. state = self.service('common').update(model, id, self.data['update'])
  117. self.log(model, 'update', self.data['update'])
  118. self.out('yes', {'id':state})
  119. return state
  120. def commonDelete(self, model):
  121. if not self.data['auth']:
  122. self.auth()
  123. else:
  124. id = self.input('id')
  125. state = self.input('state', False)
  126. state = self.service('common').delete(model, id, state)
  127. self.log(model, 'delete', {id:id, state:state})
  128. self.out('yes', {'state':state})
  129. def log(self, model, method, data):
  130. if 'admin' in self.data['setting'] and self.data['setting']['admin'] > 0:
  131. insert = {}
  132. insert['admin_id'] = self.data['setting']['admin']
  133. insert['model'] = model
  134. insert['method'] = method
  135. insert['data'] = json.dumps(data)
  136. self.service('common').update('manage_log', None, insert)
  137. def view(self, name):
  138. if not self.data['auth']:
  139. self.auth()
  140. else:
  141. config = Demeter.config[Demeter.web]
  142. path = ''
  143. if 'mobile' in config:
  144. mobile = Demeter.checkMobile(self.request)
  145. if mobile:
  146. path = 'mobile/'
  147. else:
  148. path = 'pc/'
  149. self.render(path + name, data=self.data, Demeter=Demeter)
  150. def auth(self):
  151. self.out('您没有权限')
  152. def out(self, msg='', data={}, code=0):
  153. if data:
  154. if 'page' in data and data['page']['total'] <= 0:
  155. del data['page']
  156. if 'update' in data and not data['update']:
  157. del data['update']
  158. if 'search' in data and not data['search']:
  159. del data['search']
  160. callback = self.input('callback')
  161. function = self.input('function')
  162. result = ''
  163. send = {}
  164. send['status'] = 1
  165. send['msg'] = msg
  166. send['data'] = data
  167. send['code'] = code
  168. if not send['data']:
  169. send['status'] = 2
  170. result = json.dumps(send)
  171. if callback:
  172. result = callback + '(' + result + ')'
  173. elif function:
  174. result = '<script>parent.' + function + '(' + result + ')' + '</script>';
  175. self.write(result)
  176. self.finish()
  177. class Web(object):
  178. @classmethod
  179. def auth(self, method):
  180. return tornado.web.authenticated(method)
  181. @classmethod
  182. def setting(self, method):
  183. return self.async(method)
  184. @staticmethod
  185. def async(method):
  186. @tornado.web.asynchronous
  187. @tornado.gen.coroutine
  188. @functools.wraps(method)
  189. def callback(self, *args, **kwargs):
  190. #self._auto_finish = False
  191. try:
  192. result = method(self, *args, **kwargs)
  193. return result
  194. except Exception, e:
  195. print e
  196. return self.out('404')
  197. return self.view('404.html')
  198. #return gevent.spawn(method, self, *args, **kwargs)
  199. return callback
  200. @staticmethod
  201. def file(path):
  202. files = os.listdir(path)
  203. result = []
  204. for key in files:
  205. if '.DS_Store' not in key and '__' not in key and 'pyc' not in key:
  206. key = key.replace('.py', '')
  207. result.append(key)
  208. return result
  209. @staticmethod
  210. def url(module, key, url):
  211. str = dir(module)
  212. for i in str:
  213. act = ''
  214. if '_path' in i:
  215. act = i.replace('_path', '')
  216. if '_html' in i:
  217. act = i.replace('_html', '.html')
  218. if act:
  219. attr = getattr(module, i)
  220. if key == 'main' and act == 'index':
  221. url.append((r'/', attr))
  222. elif key == act or act == 'index':
  223. url.append((r'/'+key, attr))
  224. url.append((r'/'+key+'/'+act, attr))
  225. return url
  226. @staticmethod
  227. def start(url):
  228. config = Demeter.config[Demeter.web]
  229. cookie = False
  230. if 'xsrf_cookies' in config:
  231. cookie = Demeter.bool(config['xsrf_cookies'])
  232. settings = {
  233. "static_path": Demeter.webPath + 'static',
  234. "template_path": Demeter.webPath + 'templates',
  235. "cookie_secret": "61oETzKXQAGaYekL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
  236. "login_url": "/user/login",
  237. "xsrf_cookies": cookie,
  238. "debug": Demeter.bool(config['debug']),
  239. #"autoreload": Demeter.bool(config['autoreload']),
  240. "port": config['port'],
  241. "max_buffer_size": int(config['max_buffer_size']),
  242. "process": int(config['process'])
  243. }
  244. handlers = []
  245. def application_setting():
  246. handlers.append((r"/upload/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/upload/'}))
  247. handlers.append((r"/qrcode/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/qrcode/'}))
  248. handlers.append((r"/camera/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/camera/'}))
  249. handlers.append((r"/static/(.*)", tornado.web.StaticFileHandler, {"path":"static"}))
  250. handlers.append((r"/(apple-touch-icon\.png)", tornado.web.StaticFileHandler, dict(path=settings['static_path'])))
  251. handlers.extend(url)
  252. application_setting()
  253. application = tornado.web.Application(handlers=handlers, **settings)
  254. if settings['debug'] == True:
  255. application.listen(settings['port'])
  256. tornado.ioloop.IOLoop.instance().start()
  257. else:
  258. server = tornado.httpserver.HTTPServer(application, settings['max_buffer_size'])
  259. server.bind(settings['port'])
  260. server.start(settings['process'])
  261. try:
  262. print 'running on port %s' % settings['port']
  263. tornado.ioloop.IOLoop.instance().start()
  264. except KeyboardInterrupt:
  265. tornado.ioloop.IOLoop.instance().stop()