Skip to content

Instantly share code, notes, and snippets.

@anthonycintron
Created March 20, 2012 13:24
Show Gist options
  • Save anthonycintron/2135532 to your computer and use it in GitHub Desktop.
Save anthonycintron/2135532 to your computer and use it in GitHub Desktop.
Backbone & Tastypie
# -*- coding: utf-8 -*-
from tastypie.http import HttpResponse
class HttpAccepted(HttpResponse):
status_code = 202
# -*- coding: utf-8 -*-
from tastypie.exceptions import NotFound
from tastypie.http import HttpCreated, HttpResponse
from http import HttpAccepted
class BackboneResource(ModelResource):
def create_response(self, request, data, response_class=HttpResponse, **kwargs):
desired_format = self.determine_format(request)
serialized = self.serialize(request, data, desired_format)
return response_class(content=serialized, content_type=build_content_type(desired_format), **kwargs)
def post_list(self, request, **kwargs):
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))
self.is_valid(bundle, request)
bundle = self.obj_create(bundle, request, **self.remove_api_resource_names(kwargs))
return self.create_response(request, self.full_dehydrate(bundle.obj), HttpCreated, location=self.get_resource_uri(bundle))
def put_detail(self, request, **kwargs):
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized))
self.is_valid(bundle, request)
try:
bundle = self.obj_update(bundle, request=request, **self.remove_api_resource_names(kwargs))
return self.create_response(request, self.full_dehydrate(bundle.obj), HttpAccepted)
except (NotFound, MultipleObjectsReturned):
bundle = self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))
return self.create_response(request, self.full_dehydrate(bundle.obj), HttpCreated, location=self.get_resource_uri(bundle))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment