No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

222 líneas
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.conn.commit()
  28. @webnotes.whitelist()
  29. def uploadfile():
  30. import webnotes.utils
  31. import webnotes.utils.file_manager
  32. import json
  33. try:
  34. if webnotes.form_dict.get('from_form'):
  35. try:
  36. ret = webnotes.utils.file_manager.upload()
  37. except webnotes.DuplicateEntryError, e:
  38. # ignore pass
  39. ret = None
  40. webnotes.conn.rollback()
  41. else:
  42. if webnotes.form_dict.get('method'):
  43. ret = webnotes.get_method(webnotes.form_dict.method)()
  44. except Exception, e:
  45. webnotes.errprint(webnotes.utils.getTraceback())
  46. ret = None
  47. return ret
  48. def handle():
  49. """handle request"""
  50. cmd = webnotes.form_dict['cmd']
  51. if cmd!='login':
  52. # login executed in webnotes.auth
  53. if webnotes.request_method == "POST":
  54. webnotes.conn.begin()
  55. try:
  56. execute_cmd(cmd)
  57. except webnotes.ValidationError, e:
  58. webnotes.errprint(webnotes.utils.getTraceback())
  59. if webnotes.request_method == "POST":
  60. webnotes.conn.rollback()
  61. except webnotes.PermissionError, e:
  62. webnotes.errprint(webnotes.utils.getTraceback())
  63. webnotes.response['403'] = 1
  64. if webnotes.request_method == "POST":
  65. webnotes.conn.rollback()
  66. except:
  67. webnotes.errprint(webnotes.utils.getTraceback())
  68. if webnotes.request_method == "POST":
  69. webnotes.conn and webnotes.conn.rollback()
  70. if webnotes.request_method == "POST" and webnotes.conn:
  71. webnotes.conn.commit()
  72. print_response()
  73. if webnotes.conn:
  74. webnotes.conn.close()
  75. if webnotes._memc:
  76. webnotes._memc.disconnect_all()
  77. def execute_cmd(cmd):
  78. """execute a request as python module"""
  79. method = get_method(cmd)
  80. # check if whitelisted
  81. if webnotes.session['user'] == 'Guest':
  82. if (method not in webnotes.guest_methods):
  83. webnotes.response['403'] = 1
  84. raise Exception, 'Not Allowed, %s' % str(method)
  85. else:
  86. if not method in webnotes.whitelisted:
  87. webnotes.response['403'] = 1
  88. webnotes.msgprint('Not Allowed, %s' % str(method))
  89. raise Exception, 'Not Allowed, %s' % str(method)
  90. ret = call(method, webnotes.form_dict)
  91. # returns with a message
  92. if ret:
  93. webnotes.response['message'] = ret
  94. # update session
  95. webnotes.local.session_obj.update()
  96. def call(fn, args):
  97. import inspect
  98. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  99. newargs = {}
  100. for a in fnargs:
  101. if a in args:
  102. newargs[a] = args.get(a)
  103. return fn(**newargs)
  104. def get_method(cmd):
  105. """get method object from cmd"""
  106. if '.' in cmd:
  107. method = webnotes.get_method(cmd)
  108. else:
  109. method = globals()[cmd]
  110. webnotes.log("method:" + cmd)
  111. return method
  112. def print_response():
  113. print_map = {
  114. 'csv': print_csv,
  115. 'download': print_raw,
  116. 'json': print_json,
  117. 'page': print_page
  118. }
  119. print_map.get(webnotes.response.get('type'), print_json)()
  120. def print_page():
  121. """print web page"""
  122. from webnotes.webutils import render
  123. render(webnotes.response['page_name'])
  124. def print_json():
  125. make_logs()
  126. cleanup_docs()
  127. webnotes._response.headers["Content-Type"] = "text/html; charset: utf-8"
  128. import json
  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()