Skip to content

Instantly share code, notes, and snippets.

@sorl
Last active January 20, 2016 08:42
Show Gist options
  • Save sorl/2887d902021c07a78ec1 to your computer and use it in GitHub Desktop.
Save sorl/2887d902021c07a78ec1 to your computer and use it in GitHub Desktop.
from django.http import HttpResponse
class ApiResource:
@classmethod
def dispatch(cls, request, *args, **kwargs):
if args or 'object_id' in kwargs:
if request.method == 'GET':
return cls.read(request, *args, **kwargs)
elif request.method == 'PUT':
return cls.update(request, *args, **kwargs)
elif request.method == 'DELETE':
return cls.delete(request, *args, **kwargs)
else:
if request.method == 'GET':
return cls.read_collection(request, *args, **kwargs)
if request.method == 'POST':
return cls.create(request, *args, **kwargs)
return HttpResponse(status=400)
def create(cls, request, *args, **kwargs):
raise NotImplemented
def read(cls, request, *args, **kwargs):
raise NotImplemented
def update(cls, request, *args, **kwargs):
raise NotImplemented
def delete(cls, request, *args, **kwargs):
raise NotImplemented
def read_collection(cls, request, *args, **kwargs):
raise NotImplemented
#views.py
from django.http import HttpResponse
from django.conf.urls import url
class ProductResource(ApiResource):
@property
@classmethod
def urls(cls):
return [
url(r'^$', cls.dispatch),
url(r'^([-\w]+)/?$', cls.dispatch),
]
@classmethod
def read(cls, request, id):
...
@classmethod
def create(cls, request, *args, **kwargs):
....
#urls
from django.conf.urls import url
urlpatterns = [
url('^products/', ProductResource.urls),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment