Skip to content

Instantly share code, notes, and snippets.

View tomchristie's full-sized avatar
🌿

Tom Christie tomchristie

🌿
View GitHub Profile
class LinksSerializer(serializers.Serializer):
next = pagination.NextPageField(source='*')
prev = pagination.PreviousPageField(source='*')
def field_to_native(self, obj, field_name):
if self.source == '*':
return self.to_native(obj)
return super(self, LinksSerializer).field_to_native(obj, field_name)
class IsOwner(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_permission(self, request, view, obj=None):
# Skip the check unless this is an object-level test
if obj is None:
return True
class NoCSRFSessionAuthentication(BaseAuthentication):
"""
Use Django's session framework for authentication.
"""
def authenticate(self, request):
"""
Returns a `User` if the request session currently has a logged in user.
Otherwise returns `None`.
"""
def field_from_native(self, data, files, field_name, into):
into.update(self.from_native(data[field_name]))
from rest_framework import serializers
stuff = {'name': 'toran', 'other_content': {'foo': 'things', 'bar': 'stuff'}}
class ExampleSerializer(serializers.Serializer):
name = serializers.Field()
foo = serializers.Field(source='other_content.foo')
bar = serializers.Field(source='other_content.bar')
serializer = ExampleSerializer(stuff)
# `views.py`
@api_view(['GET', 'POST']) # Or whatever methods the view should support.
def whatever(request):
...
return Response(some_data) # `some_data` should be any native python json-serializable stuff.
# `settings.py`
from rest_framework import exceptions
...
try
data = request.DATA
except exceptions.ParseError
data = '[Invalid data in request]'
from django.conf.urls import patterns, url, include
from rest_framework.routers import AutoRouter
urlpatterns = patterns('',
url(r'^', include(AutoRouter().urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
@tomchristie
tomchristie / gist:5705771
Created June 4, 2013 13:11
ObjectSerializer
class ObjectSerializer(Serializer):
def get_default_fields(self, obj, nested):
"""
Given an object, return the default set of fields to serialize.
"""
ret = SortedDict()
attrs = [key for key in obj.__dict__.keys() if not(key.startswith('_'))]
for attr in sorted(attrs):
if nested:
ret[attr] = self.__class__()
class ExtendedRouter(SimpleRouter):
routes = SimpleRouter.routes + [
Route(
url=r'^{prefix}/{lookup}/{methodname}/(?P<slug>[^/]+){trailing_slash}$',
mapping={
'{httpmethod}': '{methodname}',
},
name='{basename}-{methodnamehyphen}-slug',
initkwargs={}
),