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.
 
 
 
 
 
 

223 rivejä
6.0 KiB

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