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.
 
 
 
 
 
 

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