Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

104 rindas
3.3 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 json
  5. import datetime
  6. import gzip, cStringIO
  7. import webnotes
  8. import webnotes.utils
  9. import webnotes.sessions
  10. import webnotes.model.utils
  11. from werkzeug.local import LocalProxy
  12. def report_error(status_code):
  13. if status_code!=404:
  14. webnotes.errprint(webnotes.utils.get_traceback())
  15. webnotes._response.status_code = status_code
  16. if webnotes.request_method == "POST":
  17. webnotes.conn.rollback()
  18. def build_response():
  19. print_map = {
  20. 'csv': print_csv,
  21. 'download': print_raw,
  22. 'json': print_json,
  23. 'page': print_page
  24. }
  25. print_map.get(webnotes.response.get('type'), print_json)()
  26. def print_page():
  27. """print web page"""
  28. from webnotes.webutils import render
  29. render(webnotes.response['page_name'])
  30. def print_json():
  31. make_logs()
  32. cleanup_docs()
  33. webnotes._response.headers["Content-Type"] = "text/json; charset: utf-8"
  34. print_zip(json.dumps(webnotes.local.response, default=json_handler, separators=(',',':')))
  35. def cleanup_docs():
  36. if webnotes.response.get('docs') and type(webnotes.response['docs'])!=dict:
  37. webnotes.response['docs'] = webnotes.model.utils.compress(webnotes.response['docs'])
  38. def print_csv():
  39. webnotes._response.headers["Content-Type"] = \
  40. "text/csv; charset: utf-8"
  41. webnotes._response.headers["Content-Disposition"] = \
  42. "attachment; filename=%s.csv" % webnotes.response['doctype'].replace(' ', '_')
  43. webnotes._response.data = webnotes.response['result']
  44. def print_raw():
  45. webnotes._response.headers["Content-Type"] = \
  46. mimetypes.guess_type(webnotes.response['filename'])[0] or "application/unknown"
  47. webnotes._response.headers["Content-Disposition"] = \
  48. "filename=%s" % webnotes.response['filename'].replace(' ', '_')
  49. webnotes._response.data = webnotes.response['filecontent']
  50. def make_logs():
  51. """make strings for msgprint and errprint"""
  52. if webnotes.error_log:
  53. # webnotes.response['exc'] = json.dumps("\n".join([cstr(d) for d in webnotes.error_log]))
  54. webnotes.response['exc'] = json.dumps([webnotes.utils.cstr(d) for d in webnotes.local.error_log])
  55. if webnotes.local.message_log:
  56. webnotes.response['_server_messages'] = json.dumps([webnotes.utils.cstr(d) for d in webnotes.local.message_log])
  57. if webnotes.debug_log and webnotes.conf.get("logging") or False:
  58. webnotes.response['_debug_messages'] = json.dumps(webnotes.local.debug_log)
  59. def print_zip(response):
  60. response = response.encode('utf-8')
  61. orig_len = len(response)
  62. if accept_gzip() and orig_len>512:
  63. response = compressBuf(response)
  64. webnotes._response.headers["Content-Encoding"] = "gzip"
  65. webnotes._response.headers["Content-Length"] = str(len(response))
  66. webnotes._response.data = response
  67. def json_handler(obj):
  68. """serialize non-serializable data for json"""
  69. # serialize date
  70. if isinstance(obj, (datetime.date, datetime.timedelta, datetime.datetime)):
  71. return unicode(obj)
  72. elif isinstance(obj, LocalProxy):
  73. return unicode(obj)
  74. else:
  75. raise TypeError, """Object of type %s with value of %s is not JSON serializable""" % \
  76. (type(obj), repr(obj))
  77. def accept_gzip():
  78. if "gzip" in webnotes.get_request_header("HTTP_ACCEPT_ENCODING", ""):
  79. return True
  80. def compressBuf(buf):
  81. zbuf = cStringIO.StringIO()
  82. zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 5)
  83. zfile.write(buf)
  84. zfile.close()
  85. return zbuf.getvalue()