Skip to content

Instantly share code, notes, and snippets.

View tomchristie's full-sized avatar
🌿

Tom Christie tomchristie

🌿
View GitHub Profile
@tomchristie
tomchristie / gist:1372745
Created November 17, 2011 09:02
Dont attempt to connect to the Selenium server at import; Check at the start of every test.
class SeleniumTestCase(LiveServerTestCase):
@property
def selenium_server_running(self):
"""
Determine if we can connect to the Selenium RC server.
"""
try:
conn = httplib.HTTPConnection(settings.SELENIUM_SERVER_HOST,
settings.SELENIUM_SERVER_PORT)
@tomchristie
tomchristie / gist:3499147
Created August 28, 2012 15:31
Example of writing views with django-serializers
# serializers.py
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
def restore_object(self, attrs, instance=None):
"""
Create or update a new comment instance.
class GetAccessToken(APIView):
authentication_classes = [authentication.UserBasicAuthentication]
permission_classes = [permissions.UserIsAuthenticated]
model = djangorestframework.basictoken.models.BasicToken
def post(self, request, *args, **kwargs):
token = self.model.objects.get_or_create(user=request.user)
return Response({'key': token.key})
class TokenAuthentication(BaseAuthentication):
model = djangorestframework.tokenauth.models.Token
def authenticate(self, request):
key = request.META.get('HTTP_AUTHORIZATION', '').strip()
if not key:
return None
try:
token = self.model.objects.get(key=key)
class MultipleObjectBaseView(MultipleObjectMixin, BaseView):
"""
Base class for generic views onto a queryset.
"""
pagination_serializer_class = api_settings.PAGINATION_SERIALIZER
paginate_by = api_settings.PAGINATE_BY
filter_class = None
filter_fields = None
# Currently in initial()
if not self.has_permission(request):
self.permission_denied(request)
self.check_throttles(request)
# May be this...
if not self.has_permission(request):
if request._authenticated:
self.permission_denied(request)
else:
@tomchristie
tomchristie / models.py
Created October 26, 2012 11:19
SnippetSerializer
class SnippetSerializer(serializers.Serializer):
title = serializers.CharField(required=False,
max_length=100)
code = serializers.CharField(widget=widgets.Textarea,
max_length=100000)
linenos = serializers.BooleanField(required=False)
lexer = serializers.ChoiceField(choices=models.LEXER_CHOICES,
default='python')
style = serializers.ChoiceField(choices=models.STYLE_CHOICES,
default='friendly')

Filtering

The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.

— [Django documentation][cite]

The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.

The simplest way to filter the queryset of any view that subclasses MultipleObjectAPIView is to override the .get_queryset() method.

@tomchristie
tomchristie / gist:4285537
Created December 14, 2012 13:40
REST framework. CSRF
[13:33:03] <mikeywaites> whats the prefered way to disable csrf for resources?
[13:33:09] <mikeywaites> in v2.x
[13:33:47] <mikeywaites> ping tomchristie
[13:36:06] <tomchristie> mikeywaites: This needs docs.
[13:36:25] <tomchristie> If your using SessionAuthentication answer is dont do that.
[13:36:38] <tomchristie> If you using any other auth, csrf wont apply
[13:36:54] <tomchristie> Django docs have a section on using CSRF with AJAX
[13:37:23] <tomchristie> If you really want to be bad best answer would be use a custom auth
[13:37:37] <tomchristie> Crib from the session auth, and just drop the bit that performs CSRF
# Explicit registry
router = DefaultRouter()
router.register(r'^snippets/', resources.SnippetResource, 'snippet')
router.register(r'^users/', resources.UserResource, 'user')
urlpatterns = router.urlpatterns
# Auto register
router = DefaultRouter()
router.auto_register()
urlpatterns = router.urlpatterns