Skip to content

Instantly share code, notes, and snippets.

@loisaidasam
Last active October 6, 2015 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loisaidasam/2987352 to your computer and use it in GitHub Desktop.
Save loisaidasam/2987352 to your computer and use it in GitHub Desktop.
Django API Request Decorator
import json
import logging
from django.http import HttpResponse
logger = logging.getLogger(__name__)
ALLOWED_REQUEST_TYPES = ('GET', 'POST', 'PUT', 'DELETE')
def api_request_decorator(*request_types):
"""Sample usage in views.py:
@api_request_decorator('POST')
def sample_api_endpoint(request):
return {'foo': 'bar'}
"""
def _return_response(response_dict, status=200):
response = json.dumps(response_dict)
return HttpResponse(response, status=status, content_type="application/javascript")
def _return_error_response(error):
response_dict = {'error': error}
return _return_response(response_dict, status=400)
for request_type in request_types:
if request_type not in ALLOWED_REQUEST_TYPES:
return _return_error_response("Invalid request_type specified")
def inner_decorator(func):
def inner(request, *args, **kwargs):
try:
if request.method not in request_types:
raise Exception('request type %s required for this method' % request_type)
return _return_response(func(request, *args, **kwargs))
except Exception, e:
logger.exception("Exception caught in API request: %s" % e)
return _return_error_response(e.message)
return inner
return inner_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment