Skip to content

Instantly share code, notes, and snippets.

@emiel
Created February 16, 2017 17:51
Show Gist options
  • Save emiel/1cbc4af357e89792754f93f64ea6a969 to your computer and use it in GitHub Desktop.
Save emiel/1cbc4af357e89792754f93f64ea6a969 to your computer and use it in GitHub Desktop.
Simple Django REST API
from django.http import HttpResponse
class ApiResponse(HttpResponse):
def __init__(data, **kwargs):
kwargs.setdefault("content_type", "application/json")
content = json.dumps(data)
super(ApiResponse, self).__init__(content=data, **kwargs)
class ApiException(Exception):
def __init__(self, message, status=400):
self.message = message
self.status = status
def to_response(self):
return ApiResponse({"message": self.message}, status=self.status)
class ApiMiddleWare(object):
def process_exception(request, exception):
if instanceof(ApiException, exception):
return exception.to_response()
else:
return None
def add_numbers(request):
a = request.GET.get("a", None)
b = request.GET.get("b", None)
result = {"sum": a + b}
return ApiResponse(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment