def ajax_request args Checks request method is POST Return error in JS

 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
def ajax_request(*args):
"""
Checks request.method is POST. Return error in JSON in other case.
If view returned dict, returns JsonResponse with this dict as content.
Parameters should be either function (then it will decorated) or strings
with names of required POST variables (then actual decorator will be
returned).
"""
# python doesn't have "function" type in global namespace
if isinstance(args[0], type(wraps)):
required = []
else:
required = args
def ajax_request_inner(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
if request.method == 'POST':
for arg in required:
if arg not in request.POST:
# return immediately so there is no need to deal
# with response assigments later in code
return JsonResponse({'error': {'type': 400,
'message': 'POST parameter %s is required in %s' % (arg, request.POST)}})
response = func(request, *args, **kwargs)
else:
response = {'error': {'type': 403,
'message': 'Accepts only POST request'}}
if isinstance(response, dict):
return JsonResponse(response)
else:
return response
return wrapper
if required:
# there were required parameters so decorator should be returned
return ajax_request_inner
return ajax_request_inner(args[0])