Skip to content

Instantly share code, notes, and snippets.

@SeanHayes
Created July 16, 2012 17:43
Show Gist options
  • Save SeanHayes/3123965 to your computer and use it in GitHub Desktop.
Save SeanHayes/3123965 to your computer and use it in GitHub Desktop.
Custom TastyPie resource that returns the correct HTTP status code when
from tastypie import http
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.resources import ModelResource
class CustomModelResource(ModelResource):
def obj_get(self, request=None, **kwargs):
try:
return super(CustomModelResource, self).obj_get(request=request, **kwargs)
except ObjectDoesNotExist:
# only branch if kwargs were supplied, which indicates filtering
# should be applied. If there's no search parameters (not even a pk),
# then testing for existence is pointless and can cause incorrect
# returning of http.HttpUnauthorized() (sometimes this method is
# called on a related resource without any kwargs).
if kwargs:
exists = self.get_object_list(request).filter(**kwargs).exists()
# If the object exists but this particular user doesn't have access,
# then we should let users know they're unauthorized instead of
# saying the object doesn't exist. Also, if TastyPie thinks the
# object doesn't exist, sometimes it'll try to recreate it (such
# as during a PUT request), resulting in a DB integrity error
# from trying to insert an existing primary key, and this snippet
# prevents that.
if exists:
raise ImmediateHttpResponse(response=http.HttpUnauthorized())
raise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment