web.py 7.3 KB

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