web.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 id:
  105. id = int(id)
  106. if info and (id != info['id']):
  107. self.out(msg)
  108. return
  109. state = self.service('common').update(model, id, self.data['update'])
  110. self.log(model, 'update', self.data['update'])
  111. self.out('yes', {'id':state})
  112. return state
  113. def commonDelete(self, model):
  114. if not self.data['auth']:
  115. self.auth()
  116. else:
  117. id = self.input('id')
  118. state = self.input('state', False)
  119. state = self.service('common').delete(model, id, state)
  120. self.log(model, 'delete', {id:id, state:state})
  121. self.out('yes', {'state':state})
  122. def log(self, model, method, data):
  123. if 'admin' in self.data['setting'] and self.data['setting']['admin'] > 0:
  124. insert = {}
  125. insert['admin_id'] = self.data['setting']['admin']
  126. insert['model'] = model
  127. insert['method'] = method
  128. insert['data'] = json.dumps(data)
  129. self.service('common').update('manage_log', None, insert)
  130. def view(self, name):
  131. if not self.data['auth']:
  132. self.auth()
  133. else:
  134. config = Demeter.config[Demeter.web]
  135. path = ''
  136. if 'mobile' in config:
  137. mobile = Demeter.checkMobile(self.request)
  138. if mobile:
  139. path = 'mobile/'
  140. else:
  141. path = 'pc/'
  142. self.render(path + name, data=self.data, Demeter=Demeter)
  143. def auth(self):
  144. self.out('您没有权限')
  145. def out(self, msg='', data={}, code=0):
  146. if data:
  147. if 'page' in data and data['page']['total'] <= 0:
  148. del data['page']
  149. if 'update' in data and not data['update']:
  150. del data['update']
  151. if 'search' in data and not data['search']:
  152. del data['search']
  153. callback = self.input('callback')
  154. function = self.input('function')
  155. result = ''
  156. send = {}
  157. send['status'] = 1
  158. send['msg'] = msg
  159. send['data'] = data
  160. send['code'] = code
  161. if not send['data']:
  162. send['status'] = 2
  163. result = json.dumps(send)
  164. if callback:
  165. result = callback + '(' + result + ')'
  166. elif function:
  167. result = '<script>parent.' + function + '(' + result + ')' + '</script>';
  168. self.write(result)
  169. self.finish()
  170. class Web(object):
  171. @staticmethod
  172. def auth(method):
  173. return tornado.web.authenticated(method)
  174. @staticmethod
  175. def file(path):
  176. files = os.listdir(path)
  177. result = []
  178. for key in files:
  179. if '.DS_Store' not in key and '__' not in key and 'pyc' not in key:
  180. key = key.replace('.py', '')
  181. result.append(key)
  182. return result
  183. @staticmethod
  184. def url(module, key, url):
  185. str = dir(module)
  186. for i in str:
  187. act = ''
  188. if '_path' in i:
  189. act = i.replace('_path', '')
  190. if '_html' in i:
  191. act = i.replace('_html', '.html')
  192. if act:
  193. attr = getattr(module, i)
  194. if key == 'main' and act == 'index':
  195. url.append((r'/', attr))
  196. elif key == act or act == 'index':
  197. url.append((r'/'+key, attr))
  198. url.append((r'/'+key+'/'+act, attr))
  199. return url
  200. @staticmethod
  201. def start(url):
  202. config = Demeter.config[Demeter.web]
  203. settings = {
  204. "static_path": Demeter.webPath + 'static',
  205. "template_path": Demeter.webPath + 'templates',
  206. "cookie_secret": "61oETzKXQAGaYekL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
  207. "login_url": "/user/login",
  208. "xsrf_cookies": True,
  209. "debug": Demeter.bool(config['debug']),
  210. #"autoreload": Demeter.bool(config['autoreload']),
  211. "port": config['port'],
  212. "max_buffer_size": int(config['max_buffer_size']),
  213. "process": int(config['process'])
  214. }
  215. handlers = []
  216. def application_setting():
  217. handlers.append((r"/upload/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/upload/'}))
  218. handlers.append((r"/qrcode/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/qrcode/'}))
  219. handlers.append((r"/camera/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/camera/'}))
  220. handlers.append((r"/static/(.*)", tornado.web.StaticFileHandler, {"path":"static"}))
  221. handlers.append((r"/(apple-touch-icon\.png)", tornado.web.StaticFileHandler, dict(path=settings['static_path'])))
  222. handlers.extend(url)
  223. application_setting()
  224. application = tornado.web.Application(handlers=handlers, **settings)
  225. if settings['debug'] == True:
  226. application.listen(settings['port'])
  227. tornado.ioloop.IOLoop.instance().start()
  228. else:
  229. server = tornado.httpserver.HTTPServer(application, settings['max_buffer_size'])
  230. server.bind(settings['port'])
  231. server.start(settings['process'])
  232. try:
  233. print 'running on port %s' % settings['port']
  234. tornado.ioloop.IOLoop.instance().start()
  235. except KeyboardInterrupt:
  236. tornado.ioloop.IOLoop.instance().stop()