Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / ui / userdata / rest.py @ 5facd191

History | View | Annotate | Download (8.4 kB)

1
#
2
# Copyright 2011 GRNET S.A. All rights reserved.
3
#
4
# Redistribution and use in source and binary forms, with or
5
# without modification, are permitted provided that the following
6
# conditions are met:
7
#
8
#   1. Redistributions of source code must retain the above
9
#      copyright notice, this list of conditions and the following
10
#      disclaimer.
11
#
12
#   2. Redistributions in binary form must reproduce the above
13
#      copyright notice, this list of conditions and the following
14
#      disclaimer in the documentation and/or other materials
15
#      provided with the distribution.
16
#
17
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
# POSSIBILITY OF SUCH DAMAGE.
29
#
30
# The views and conclusions contained in the software and
31
# documentation are those of the authors and should not be
32
# interpreted as representing official policies, either expressed
33
# or implied, of GRNET S.A.
34

    
35
from django import http
36
from django.template import RequestContext, loader
37
from django.utils import simplejson as json
38
from django.core import serializers
39
from django.core.urlresolvers import reverse
40

    
41
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
42

    
43
from synnefo.lib.astakos import get_user
44
from django.conf import settings
45

    
46
# base view class
47
# https://github.com/bfirsh/django-class-based-views/blob/master/class_based_views/base.py
48

    
49

    
50
class View(object):
51
    """
52
    Intentionally simple parent class for all views. Only implements
53
    dispatch-by-method and simple sanity checking.
54
    """
