Source

django-rest-api / rest_api / options.py

The default branch has multiple heads

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
"""

"""

from django.utils.functional import update_wrapper
from django.utils.text import capfirst
from django.core.urlresolvers import reverse, resolve
from django.db import IntegrityError, transaction
from django.db.models.fields import FieldDoesNotExist
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import force_unicode
from django.conf.urls.defaults import patterns, url
from django.forms import ValidationError

from decorators import methods
import http

import datetime
import logging

from models import LogEntry, ADDITION, CHANGE, DELETION

import re
def snake_case(string):
    return re.sub('([A-Z])', '_\\1', string).lower().strip('_')

class BaseApi(object):
    """
    
    """
    
    #: What methods are allowed on an object?
    allowed_methods = ('GET','PUT','DELETE')
    #: What methods are allowed on an index?
    allowed_methods_index = ('GET','POST')
    
    #: Set root path if you want it to be different to the snake_case name of
    #: the model. You will need to set this if you have two models in
    #: different apps with the same name.
    root_path = None
    
    def urls(self):
        return self.get_urls()
    urls = property(urls)

    def wrap(self, view, fields=None):
        def wrapper(*args, **kwargs):
            return self.api_site.api_view(view, fields=fields)(*args, **kwargs)
        wrapper.csrf_exempt = True
        return update_wrapper(wrapper, view)
    
    def dispatch(self, fields=None, **methods):
        """
        Hand off to a different instance method depending upon what the
        HTTP request method was (ie, POST, GET, PUT, etc)
        """
        lc_methods = dict( (method.lower(), handler) for (method, handler) in methods.iteritems() )

        def __dispatch(request, *args, **kwargs):
            handler = lc_methods.get(request.method.lower())
            if handler:
                return handler(request, *args, **kwargs)
            else:
                return http.MethodNotAllowed(list(m.upper() for m in lc_methods.keys()))
        __dispatch.require_auth = self.require_auth
        return self.wrap(__dispatch, fields=fields)
        
class BaseModelApi(BaseApi):
    """
    Functionality common to ModelApi, and InlineApi.
    """
    # Change the default ordering key for this API model
    ordering = ()
    # What fields do we want to show in this model? None -> all
    fields = None
    # By putting extra fields in we can show m2m, for instance, and attributes
    # that are not defined fields, but could be from .extra(), or so on.
    extra_fields = []
    # Which fields in the index view for this model?
    index_fields = ('name', 'href', 'id', 'type')
    # And which ones do we want to exclude?
    exclude = ('created', 'modified', 'created_at', 'updated_at')
    #: Include the whole object, rather than just a reference to it.
    embed_objects = []
    
class Api(BaseApi):
    def __init__(self, api_site):
        self.api_site = api_site
        self.root_path = self.root_path or snake_case(self.__class__.__name__)
        super(Api, self).__init__()
        
    def get_urls(self):
        return patterns('', url(r'^$', self.wrap(self.index)))

