web.py 7.4 KB

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