55

    
56
    method_names = ['GET', 'POST', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE']
57

    
58
    def __init__(self, *args, **kwargs):
59
        """
60
        Constructor. Called in the URLconf; can contain helpful extra
61
        keyword arguments, and other things.
62
        """
63
        # Go through keyword arguments, and either save their values to our
64
        # instance, or raise an error.
65
        for key, value in kwargs.items():
66
            if key in self.method_names:
67
                raise TypeError(u"You tried to pass in the %s method name as a"
68
                                u" keyword argument to %s(). Don't do that."
69
                                % (key, self.__class__.__name__))
70
            if hasattr(self, key):
71
                setattr(self, key, value)
72
            else:
73
                raise TypeError(u"%s() received an invalid keyword %r" % (
74
                    self.__class__.__name__,
75
                    key,
76
                ))
77

    
78
    @classmethod
79
    def as_view(cls, *initargs, **initkwargs):
80
        """
81
        Main entry point for a request-response process.
82
        """
83
        def view(request, *args, **kwargs):
84
            get_user(request, settings.ASTAKOS_URL)
85
            self = cls(*initargs, **initkwargs)
86
            return self.dispatch(request, *args, **kwargs)
87
        return view
88

    
89
    def dispatch(self, request, *args, **kwargs):
90
        # Try to dispatch to the right method for that; if it doesn't exist,
91
        # raise a big error.
92
        if hasattr(self, request.method.upper()):
93
            self.request = request
94
            self.args = args
95
            self.kwargs = kwargs
96
            data = request.raw_post_data
97

    
98
            if request.method.upper() in ['POST', 'PUT']:
99
                # Expect json data
100
                if request.META.get('CONTENT_TYPE').startswith('application/json'):
101
                    try:
102
                        data = json.loads(data)
103
                    except ValueError:
104
                        raise http.HttpResponseServerError('Invalid JSON data.')
105
                else:
106
                    raise http.HttpResponseServerError('Unsupported Content-Type.')
107
            try:
108
                return getattr(self, request.method.upper())(request, data, *args, **kwargs)
109
            except ValidationError, e:
110
                # specific response for validation errors
111
                return http.HttpResponseServerError(json.dumps({'errors':
112
                    e.message_dict, 'non_field_key':
113
                    NON_FIELD_ERRORS }))
114

    
115
        else:
116
            allowed_methods = [m for m in self.method_names if hasattr(self, m)]
117
            return http.HttpResponseNotAllowed(allowed_methods)
118

    
119

    
120
class JSONRestView(View):
121
    """
122
    Class that provides helpers to produce a json response
123
    """
124

    
125
    url_name = None
126
    def __init__(self, url_name, *args, **kwargs):
127
        self.url_name = url_name
128
        return super(JSONRestView, self).__init__(*args, **kwargs)
129

    
130
    def update_instance(self, i, data, exclude_fields=[]):
131
        update_keys = data.keys()
132
        for field in i._meta.get_all_field_names():
133
            if field in update_keys and (field not in exclude_fields):
134
                i.__setattr__(field, data[field])
135

    
136
        return i
137

    
138
    def instance_to_dict(self, i, exclude_fields=[]):
139
        """
140
        Convert model instance to python dict
141
        """
142
        d = {}
143
        d['uri'] = reverse(self.url_name, kwargs={'id': i.pk})
144

    
145
        for field in i._meta.get_all_field_names():
146
            if field in exclude_fields:
147
                continue
148

    
149
            d[field] = i.__getattribute__(field)
150
        return d
151

    
152
    def qs_to_dict_iter(self, qs, exclude_fields=[]):
153
        """
154
        Convert queryset to an iterator of model instances dicts
155
        """
156
        for i in qs:
157
            yield self.instance_to_dict(i, exclude_fields)
158

    
159
    def json_response(self, data):
160
        return http.HttpResponse(json.dumps(data), mimetype="application/json")
161

    
162

    
163
class ResourceView(JSONRestView):
164
    method_names = ['GET', 'POST', 'PUT', 'DELETE']
165

    
166
    model = None
167
    exclude_fields = []
168

    
169
    def queryset(self):
170
        return self.model.objects.all()
171

    
172
    def instance(self):
173
        """
174
        Retrieve selected instance based on url parameter
175

176
        id parameter should be set in urlpatterns expression
177
        """
178
        try:
179
            return self.queryset().get(pk=self.kwargs.get("id"))
180
        except self.model.DoesNotExist:
181
            raise http.Http404
182

    
183
    def GET(self, request, data, *args, **kwargs):
184
        return self.json_response(self.instance_to_dict(self.instance(),
185
            self.exclude_fields))
186

    
187
    def PUT(self, request, data, *args, **kwargs):
188
        instance = self.instance()
189
        self.update_instance(instance, data, self.exclude_fields)
190
        instance.full_clean()
191
        instance.save()
192
        return self.GET(request, data, *args, **kwargs)
193

    
194
    def DELETE(self, request, data, *args, **kwargs):
195
        self.instance().delete()
196
        return self.json_response("")
197

    
198

    
199
class CollectionView(JSONRestView):
200
    method_names = ['GET', 'POST']
201

    
202
    model = None
203
    exclude_fields = []
204

    
205
    def queryset(self):
206
        return self.model.objects.all()
207

    
208
    def GET(self, request, data, *args, **kwargs):
209
        return self.json_response(list(self.qs_to_dict_iter(self.queryset(),
210
            self.exclude_fields)))
211

    
212
    def POST(self, request, data, *args, **kwargs):
213
        instance = self.model()
214
        self.update_instance(instance, data, self.exclude_fields)
215
        instance.full_clean()
216
        instance.save()
217
        return self.json_response(self.instance_to_dict(instance,
218
            self.exclude_fields))
219

    
220

    
221
class UserResourceView(ResourceView):
222
    """
223
    Filter resource queryset for request user entries
224
    """
225
    def queryset(self):
226
        return super(UserResourceView,
227
                self).queryset().filter(user=self.request.user)
228

    
229

    
230
class UserCollectionView(CollectionView):
231
    """
232
    Filter collection queryset for request user entries
233
    """
234
    def queryset(self):
235
        return super(UserCollectionView, self).queryset().filter(user=self.request.user_uniq)
236

    
237
    def POST(self, request, data, *args, **kwargs):
238
        instance = self.model()
239
        self.update_instance(instance, data, self.exclude_fields)
240
        instance.user = request.user
241
        instance.full_clean()
242
        instance.save()
243
        return self.json_response(self.instance_to_dict(instance,
244
            self.exclude_fields))