gooderp18绿色标准版
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.

180 lines
4.6KB

  1. ##########################################################################
  2. #
  3. # pgAdmin 4 - PostgreSQL Tools
  4. #
  5. # Copyright (C) 2013 - 2020, The pgAdmin Development Team
  6. # This software is released under the PostgreSQL Licence
  7. #
  8. ##########################################################################
  9. """Utility functions for dealing with AJAX."""
  10. import datetime
  11. import decimal
  12. import simplejson as json
  13. from flask import Response
  14. from flask_babelex import gettext as _
  15. class DataTypeJSONEncoder(json.JSONEncoder):
  16. def default(self, obj):
  17. if isinstance(obj, datetime.datetime) \
  18. or hasattr(obj, 'isoformat'):
  19. return obj.isoformat()
  20. elif isinstance(obj, datetime.timedelta):
  21. return (datetime.datetime.min + obj).time().isoformat()
  22. if isinstance(obj, decimal.Decimal):
  23. return float(obj)
  24. return json.JSONEncoder.default(self, obj)
  25. class ColParamsJSONDecoder(json.JSONDecoder):
  26. def decode(self, obj):
  27. retval = obj
  28. try:
  29. retval = json.JSONDecoder.decode(self, obj)
  30. if type(retval) == str:
  31. retval = obj
  32. except (ValueError, TypeError, KeyError):
  33. retval = obj
  34. return retval
  35. def get_no_cache_header():
  36. """
  37. Prevent browser from caching data every time an
  38. http request is made.
  39. Returns: headers
  40. """
  41. headers = {}
  42. # HTTP 1.1.
  43. headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  44. headers["Pragma"] = "no-cache" # HTTP 1.0.
  45. headers["Expires"] = "0" # Proxies.
  46. return headers
  47. def make_json_response(
  48. success=1, errormsg='', info='', result=None, data=None, status=200,
  49. encoding='utf-8'
  50. ):
  51. """Create a HTML response document describing the results of a request and
  52. containing the data."""
  53. doc = dict()
  54. doc['success'] = success
  55. doc['errormsg'] = errormsg
  56. doc['info'] = info
  57. doc['result'] = result
  58. doc['data'] = data
  59. return Response(
  60. response=json.dumps(doc, cls=DataTypeJSONEncoder,
  61. separators=(',', ':'), encoding=encoding),
  62. status=status,
  63. mimetype="application/json",
  64. headers=get_no_cache_header()
  65. )
  66. def make_response(response=None, status=200):
  67. """Create a JSON response handled by the backbone models."""
  68. return Response(
  69. response=json.dumps(
  70. response, cls=DataTypeJSONEncoder, separators=(',', ':')),
  71. status=status,
  72. mimetype="application/json",
  73. headers=get_no_cache_header()
  74. )
  75. def internal_server_error(errormsg=''):
  76. """Create a response with HTTP status code 500 - Internal Server Error."""
  77. return make_json_response(
  78. status=500,
  79. success=0,
  80. errormsg=errormsg
  81. )
  82. def forbidden(errmsg=''):
  83. """Create a response with HTTP status code 403 - Forbidden."""
  84. return make_json_response(
  85. status=403,
  86. success=0,
  87. errormsg=errmsg
  88. )
  89. def unauthorized(errormsg=''):
  90. """Create a response with HTTP status code 401 - Unauthorized."""
  91. return make_json_response(
  92. status=401,
  93. success=0,
  94. errormsg=errormsg
  95. )
  96. def bad_request(errormsg=''):
  97. """Create a response with HTTP status code 400 - Bad Request."""
  98. return make_json_response(
  99. status=400,
  100. success=0,
  101. errormsg=errormsg
  102. )
  103. def precondition_required(errormsg=''):
  104. """Create a response with HTTP status code 428 - Precondition Required."""
  105. return make_json_response(
  106. status=428,
  107. success=0,
  108. errormsg=errormsg
  109. )
  110. def success_return(message=''):
  111. """Create a response with HTTP status code 200 - OK."""
  112. return make_json_response(
  113. status=200,
  114. success=1,
  115. info=message
  116. )
  117. def gone(errormsg=''):
  118. """Create a response with HTTP status code 410 - GONE."""
  119. return make_json_response(
  120. status=410,
  121. success=0,
  122. errormsg=errormsg
  123. )
  124. def not_implemented(errormsg=_('Not implemented.'), info='',
  125. result=None, data=None):
  126. """Create a response with HTTP status code 501 - Not Implemented."""
  127. return make_json_response(
  128. status=501,
  129. success=0,
  130. errormsg=errormsg,
  131. info=info,
  132. result=result,
  133. data=data
  134. )
  135. def service_unavailable(errormsg=_("Service Unavailable"), info='',
  136. result=None, data=None):
  137. """Create a response with HTTP status code 503 - Server Unavailable."""
  138. return make_json_response(
  139. status=503,
  140. success=0,
  141. errormsg=errormsg,
  142. info=info,
  143. result=result,
  144. data=data
  145. )
上海开阖软件有限公司 沪ICP备12045867号-1