web.py 8.2 KB

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