Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple Django RestView view class
from django.http import HttpResponse, JsonResponse, HttpResponseForbidden, HttpResponseNotAllowed, HttpResponseNotFound
from django.forms.models import model_to_dict
from django.db.models import Model
from django.db.models.query import QuerySet
from functools import wraps
from django.utils.decorators import available_attrs
from django.core import serializers
class PermissionError(Exception):
class RestView(object):
Subclass this and add GET / POST / etc methods.
allowed_methods = ('GET', 'PUT', 'POST', 'DELETE', 'HEAD', 'OPTIONS')
authenticated_methods = ('PUT', 'POST', 'DELETE')
_allowed_methods = []
request = None
response_type = 'json'
jsonp_callbackfn = 'callback'
def __init__(self):
self._allowed_methods = [method for method in self.allowed_methods if hasattr(self, method)]
def __call__(self, request, *args, **kwargs):
self.request = request
method = request.method.upper()
if method == 'GET' and request.GET.get('callback'):
self.response_type = 'jsonp'
self.jsonp_callbackfn = request.GET.get('callback')
if not method in self._allowed_methods:
return self.method_not_allowed()
if method in self.authenticated_methods and not request.user.is_authenticated():
return self.authentication_required()
return getattr(self, method)(request, *args, **kwargs)
except PermissionError:
return self.permission_required()
def check_permission(self, perm):
if not isinstance(perm, (list, tuple)):
perms = (perm, )
perms = perm
# Check if the user has the permission (even anon users)
if not self.request.user.has_perms(perms):
raise PermissionError("PERMISSION_REQUIRED")
def permission_required(self):
return HttpResponse('401 Unauthorized', status=401)
def authentication_required(self):
return HttpResponseForbidden(self._allowed_methods)
def method_not_allowed(self, allowed_methods):
return HttpResponseNotAllowed()
def not_found(self):
return HttpResponseNotFound()
def response(self, context, success=True, errors=[]):
if isinstance(context, Model):
context = model_to_dict(context)
if isinstance(context, QuerySet):
context = list(context)
json_response = JsonResponse({'success': success, 'data': context, 'errors': errors}, safe=False)
if self.response_type == 'jsonp':
return HttpResponse('%s(%s)' % (self.jsonp_callbackfn, json_response.content), content_type='text/javascript')
return json_response
class TestView(RestView):
    allowed_methods = ('GET', 'PUT')
    authenticated_methods = ('PUT',)

    def GET(self, request):
        data = {'operationResult': True}
        return self.response(data)
    def PUT(self, request):
        data = {'object': True}
        return self.response(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.