-
Notifications
You must be signed in to change notification settings - Fork 725
/
Copy pathajax.py
190 lines (154 loc) · 4.84 KB
/
ajax.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2025, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
##########################################################################
"""Utility functions for dealing with AJAX."""
import datetime
import decimal
import json
from flask import Response
from flask_babel import gettext as _
class DataTypeJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime) \
or hasattr(obj, 'isoformat'):
return obj.isoformat()
elif isinstance(obj, datetime.timedelta):
return (datetime.datetime.min + obj).time().isoformat()
if isinstance(obj, decimal.Decimal):
return float(obj)
if isinstance(obj, bytes):
return obj.decode('utf-8')
try:
retval = json.JSONEncoder.default(self, obj)
except TypeError:
retval = obj
return retval
class ColParamsJSONDecoder(json.JSONDecoder):
def decode(self, obj, **kwargs):
retval = obj
try:
retval = json.JSONDecoder.decode(self, obj)
if isinstance(retval, str):
retval = obj
except (ValueError, TypeError, KeyError):
retval = obj
return retval
def get_no_cache_header():
"""
Prevent browser from caching data every time an
http request is made.
Returns: headers
"""
headers = {}
# HTTP 1.1.
headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
headers["Pragma"] = "no-cache" # HTTP 1.0.
headers["Expires"] = "0" # Proxies.
return headers
def make_json_response(
success=1, errormsg='', info='', result=None, data=None, status=200
):
"""Create a HTML response document describing the results of a request and
containing the data."""
doc = dict()
doc['success'] = success
doc['errormsg'] = errormsg
doc['info'] = info
doc['result'] = result
doc['data'] = data
return Response(
response=json.dumps(doc, cls=DataTypeJSONEncoder,
separators=(',', ':')),
status=status,
mimetype="application/json",
headers=get_no_cache_header()
)
def make_response(response=None, status=200):
"""Create a JSON response"""
return Response(
response=json.dumps(
response, cls=DataTypeJSONEncoder, separators=(',', ':')),
status=status,
mimetype="application/json",
headers=get_no_cache_header()
)
def internal_server_error(errormsg='',data=None):
"""Create a response with HTTP status code 500 - Internal Server Error."""
return make_json_response(
status=500,
success=0,
errormsg=errormsg,
data=data
)
def forbidden(errmsg=''):
"""Create a response with HTTP status code 403 - Forbidden."""
return make_json_response(
status=403,
success=0,
errormsg=errmsg
)
def unauthorized(errormsg=''):
"""Create a response with HTTP status code 401 - Unauthorized."""
return make_json_response(
status=401,
success=0,
errormsg=errormsg
)
def bad_request(errormsg=''):
"""Create a response with HTTP status code 400 - Bad Request."""
return make_json_response(
status=400,
success=0,
errormsg=errormsg
)
def precondition_required(errormsg=''):
"""Create a response with HTTP status code 428 - Precondition Required."""
return make_json_response(
status=428,
success=0,
errormsg=errormsg
)
def success_return(message=''):
"""Create a response with HTTP status code 200 - OK."""
return make_json_response(
status=200,
success=1,
info=message
)
def gone(errormsg=''):
"""Create a response with HTTP status code 410 - GONE."""
return make_json_response(
status=410,
success=0,
errormsg=errormsg
)
def not_implemented(errormsg=_('Not implemented.'), info='',
result=None, data=None):
"""Create a response with HTTP status code 501 - Not Implemented."""
return make_json_response(
status=501,
success=0,
errormsg=errormsg,
info=info,
result=result,
data=data
)
def service_unavailable(errormsg=_("Service Unavailable"), info='',
result=None, data=None):
"""Create a response with HTTP status code 503 - Server Unavailable."""
return make_json_response(
status=503,
success=0,
errormsg=errormsg,
info=info,
result=result,
data=data
)
def plain_text_response(message=''):
response = Response(message, status=200, mimetype="text/plain")
return response