選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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