Part 1 - Serialization
:
class ExtraPostResource(object):
def deserialize(self, request, data, format=None):
"""
Changes request stat in to python objects
"""
if not format:
format = request.META.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
multipart_data = request.POST.copy()
multipart_data.update(request.FILES)
return multipart_data
return super(ExtraPostResource, self).deserialize(request, data, format)
, :
class MyModel(ExtraPostResource, ModelResource):
class Meta:
serializer = Serializer(formats=['json'])
queryset = MyModel.objects.all()
resource_name = 'my_model'
application/x-www-form-urlencoded, multipart .
2 - 500
500.
try:
from django.views.decorators.csrf import csrf_exempt
except ImportError:
def csrf_exempt(func):
return func
class MyBaseModelResource(ModelResource):
"""
Basically it defines own error feedback format.
"""
def wrap_view(self, view):
"""
Wraps views to return custom error codes instead of generic 500's.
"""
@csrf_exempt
def wrapper(request, *args, **kwargs):
try:
callback = getattr(self, view)
response = callback(request, *args, **kwargs)
if request.is_ajax():
patch_cache_control(response, no_cache=True)
return response
except UnsupportedFormat, e:
return self.create_response(
request,
{'success': False,
'code': 123,
'message': e},
response_class=HttpBadRequest,
)
except Exception, e:
return self._handle_500(request, e)
return wrapper
* (1) , Tastypie, . .