class ModelApi(BaseModelApi):
    
    def __init__(self, model, api_site):
        self.model = model
        self.opts = model._meta
        self.api_site = api_site
        self.fields = self.fields or [field.name for field in self.opts.fields if field.name not in self.exclude]
        if api_site.index_provides_data:
            self.index_fields = self.fields
        if not hasattr(model, 'href'):
            model.href = property(lambda x: reverse('api:%s_%s_object' % (model._meta.app_label, model._meta.module_name), args=(x.pk,)))
        self.root_path = self.root_path or snake_case(model.__name__)
        super(ModelApi, self).__init__()
        
    def get_urls(self):
        info = self.opts.app_label, self.opts.module_name
        
        urlpatterns = patterns('',
        url(r'^$',
                self.dispatch(get=self.index, 
                              post=self.create, 
                              fields=self.index_fields),
                name='%s_%s_index' % info),
        url(r'^(\d+)/$',
                self.dispatch(get=self.read, 
                              put=self.update, 
                              delete=self.delete,
                              fields=self.fields),
                name='%s_%s_object' % info),
        )
        
        return urlpatterns
    
    def has_add_permission(self, request):
        """
        Returns True if the given request has permission to add objects of
        this Django model.
        """
        opts = self.opts
        return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission())
    
    def has_view_permission(self, request, obj=None):
        """
        Returns True if the given request has permission to view the given
        Django model instance.
        
        If `obj` is None, this should return True if the given request has
        permission to view *an* object of the given type.
        
        This is likely to require overriding this method to enable per-object
        testing of if it should be viewable.
        """
        opts = self.opts
        if not opts.get_view_permission():
            return True
        return request.user.has_perm(opts.app_label + '.' + opts.get_view_permission())
    
    def has_change_permission(self, request, obj=None):
        """
        Returns True if the given request has permission to change the given
        Django model instance.
        
        If `obj` is None, this should return True if the given request has
        permission to change *an* object of the given type.
        """
        opts = self.opts
        return request.user.has_perm(opts.app_label + '.' + opts.get_change_permission()) \
            and self.has_view_permission(request, obj)
        
    def has_delete_permission(self, request, obj=None):
        """
        Returns True if the given request has permission to delete the given
        Django model instance.

        If `obj` is None, this should return True if the given request has
        permission to delete *an* object of the given type.
        """
        opts = self.opts
        return request.user.has_perm(opts.app_label + '.' + opts.get_delete_permission()) \
            and self.has_view_permission(request, obj)
    
    def get_model_perms(self, request):
        return {
            'view':self.has_view_permission(request),
            'add':self.has_add_permission(request),
            'change':self.has_change_permission(request),
            'delete':self.has_delete_permission(request),
        }

    def queryset(self, request):
        """
        Returns a QuerySet of all model instances that can be viewed by the
        given request.
        """
        qs = self.model._default_manager.get_query_set()
        
        # There is a setting on ModelApi for ordering by a certain field
        # that may be different from the default ordering.
        ordering = self.ordering or ()
        if ordering:
            qs = qs.order_by(*ordering)
        
        return qs
    
    
    def log_addition(self, request, object):
        """
        Log that an object has been added.
        """
        LogEntry.objects.log_action(
            user_id         = _get_user_pk(request),
            content_type_id = ContentType.objects.get_for_model(object).pk,
            object_id       = object.pk,
            object_repr     = force_unicode(object),
            action_flag     = ADDITION
        )
        logging.getLogger('rest-api').info("%s added by %s" % (
            force_unicode(object), _get_user(request))
        )
    
    def log_change(self, request, object, message):
        """
        Log that an object has been changed.
        """
        LogEntry.objects.log_action(
            user_id         = _get_user_pk(request),
            content_type_id = ContentType.objects.get_for_model(object).pk,
            object_id       = object.pk,
            object_repr     = force_unicode(object),
            action_flag     = CHANGE,
            change_message  = message
        )
        logging.getLogger('rest-api').info("%s updated by %s [%s]" % (
            force_unicode(object), _get_user(request), message)
        )
    
    def log_deletion(self, request, object, object_repr):
        """
        Log that an object has been deleted.
        """
        LogEntry.objects.log_action(
            user_id         = _get_user_pk(request),
            content_type_id = ContentType.objects.get_for_model(self.model).pk,
            object_id       = object.pk,
            object_repr     = object_repr,
            action_flag     = DELETION
        )
        logging.getLogger('rest-api').info("%s deleted by %s" % (object_repr, _get_user(request)))
            
    def index(self, request):
        return self.queryset(request)
        
    def read(self, request, pk):
        qs = self.queryset(request).filter(pk=pk)
        if self.has_view_permission(request, qs.get()):
            return qs
        raise http.Forbidden()
    
    def create(self, request):
        """
        We should be able to handle a single object, or a list of objects.
        
        If you want it to only succeed if they all succeed, then we need to
        have Transactions enabled in the MIDDLEWARE_CLASSES. Otherwise,
        objects will be created until one fails, and then it will return.
        
        Chances are you want the former, rather than the latter.
        """
        if not self.has_add_permission(request):
            raise http.Forbidden()
        
        # Ensure that we have a list of objects, in the case we only recvd
        # a single object.
        data = request.data
        if getattr(data, 'keys', False):
            data = [data]
        
        created = []
        related = {}
        for incoming in data:
            # We now need to ensure that any foreign key fields are objects,
            # not the keys.
            if incoming.has_key("id"):
                incoming.pop("id")
            for f in self.model._meta.fields:
                if getattr(f, 'related', False):
                    if f.name in incoming.keys():
                        if f.null and incoming[f.name] == '':
                            incoming[f.name] = None
                        if incoming[f.name]:
                            if not isinstance(incoming[f.name], f.rel.to):
                                # Check to see if it is already an object.
                                incoming[f.name] = f.rel.to.objects.get(pk=incoming[f.name])
            for f in self.model._meta.get_all_related_objects():
                # Not sure how m2m will go here.
                if incoming.get(f.get_accessor_name(), False):
                    related[f.get_accessor_name()] = incoming.pop(f.get_accessor_name())
            try:
                instance = self.model(**incoming)
                # If there are audit fields, then update the values.
                instance.created_by = request.user
                instance.updated_by = request.user
                instance.save()
                # Examine related fields, as we will need to create
                # new models, potentially with relations to other models.
                if related:
                    for accessor, obj in related.iteritems():
                        relation = getattr(instance, accessor)
                        model = relation.model
                        if not isinstance(obj, list):
                            obj = [obj]
                        for x in obj:
                            for k,v in x.iteritems():
                                field = model._meta.get_field_by_name(k)[0]
                                # If it is a related field, get the object,
                                # as we cannot create it without it.
                                if hasattr(field,'related'):
                                    x[k] = field.rel.to.objects.get(pk=v)
                            getattr(instance, accessor).create(**x)
                created.append(instance.pk)
            except (IntegrityError, TypeError, ValueError), arg:
                transaction.rollback()
                raise http.Conflict(arg.args[0])
        objects = self.model.objects.filter(pk__in=created)
        for obj in objects:
            self.log_addition(request, obj)
            obj.save()
        if len(objects):
            return http.Created(objects)
        return http.OK("Nothing created.")

    
    def update(self, request, pk):
        qs = self.queryset(request).filter(pk=pk)
        # If we didn't find any objects, hand off to create()
        if not qs.exists():
            return self.create(request)
        
        if not hasattr(request.data, 'keys'):
            # Might be a list
            if len(request.data) == 1:
                request.data = request.data[0]
            else:
                raise http.BadRequest('Cannot update an object with more than one item.')
                
        instance = qs.get()
        if not self.has_change_permission(request, instance):
            raise http.Forbidden()
        
        changed = {}
        for key,value in request.data.iteritems():
            # We don't mind if things are passed in that we don't know about.
            # Just ignore them.
            if not hasattr(instance, key):
                continue
            try:
                field = instance._meta.get_field(key)
                # We don't want to be changing primary keys of objects.
                if field.primary_key:
                    continue
                # If this is a field that is automatically update, we can
                # ignore the passed in value(s)
                if getattr(field, 'auto_now', False) or getattr(field, 'auto_now_add', False):
                    continue
                # If this was an audit field, ignore it. We set these according to the user who ran the request.
                if field.name == 'updated_by' or field.name == 'created_by':
                    continue
                if not field.empty_strings_allowed and field.null and value == "":
                    # I hate that django wants to store "" in the database
                    # when I really mean None.
                    setattr(instance, key, None)
                    continue
                if field.value_from_object(instance) != field.to_python(value):
                    # Do I need to serialize this?
                    if field.rel:
                        if value is not None:
                            rel_obj = field.rel.to.objects.get(pk=value)
                        else:
                            rel_obj = None
                        setattr(instance, key, rel_obj)
                        changed[key] = unicode(rel_obj)
                        #TODO: set the changed value to the __unicode__ of the referenced object,
                        # but this will require another database request for each change.
                    else:
                        setattr(instance, key, field.to_python(value))
                        changed[key] = value
            except FieldDoesNotExist:
                # There was no field. There may be an attribute, that alters
                # something, or a reverse relation on a ForeignKey
                if hasattr(getattr(instance, key), 'all'):
                    # Maybe a ForeignKey?
                    # For now, just delete all of the values, and
                    # create new ones. Eventually, we want to be able to
                    # compare what is already there, and mark changes.
                    getattr(instance, key).all().delete()
                    for val in value:
                        for k,v in val.items():
                            f = getattr(instance, key).model._meta.get_field(k)
                            if f.primary_key:
                                del val[k]
                                continue
                            if getattr(f, 'auto_now', False) or getattr(f, 'auto_now_add', False):
                                del val[k]
                                continue
                            if f.name == 'updated_by':
                                val[k] = request.user
                                continue
                            if f.name == 'created_by':
                                val[k] = request.user
                                continue
                            if f.rel:
                                val[k] = f.rel.to.objects.get(pk=v)
                        getattr(instance, key).create(**val)
                elif getattr(instance, key) != value:
                    try:
                        setattr(instance, key, value)
                        changed[key] = value
                    except AttributeError:
                        # Could not set this attribute: read-only?
                        pass
                
        instance.updated_by = request.user
        try:
            instance.save()
        except IntegrityError, arg:
            transaction.rollback()
            raise http.Conflict(arg.args[0])

        if len(changed):
            message = "Changed %s." % ", ".join(["%s to %s" % x for x in changed.iteritems()])
            #TODO: instance should reflect the new values?
            self.log_change(request, instance, message)

        return self.model._default_manager.filter(pk=pk)
    
    def delete(self, request, pk):
        qs = self.queryset(request).filter(pk=pk)
        if qs.count() == 0:
            return http.Deleted()
        instance = qs.get()
        if self.has_delete_permission(request, instance):
            instance.delete()
            self.log_deletion(request, instance, unicode(instance))
            return qs
        raise http.Forbidden()

class InlineApi(BaseModelApi):
    """
    A model that is a related model of another.
    
    It is not accessible as /root/model/, but rather only as
    /root/parent/:id/models/.
    """
    pass

# Monkey-patch to add in get_view_permission().
from django.db.models.options import Options

def get_view_permission(self):
    if 'view_%s' % self.object_name.lower() in map(lambda x: x[0], 
        self.permissions):
        return 'view_%s' % self.object_name.lower()
    return None

Options.get_view_permission = get_view_permission

def _get_user_pk(request):
    """
    This is used to log the user who is logged in, even if they are
    masquerading as another user.
    """
    try:
        return _get_user(request).pk
    except AttributeError:
        return request.user.pk

def _get_user(request):
    """
    This is used to log the user who is logged in, even if they are
    masquerading as another user.
    """
    return getattr(request, 'real_user', request.user)