def api_view(method):
"""Decorator that forces the view to require a valid
API key in order to be processed.
Calls to the view that do not have an appropriate key
will return a 403 response.
"""
def f(request, *args, **kwargs):
# Ensure that there is an appropriate key attached
# to this request, and return a 401 otherwise.
try:
APIAuth.verify_request(request)
except AuthenticationError as ex:
return HttpResponse(
content=json.dumps({
'code': 403,
'error': unicode(ex).strip("'"),
}),
content_type='application/json',
status=403,
)
# Run the decorated method.
try:
response = method(request, *args, **kwargs)
code = 200
# Sanity check: Did we get a tuple back?
# This shorthand provides me an easy way to send back
# a success response that is not a 200.
if isinstance(response, tuple) and len(response) == 2:
response, code = response
return HttpResponse(
json.dumps({
'code': code,
'data': response,
}, cls=JSONDatetimeEncoder),
content_type='application/json',
status=code,
)
except Http404 as ex:
msg = unicode(ex).strip("'")
return HttpResponse(
content=json.dumps({
'code': 404,
'error': msg if msg else 'not found',
}),
content_type='application/json',
status=404,
)
f = csrf_exempt(f)
return update_wrapper(f, method)
评论列表
文章目录