web.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 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 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. 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 = True
  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()