root / userdata / rest.py @ eee0487e
History | View | Annotate | Download (5.1 kB)
1 |
from django import http |
---|---|
2 |
from django.template import RequestContext, loader |
3 |
from django.utils import simplejson as json |
4 |
from django.core import serializers |
5 |
|
6 |
# base view class
|
7 |
# https://github.com/bfirsh/django-class-based-views/blob/master/class_based_views/base.py
|
8 |
class View(object): |
9 |
"""
|
10 |
Intentionally simple parent class for all views. Only implements
|
11 |
dispatch-by-method and simple sanity checking.
|
12 |
"""
|
13 |
|
14 |
method_names = ['GET', 'POST', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE'] |
15 |
|
16 |
def __init__(self, *args, **kwargs): |
17 |
"""
|
18 |
Constructor. Called in the URLconf; can contain helpful extra
|
19 |
keyword arguments, and other things.
|
20 |
"""
|
21 |
# Go through keyword arguments, and either save their values to our
|
22 |
# instance, or raise an error.
|
23 |
for key, value in kwargs.items(): |
24 |
if key in self.method_names: |
25 |
raise TypeError(u"You tried to pass in the %s method name as a " |
26 |
u"keyword argument to %s(). Don't do that."
|
27 |
% (key, self.__class__.__name__))
|
28 |
if hasattr(self, key): |
29 |
setattr(self, key, value) |
30 |
else:
|
31 |
raise TypeError(u"%s() received an invalid keyword %r" % ( |
32 |
self.__class__.__name__,
|
33 |
key, |
34 |
)) |
35 |
|
36 |
def instance_to_dict(self, i, exclude_fields=[]): |
37 |
"""
|
38 |
Convert model instance to python dict
|
39 |
"""
|
40 |
d = {} |
41 |
for field in i._meta.get_all_field_names(): |
42 |
if field in exclude_fields: |
43 |
continue
|
44 |
|
45 |
d[field] = i.__getattribute__(field) |
46 |
return d
|
47 |
|
48 |
def qs_to_dict_iter(self, qs, exclude_fields=[]): |
49 |
"""
|
50 |
Convert queryset to an iterator of model instances dicts
|
51 |
"""
|
52 |
for i in qs: |
53 |
yield self.instance_to_dict(i, exclude_fields) |
54 |
|
55 |
def json_response(self, data): |
56 |
return http.HttpResponse(json.dumps(data))
|
57 |
|
58 |
@classmethod
|
59 |
def as_view(cls, *initargs, **initkwargs): |
60 |
"""
|
61 |
Main entry point for a request-response process.
|
62 |
"""
|
63 |
def view(request, *args, **kwargs): |
64 |
self = cls(*initargs, **initkwargs)
|
65 |
return self.dispatch(request, *args, **kwargs) |
66 |
return view
|
67 |
|
68 |
def dispatch(self, request, *args, **kwargs): |
69 |
# Try to dispatch to the right method for that; if it doesn't exist,
|
70 |
# raise a big error.
|
71 |
if hasattr(self, request.method.upper()): |
72 |
self.request = request
|
73 |
self.args = args
|
74 |
self.kwargs = kwargs
|
75 |
data = request.raw_post_data |
76 |
|
77 |
if request.method.upper() in ['POST', 'PUT']: |
78 |
# Expect json data
|
79 |
if request.META.get('CONTENT_TYPE').startswith('application/json'): |
80 |
try:
|
81 |
data = json.loads(data) |
82 |
except ValueError: |
83 |
raise http.HttpResponseServerError('Invalid JSON data.') |
84 |
else:
|
85 |
raise http.HttpResponseServerError('Unsupported Content-Type.') |
86 |
|
87 |
return getattr(self, request.method.upper())(request, data, *args, **kwargs) |
88 |
else:
|
89 |
allowed_methods = [m for m in self.method_names if hasattr(self, m)] |
90 |
return http.HttpResponseNotAllowed(allowed_methods)
|
91 |
|
92 |
|
93 |
class ResourceView(View): |
94 |
method_names = ['GET', 'POST', 'PUT', 'DELETE'] |
95 |
|
96 |
model = None
|
97 |
exclude_fields = [] |
98 |
|
99 |
def queryset(self): |
100 |
return self.model.objects.all() |
101 |
|
102 |
def instance(self): |
103 |
"""
|
104 |
Retrieve selected instance based on url parameter
|
105 |
|
106 |
id parameter should be set in urlpatterns expression
|
107 |
"""
|
108 |
try:
|
109 |
return self.queryset().get(pk=self.kwargs.get("id")) |
110 |
except self.model.DoesNotExist: |
111 |
raise http.Http404
|
112 |
|
113 |
def GET(self, request, data, *args, **kwargs): |
114 |
return self.json_response(self.instance_to_dict(self.instance(), |
115 |
self.exclude_fields))
|
116 |
|
117 |
def POST(self, request, data, *args, **kwargs): |
118 |
pass
|
119 |
|
120 |
def DELETE(self, request, data, *args, **kwargs): |
121 |
self.instance().delete()
|
122 |
return HttpResponse()
|
123 |
|
124 |
|
125 |
class CollectionView(View): |
126 |
method_names = ['GET', 'POST', 'PUT', 'DELETE'] |
127 |
|
128 |
model = None
|
129 |
exclude_fields = [] |
130 |
|
131 |
def queryset(self): |
132 |
return self.model.objects.all() |
133 |
|
134 |
def GET(self, request, data, *args, **kwargs): |
135 |
return self.json_response(list(self.qs_to_dict_iter(self.queryset(), |
136 |
self.exclude_fields)))
|
137 |
|
138 |
def PUT(self, request, data, *args, **kwargs): |
139 |
pass
|
140 |
|
141 |
def DELETE(self, request, data, *args, **kwargs): |
142 |
pass
|
143 |
|
144 |
class UserResourceView(ResourceView): |
145 |
"""
|
146 |
Filter resource queryset for request user entries
|
147 |
"""
|
148 |
def queryset(self): |
149 |
return super(UserResourceView, |
150 |
self).queryset().filter(user=self.request.user) |
151 |
|
152 |
class UserCollectionView(CollectionView): |
153 |
"""
|
154 |
Filter collection queryset for request user entries
|
155 |
"""
|
156 |
def queryset(self): |
157 |
return super(UserCollectionView, self).queryset().filter(user=self.request.user) |
158 |
|