web.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. self.render(name, data=self.data, Demeter=Demeter)
  134. def auth(self):
  135. self.out('您没有权限')
  136. def out(self, msg='', data={}, code=0):
  137. if data:
  138. if 'page' in data and data['page']['total'] <= 0:
  139. del data['page']
  140. if 'update' in data and not data['update']:
  141. del data['update']
  142. if 'search' in data and not data['search']:
  143. del data['search']
  144. callback = self.input('callback')
  145. function = self.input('function')
  146. result = ''
  147. send = {}
  148. send['status'] = 1
  149. send['msg'] = msg
  150. send['data'] = data
  151. send['code'] = code
  152. if not send['data']:
  153. send['status'] = 2
  154. result = json.dumps(send)
  155. if callback:
  156. result = callback + '(' + result + ')'
  157. elif function:
  158. result = '<script>parent.' + function + '(' + result + ')' + '</script>';
  159. self.write(result)
  160. #self.finish(result)
  161. class Web(object):
  162. @staticmethod
  163. def auth(method):
  164. return tornado.web.authenticated(method)
  165. @staticmethod
  166. def file(path):
  167. files = os.listdir(path)
  168. result = []
  169. for key in files:
  170. if '.DS_Store' not in key and '__' not in key and 'pyc' not in key:
  171. key = key.replace('.py', '')
  172. result.append(key)
  173. return result
  174. @staticmethod
  175. def url(module, key, url):
  176. str = dir(module)
  177. for i in str:
  178. act = ''
  179. if '_path' in i:
  180. act = i.replace('_path', '')
  181. if '_html' in i:
  182. act = i.replace('_html', '.html')
  183. if act:
  184. attr = getattr(module, i)
  185. if key == 'main' and act == 'index':
  186. url.append((r'/', attr))
  187. elif key == act or act == 'index':
  188. url.append((r'/'+key, attr))
  189. url.append((r'/'+key+'/'+act, attr))
  190. return url
  191. @staticmethod
  192. def start(url):
  193. config = Demeter.config[Demeter.web]
  194. settings = {
  195. "static_path": Demeter.webPath + 'static',
  196. "template_path": Demeter.webPath + 'templates',
  197. "cookie_secret": "61oETzKXQAGaYekL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
  198. "login_url": "/user/login",
  199. "xsrf_cookies": True,
  200. "debug": Demeter.bool(config['debug']),
  201. #"autoreload": Demeter.bool(config['autoreload']),
  202. "port": config['port'],
  203. "max_buffer_size": int(config['max_buffer_size']),
  204. "process": int(config['process'])
  205. }
  206. handlers = []
  207. def application_setting():
  208. handlers.append((r"/upload/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/upload/'}))
  209. handlers.append((r"/camera/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/camera/'}))
  210. handlers.append((r"/static/(.*)", tornado.web.StaticFileHandler, {"path":"static"}))
  211. handlers.append((r"/(apple-touch-icon\.png)", tornado.web.StaticFileHandler, dict(path=settings['static_path'])))
  212. handlers.extend(url)
  213. application_setting()
  214. application = tornado.web.Application(handlers=handlers, **settings)
  215. if settings['debug'] == True:
  216. application.listen(settings['port'])
  217. tornado.ioloop.IOLoop.instance().start()
  218. else:
  219. server = tornado.httpserver.HTTPServer(application, settings['max_buffer_size'])
  220. server.bind(settings['port'])
  221. server.start(settings['process'])
  222. try:
  223. print 'running on port %s' % settings['port']
  224. tornado.ioloop.IOLoop.instance().start()
  225. except KeyboardInterrupt:
  226. tornado.ioloop.IOLoop.instance().stop()