web.py 7.3 KB

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