You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

handler.py 6.7 KiB

12 years ago
12 years ago
11 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
12 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
13 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
13 years ago
13 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import sys, os
  5. import webnotes
  6. import webnotes.utils
  7. import webnotes.sessions
  8. @webnotes.whitelist(allow_guest=True)
  9. def startup():
  10. webnotes.response.update(webnotes.sessions.get())
  11. def cleanup_docs():
  12. import webnotes.model.utils
  13. if webnotes.response.get('docs') and type(webnotes.response['docs'])!=dict:
  14. webnotes.response['docs'] = webnotes.model.utils.compress(webnotes.response['docs'])
  15. @webnotes.whitelist()
  16. def runserverobj(arg=None):
  17. import webnotes.widgets.form.run_method
  18. webnotes.widgets.form.run_method.runserverobj()
  19. @webnotes.whitelist(allow_guest=True)
  20. def logout():
  21. webnotes.local.login_manager.logout()
  22. @webnotes.whitelist(allow_guest=True)
  23. def web_logout():
  24. webnotes.local.login_manager.logout()
  25. webnotes.conn.commit()
  26. webnotes.repsond_as_web_page("Logged Out", """<p>You have been logged out.</p>
  27. <p><a href='index'>Back to Home</a></p>""")
  28. @webnotes.whitelist(allow_guest=True)
  29. def run_custom_method(doctype, name, custom_method):
  30. """cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}"""
  31. bean = webnotes.bean(doctype, name)
  32. controller = bean.get_controller()
  33. if getattr(controller, custom_method, webnotes._dict()).is_whitelisted:
  34. call(getattr(controller, custom_method), webnotes.local.form_dict)
  35. else:
  36. webnotes.throw("Not Allowed")
  37. @webnotes.whitelist()
  38. def uploadfile():
  39. import webnotes.utils
  40. import webnotes.utils.file_manager
  41. import json
  42. try:
  43. if webnotes.form_dict.get('from_form'):
  44. try:
  45. ret = webnotes.utils.file_manager.upload()
  46. except webnotes.DuplicateEntryError, e:
  47. # ignore pass
  48. ret = None
  49. webnotes.conn.rollback()
  50. else:
  51. if webnotes.form_dict.get('method'):
  52. ret = webnotes.get_method(webnotes.form_dict.method)()
  53. except Exception, e:
  54. webnotes.errprint(webnotes.utils.getTraceback())
  55. ret = None
  56. return ret
  57. def handle():
  58. """handle request"""
  59. cmd = webnotes.form_dict['cmd']
  60. if cmd!='login':
  61. # login executed in webnotes.auth
  62. if webnotes.request_method == "POST":
  63. webnotes.conn.begin()
  64. try:
  65. execute_cmd(cmd)
  66. except webnotes.ValidationError, e:
  67. webnotes.errprint(webnotes.utils.getTraceback())
  68. if webnotes.request_method == "POST":
  69. webnotes.conn.rollback()
  70. except webnotes.PermissionError, e:
  71. webnotes.errprint(webnotes.utils.getTraceback())
  72. webnotes.response['403'] = 1
  73. if webnotes.request_method == "POST":
  74. webnotes.conn.rollback()
  75. except:
  76. webnotes.errprint(webnotes.utils.getTraceback())
  77. if webnotes.request_method == "POST":
  78. webnotes.conn and webnotes.conn.rollback()
  79. if webnotes.request_method == "POST" and webnotes.conn:
  80. webnotes.conn.commit()
  81. print_response()
  82. if webnotes.conn:
  83. webnotes.conn.close()
  84. if webnotes._memc:
  85. webnotes._memc.disconnect_all()
  86. def execute_cmd(cmd):
  87. """execute a request as python module"""
  88. method = get_method(cmd)
  89. # check if whitelisted
  90. if webnotes.session['user'] == 'Guest':
  91. if (method not in webnotes.guest_methods):
  92. webnotes.response['403'] = 1
  93. raise Exception, 'Not Allowed, %s' % str(method)
  94. else:
  95. if not method in webnotes.whitelisted:
  96. webnotes.response['403'] = 1
  97. webnotes.msgprint('Not Allowed, %s' % str(method))
  98. raise Exception, 'Not Allowed, %s' % str(method)
  99. ret = call(method, webnotes.form_dict)
  100. # returns with a message
  101. if ret:
  102. webnotes.response['message'] = ret
  103. # update session
  104. webnotes.local.session_obj.update()
  105. def call(fn, args):
  106. import inspect
  107. if hasattr(fn, 'fnargs'):
  108. fnargs = fn.fnargs
  109. else:
  110. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  111. newargs = {}
  112. for a in fnargs:
  113. if a in args:
  114. newargs[a] = args.get(a)
  115. return fn(**newargs)
  116. def get_method(cmd):
  117. """get method object from cmd"""
  118. if '.' in cmd:
  119. method = webnotes.get_method(cmd)
  120. else:
  121. method = globals()[cmd]
  122. webnotes.log("method:" + cmd)
  123. return method
  124. def print_response():
  125. print_map = {
  126. 'csv': print_csv,
  127. 'download': print_raw,
  128. 'json': print_json,
  129. 'page': print_page
  130. }
  131. print_map.get(webnotes.response.get('type'), print_json)()
  132. def print_page():
  133. """print web page"""
  134. from webnotes.webutils import render
  135. render(webnotes.response['page_name'])
  136. def print_json():
  137. make_logs()
  138. cleanup_docs()
  139. webnotes._response.headers["Content-Type"] = "text/html; charset: utf-8"
  140. import json
  141. print_zip(json.dumps(webnotes.local.response, default=json_handler, separators=(',',':')))
  142. def print_csv():
  143. webnotes._response.headers["Content-Type"] = \
  144. "text/csv; charset: utf-8"
  145. webnotes._response.headers["Content-Disposition"] = \
  146. "attachment; filename=%s.csv" % webnotes.response['doctype'].replace(' ', '_')
  147. webnotes._response.data = webnotes.response['result']
  148. def print_raw():
  149. webnotes._response.headers["Content-Type"] = \
  150. mimetypes.guess_type(webnotes.response['filename'])[0] or "application/unknown"
  151. webnotes._response.headers["Content-Disposition"] = \
  152. "filename=%s" % webnotes.response['filename'].replace(' ', '_')
  153. webnotes._response.data = webnotes.response['filecontent']
  154. def make_logs():
  155. """make strings for msgprint and errprint"""
  156. import json
  157. from webnotes import conf
  158. from webnotes.utils import cstr
  159. if webnotes.error_log:
  160. # webnotes.response['exc'] = json.dumps("\n".join([cstr(d) for d in webnotes.error_log]))
  161. webnotes.response['exc'] = json.dumps([cstr(d) for d in webnotes.local.error_log])
  162. if webnotes.local.message_log:
  163. webnotes.response['_server_messages'] = json.dumps([cstr(d) for d in webnotes.local.message_log])
  164. if webnotes.debug_log and conf.get("logging") or False:
  165. webnotes.response['_debug_messages'] = json.dumps(webnotes.local.debug_log)
  166. def print_zip(response):
  167. response = response.encode('utf-8')
  168. orig_len = len(response)
  169. if accept_gzip() and orig_len>512:
  170. response = compressBuf(response)
  171. webnotes._response.headers["Content-Encoding"] = "gzip"
  172. webnotes._response.headers["Content-Length"] = str(len(response))
  173. webnotes._response.data = response
  174. def json_handler(obj):
  175. """serialize non-serializable data for json"""
  176. import datetime
  177. from werkzeug.local import LocalProxy
  178. # serialize date
  179. if isinstance(obj, (datetime.date, datetime.timedelta, datetime.datetime)):
  180. return unicode(obj)
  181. elif isinstance(obj, LocalProxy):
  182. return unicode(obj)
  183. else:
  184. raise TypeError, """Object of type %s with value of %s is not JSON serializable""" % \
  185. (type(obj), repr(obj))
  186. def accept_gzip():
  187. if "gzip" in webnotes.get_request_header("HTTP_ACCEPT_ENCODING", ""):
  188. return True
  189. def compressBuf(buf):
  190. import gzip, cStringIO
  191. zbuf = cStringIO.StringIO()
  192. zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
  193. zfile.write(buf)
  194. zfile.close()
  195. return zbuf.getvalue()