Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

290 linhas
7.5 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. form = webnotes.form
  9. form_dict = webnotes.form_dict
  10. sql = None
  11. session = None
  12. errdoc = ''
  13. errdoctype = ''
  14. errmethod = ''
  15. def get_cgi_fields():
  16. """make webnotes.form_dict from cgi field storage"""
  17. import cgi
  18. import webnotes
  19. from webnotes.utils import cstr
  20. # make the form_dict
  21. webnotes.form = cgi.FieldStorage(keep_blank_values=True)
  22. for key in webnotes.form.keys():
  23. # file upload must not be decoded as it is treated as a binary
  24. # file and hence in any encoding (it does not matter)
  25. if not getattr(webnotes.form[key], 'filename', None):
  26. webnotes.form_dict[key] = cstr(webnotes.form.getvalue(key))
  27. @webnotes.whitelist(allow_guest=True)
  28. def startup():
  29. webnotes.response.update(webnotes.sessions.get())
  30. def cleanup_docs():
  31. import webnotes.model.utils
  32. if webnotes.response.get('docs') and type(webnotes.response['docs'])!=dict:
  33. webnotes.response['docs'] = webnotes.model.utils.compress(webnotes.response['docs'])
  34. @webnotes.whitelist()
  35. def runserverobj(arg=None):
  36. import webnotes.widgets.form.run_method
  37. webnotes.widgets.form.run_method.runserverobj()
  38. @webnotes.whitelist(allow_guest=True)
  39. def logout():
  40. webnotes.login_manager.logout()
  41. @webnotes.whitelist(allow_guest=True)
  42. def web_logout():
  43. webnotes.repsond_as_web_page("Logged Out", """<p>You have been logged out.</p>
  44. <p><a href='index'>Back to Home</a></p>""")
  45. webnotes.login_manager.logout()
  46. webnotes.commit()
  47. @webnotes.whitelist()
  48. def uploadfile():
  49. import webnotes.utils
  50. import webnotes.utils.file_manager
  51. import json
  52. try:
  53. if webnotes.form_dict.get('from_form'):
  54. try:
  55. ret = webnotes.utils.file_manager.upload()
  56. except webnotes.DuplicateEntryError, e:
  57. # ignore pass
  58. ret = None
  59. webnotes.conn.rollback()
  60. else:
  61. if webnotes.form_dict.get('method'):
  62. ret = webnotes.get_method(webnotes.form_dict.method)()
  63. except Exception, e:
  64. webnotes.errprint(webnotes.utils.getTraceback())
  65. ret = None
  66. return ret
  67. def handle():
  68. """handle request"""
  69. cmd = webnotes.form_dict['cmd']
  70. if cmd!='login':
  71. # login executed in webnotes.auth
  72. if webnotes.request_method == "POST":
  73. webnotes.conn.begin()
  74. try:
  75. execute_cmd(cmd)
  76. except webnotes.ValidationError, e:
  77. webnotes.errprint(webnotes.utils.getTraceback())
  78. if webnotes.request_method == "POST":
  79. webnotes.conn.rollback()
  80. except webnotes.PermissionError, e:
  81. webnotes.errprint(webnotes.utils.getTraceback())
  82. webnotes.response['403'] = 1
  83. if webnotes.request_method == "POST":
  84. webnotes.conn.rollback()
  85. except:
  86. webnotes.errprint(webnotes.utils.getTraceback())
  87. if webnotes.request_method == "POST":
  88. webnotes.conn and webnotes.conn.rollback()
  89. if webnotes.request_method == "POST" and webnotes.conn:
  90. webnotes.conn.commit()
  91. print_response()
  92. if webnotes.conn:
  93. webnotes.conn.close()
  94. if webnotes._memc:
  95. webnotes._memc.disconnect_all()
  96. def execute_cmd(cmd):
  97. """execute a request as python module"""
  98. method = get_method(cmd)
  99. # check if whitelisted
  100. if webnotes.session['user'] == 'Guest':
  101. if (method not in webnotes.guest_methods):
  102. webnotes.response['403'] = 1
  103. raise Exception, 'Not Allowed, %s' % str(method)
  104. else:
  105. if not method in webnotes.whitelisted:
  106. webnotes.response['403'] = 1
  107. webnotes.msgprint('Not Allowed, %s' % str(method))
  108. raise Exception, 'Not Allowed, %s' % str(method)
  109. ret = call(method, webnotes.form_dict)
  110. # returns with a message
  111. if ret:
  112. webnotes.response['message'] = ret
  113. # update session
  114. webnotes.session_obj.update()
  115. def call(fn, args):
  116. import inspect
  117. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  118. newargs = {}
  119. for a in fnargs:
  120. if a in args:
  121. newargs[a] = args.get(a)
  122. return fn(**newargs)
  123. def get_method(cmd):
  124. """get method object from cmd"""
  125. if '.' in cmd:
  126. method = webnotes.get_method(cmd)
  127. else:
  128. method = globals()[cmd]
  129. webnotes.log("method:" + cmd)
  130. return method
  131. def print_response():
  132. print_map = {
  133. 'csv': print_csv,
  134. 'iframe': print_iframe,
  135. 'download': print_raw,
  136. 'json': print_json,
  137. 'page': print_page
  138. }
  139. print_map.get(webnotes.response.get('type'), print_json)()
  140. def print_page():
  141. """print web page"""
  142. print_cookie_header()
  143. from webnotes.webutils import render
  144. render(webnotes.response['page_name'])
  145. def eprint(content):
  146. print content.encode('utf-8')
  147. def print_json():
  148. make_logs()
  149. cleanup_docs()
  150. print_cookie_header()
  151. eprint("Content-Type: text/html; charset: utf-8")
  152. import json
  153. print_zip(json.dumps(webnotes.response, default=json_handler, separators=(',',':')))
  154. def print_csv():
  155. eprint("Content-Type: text/csv; charset: utf-8")
  156. eprint("Content-Disposition: attachment; filename=%s.csv" % webnotes.response['doctype'].replace(' ', '_'))
  157. eprint("")
  158. eprint(webnotes.response['result'])
  159. def print_iframe():
  160. eprint("Content-Type: text/html; charset: utf-8")
  161. eprint("")
  162. eprint(webnotes.response.get('result') or '')
  163. if webnotes.error_log:
  164. import json
  165. eprint("""\
  166. <script>
  167. var messages = %(messages)s;
  168. if (messages.length) {
  169. for (var i in messages) {
  170. window.parent.msgprint(messages[i]);
  171. }
  172. }
  173. var errors = %(errors)s;
  174. if (errors.length) {
  175. for (var i in errors) {
  176. window.parent.console.log(errors[i]);
  177. }
  178. }
  179. </script>""" % {
  180. 'messages': json.dumps(webnotes.message_log).replace("'", "\\'"),
  181. 'errors': json.dumps(webnotes.error_log).replace("'", "\\'"),
  182. })
  183. def print_raw():
  184. eprint("Content-Type: %s" % \
  185. mimetypes.guess_type(webnotes.response['filename'])[0] \
  186. or 'application/unknown'),
  187. eprint("Content-Disposition: filename=%s" % \
  188. webnotes.response['filename'].replace(' ', '_'))
  189. eprint("")
  190. eprint(webnotes.response['filecontent'])
  191. def make_logs():
  192. """make strings for msgprint and errprint"""
  193. import json, conf
  194. from webnotes.utils import cstr
  195. if webnotes.error_log:
  196. # webnotes.response['exc'] = json.dumps("\n".join([cstr(d) for d in webnotes.error_log]))
  197. webnotes.response['exc'] = json.dumps([cstr(d) for d in webnotes.error_log])
  198. if webnotes.message_log:
  199. webnotes.response['_server_messages'] = json.dumps([cstr(d) for d in webnotes.message_log])
  200. if webnotes.debug_log and getattr(conf, "logging", False):
  201. webnotes.response['_debug_messages'] = json.dumps(webnotes.debug_log)
  202. def print_cookie_header():
  203. """if there ar additional cookies defined during the request, add them"""
  204. if webnotes.cookies or webnotes.add_cookies:
  205. for c in webnotes.add_cookies.keys():
  206. webnotes.cookies[c.encode('utf-8')] = \
  207. webnotes.add_cookies[c].encode('utf-8')
  208. if webnotes.cookies:
  209. print webnotes.cookies
  210. def print_zip(response):
  211. response = response.encode('utf-8')
  212. orig_len = len(response)
  213. if accept_gzip() and orig_len>512:
  214. response = compressBuf(response)
  215. eprint("Content-Encoding: gzip")
  216. eprint("Original-Length: %d" % orig_len)
  217. eprint("Content-Length: %d" % len(response))
  218. eprint("")
  219. print response
  220. def json_handler(obj):
  221. """serialize non-serializable data for json"""
  222. import datetime
  223. # serialize date
  224. if isinstance(obj, (datetime.date, datetime.timedelta, datetime.datetime)):
  225. return unicode(obj)
  226. else:
  227. raise TypeError, """Object of type %s with value of %s is not JSON serializable""" % \
  228. (type(obj), repr(obj))
  229. def accept_gzip():
  230. if "gzip" in os.environ.get("HTTP_ACCEPT_ENCODING", ""):
  231. return True
  232. def compressBuf(buf):
  233. import gzip, cStringIO
  234. zbuf = cStringIO.StringIO()
  235. zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
  236. zfile.write(buf)
  237. zfile.close()
  238. return zbuf.getvalue()