Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

244 lignes
6.7 KiB

  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_attr(webnotes.form_dict.method)()
  53. except Exception, e:
  54. webnotes.errprint(webnotes.utils.get_traceback())
  55. ret = None
  56. return ret
  57. def handle():
  58. """handle request"""
  59. cmd = webnotes.form_dict['cmd']
  60. def _error(status_code):
  61. webnotes.errprint(webnotes.utils.get_traceback())
  62. webnotes._response.status_code = status_code
  63. if webnotes.request_method == "POST":
  64. webnotes.conn.rollback()
  65. if cmd!='login':
  66. # login executed in webnotes.auth
  67. if webnotes.request_method == "POST":
  68. webnotes.conn.begin()
  69. status_codes = {
  70. webnotes.PermissionError: 403,
  71. webnotes.AuthenticationError: 401,
  72. webnotes.DoesNotExistError: 404,
  73. webnotes.SessionStopped: 503,
  74. webnotes.OutgoingEmailError: 501
  75. }
  76. try:
  77. execute_cmd(cmd)
  78. except Exception, e:
  79. _error(status_codes.get(e.__class__, 500))
  80. else:
  81. if webnotes.request_method == "POST" and webnotes.conn:
  82. webnotes.conn.commit()
  83. print_response()
  84. if webnotes.conn:
  85. webnotes.conn.close()
  86. if webnotes._memc:
  87. webnotes._memc.disconnect_all()
  88. def execute_cmd(cmd):
  89. """execute a request as python module"""
  90. method = get_attr(cmd)
  91. # check if whitelisted
  92. if webnotes.session['user'] == 'Guest':
  93. if (method not in webnotes.guest_methods):
  94. raise webnotes.PermissionError('Not Allowed, %s' % str(method))
  95. else:
  96. if not method in webnotes.whitelisted:
  97. webnotes._response.status_code = 403
  98. webnotes.msgprint('Not Allowed, %s' % str(method))
  99. raise webnotes.PermissionError('Not Allowed, %s' % str(method))
  100. ret = call(method, webnotes.form_dict)
  101. # returns with a message
  102. if ret:
  103. webnotes.response['message'] = ret
  104. # update session
  105. if "session_obj" in webnotes.local:
  106. webnotes.local.session_obj.update()
  107. def call(fn, args):
  108. import inspect
  109. if hasattr(fn, 'fnargs'):
  110. fnargs = fn.fnargs
  111. else:
  112. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  113. newargs = {}
  114. for a in fnargs:
  115. if a in args:
  116. newargs[a] = args.get(a)
  117. return fn(**newargs)
  118. def get_attr(cmd):
  119. """get method object from cmd"""
  120. if '.' in cmd:
  121. method = webnotes.get_attr(cmd)
  122. else:
  123. method = globals()[cmd]
  124. webnotes.log("method:" + cmd)
  125. return method
  126. def print_response():
  127. print_map = {
  128. 'csv': print_csv,
  129. 'download': print_raw,
  130. 'json': print_json,
  131. 'page': print_page
  132. }
  133. print_map.get(webnotes.response.get('type'), print_json)()
  134. def print_page():
  135. """print web page"""
  136. from webnotes.webutils import render
  137. render(webnotes.response['page_name'])
  138. def print_json():
  139. make_logs()
  140. cleanup_docs()
  141. webnotes._response.headers["Content-Type"] = "text/json; charset: utf-8"
  142. import json
  143. print_zip(json.dumps(webnotes.local.response, default=json_handler, separators=(',',':')))
  144. def print_csv():
  145. webnotes._response.headers["Content-Type"] = \
  146. "text/csv; charset: utf-8"
  147. webnotes._response.headers["Content-Disposition"] = \
  148. "attachment; filename=%s.csv" % webnotes.response['doctype'].replace(' ', '_')
  149. webnotes._response.data = webnotes.response['result']
  150. def print_raw():
  151. webnotes._response.headers["Content-Type"] = \
  152. mimetypes.guess_type(webnotes.response['filename'])[0] or "application/unknown"
  153. webnotes._response.headers["Content-Disposition"] = \
  154. "filename=%s" % webnotes.response['filename'].replace(' ', '_')
  155. webnotes._response.data = webnotes.response['filecontent']
  156. def make_logs():
  157. """make strings for msgprint and errprint"""
  158. import json
  159. from webnotes import conf
  160. from webnotes.utils import cstr
  161. if webnotes.error_log:
  162. # webnotes.response['exc'] = json.dumps("\n".join([cstr(d) for d in webnotes.error_log]))
  163. webnotes.response['exc'] = json.dumps([cstr(d) for d in webnotes.local.error_log])
  164. if webnotes.local.message_log:
  165. webnotes.response['_server_messages'] = json.dumps([cstr(d) for d in webnotes.local.message_log])
  166. if webnotes.debug_log and conf.get("logging") or False:
  167. webnotes.response['_debug_messages'] = json.dumps(webnotes.local.debug_log)
  168. def print_zip(response):
  169. response = response.encode('utf-8')
  170. orig_len = len(response)
  171. if accept_gzip() and orig_len>512:
  172. response = compressBuf(response)
  173. webnotes._response.headers["Content-Encoding"] = "gzip"
  174. webnotes._response.headers["Content-Length"] = str(len(response))
  175. webnotes._response.data = response
  176. def json_handler(obj):
  177. """serialize non-serializable data for json"""
  178. import datetime
  179. from werkzeug.local import LocalProxy
  180. # serialize date
  181. if isinstance(obj, (datetime.date, datetime.timedelta, datetime.datetime)):
  182. return unicode(obj)
  183. elif isinstance(obj, LocalProxy):
  184. return unicode(obj)
  185. else:
  186. raise TypeError, """Object of type %s with value of %s is not JSON serializable""" % \
  187. (type(obj), repr(obj))
  188. def accept_gzip():
  189. if "gzip" in webnotes.get_request_header("HTTP_ACCEPT_ENCODING", ""):
  190. return True
  191. def compressBuf(buf):
  192. import gzip, cStringIO
  193. zbuf = cStringIO.StringIO()
  194. zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
  195. zfile.write(buf)
  196. zfile.close()
  197. return zbuf.getvalue()