Skip to content

Instantly share code, notes, and snippets.

@shofetim
Created May 8, 2013 23:14
Show Gist options
  • Select an option

  • Save shofetim/5544399 to your computer and use it in GitHub Desktop.

Select an option

Save shofetim/5544399 to your computer and use it in GitHub Desktop.
class BaseView(object):
"""
BaseView provides a class that is instantiated and then
called like a function.
__init__ called without arguments.
You just (must) override the __call__ method.
"""
def __new__(cls, *args, **kwargs):
obj = super(BaseView, cls).__new__(cls)
return obj(*args, **kwargs)
def __call__(self, *args, **kwargs):
pass
from django.http import HttpResponse
class REST(BaseView):
"""
A class to handle CRUD boilerplate for Backbone.js requests.
Override methods as needed, be sure to set the model class in the child class.
"""
def __call__(self, request, *args, **kwargs):
func = getattr(self, request.method.lower(), "get")
if kwargs.get("id", None):
self.object_id = int(kwargs.get("id", None))
else:
self.object_id = None
return func(request, *args, **kwargs)
model_class = None #Override in child classes.
# HTTP methods www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
def get(self, request, *args, **kwargs):
if self.object_id:
data = self.model_class.objects.get(pk=self.object_id)
else:
data = self.model_class.objects.all()
return HttpResponse(to_json(data), content_type="application/json")
def post(self, request, *args, **kwargs):
data = parse_json(request.body)
obj = self.model_class(**data)
obj.save()
return HttpResponse(to_json(obj), content_type="application/json")
def put(self, request, *args, **kwargs):
data = parse_json(request.body)
obj = self.model_class.objects.get(pk=self.object_id)
for field in data.keys():
setattr(obj, field, data[field])
obj.save()
return HttpResponse(to_json(obj), content_type="application/json")
def delete(self, request, *args, **kwargs):
obj = self.model_class.objects.get(pk=self.object_id)
obj.delete()
return HttpResponse("", content_type="application/json")
def head(self, request, *args, **kwargs):
return self.get(request, *args, **kwargs)
def options(self, request, *args, **kwargs):
raise NotImplementedError
def trace(self, request, *args, **kwargs):
raise NotImplementedError
def connect(self, request, *args, **kwargs):
raise NotImplementedError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment