Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

Django REST Framework

1 636 vues

Publié le

These slides are from Jenny Olsson's lightning talk at the PyLadies Meetup in Stockholm June 15. Jenny is a backend developer at Load Impact.

Publié dans : Technologie
  • Identifiez-vous pour voir les commentaires

Django REST Framework

  1. 1. Django REST Framework Jenny Olsson Load Impact
  2. 2. Framework for building REST applications pip install djangorestframework Django REST Framework (DRF)
  3. 3. ● URL-routing ● Views/ViewSets ● Serializers What do you get from DRF:
  4. 4. We’ll assume we’ve got: ● A Django Application ● A Snail Model Let’s build a snail API!
  5. 5. Request: GET www.api.snails.com/snails/1 Reply: {'id': 1, 'name': 'Helix Aspersa', 'description': 'Common garden snail'} Example
  6. 6. from django.conf.urls import url, patterns, include from rest_framework import routers router = routers.DefaultRouter(trailing_slash=False) # /snails router.register(r'snails', SnailViewSet, base_name='snail') urlpatterns = (patterns( '', url('', include(router.urls)), )) URL routing
  7. 7. A ViewSet is a set of Views (this is a useful abstraction) This is where you: ● Handle the request ● Check permissions ● Authenticate ● Define allowed methods ViewSet
  8. 8. from rest_framework import viewsets from snail_app import models from serializers import SnailSerializer class SnailViewSet(viewsets.ModelViewSet): queryset = models.Snail.objects.all() serializer_class = SnailSerializer permission_classes = (IsMember,) /views/snails.py
  9. 9. This is where you: ● Validate input ● Format input data ● Format output data Serializers
  10. 10. from rest_framework import serializers from snail_app import models class SnailSerializer(serializers.ModelSerializer): class Meta: model = models.Snail fields = ( 'id', 'name', 'description' ) /serializers/snails.py
  11. 11. Request: GET www.api.snails.com/snails/1 Reply: {'id': 1, 'name': 'Helix Aspersa', 'description': 'Common garden snail'} Example
  12. 12. ● I want to show you some more hacky stuff, because reality I’ll go through how to ● Create a non REST endpoint ● Add a custom field to a serializer (and remove field) DRF Website has good tutorials
  13. 13. Standard REST endpoints are connected to resource: POST /snails <-- create snail GET /snails <--- list snails GET /snails/1 <--- get snail UPDATE /snails/1 <--- update snail But what if we want: POST /snails/1/befriend ← befriend snail Non REST endpoints
  14. 14. class SnailViewSet(viewsets.ModelViewSet): … @detail_route(methods=['post']) def befriend(self, request, pk=None): # Somehow befriend snail return Response({'msg': 'Yay got snail friend'}) Use @detail_route or @list_route
  15. 15. Since we use ViewSets the endpoint will be automatically routed. We can now befriend snails by posting to: /snails/1/befriend Automatic routing FTW
  16. 16. Our SnailSerializer is based on our model Snail. But what if we want to return something that’s not a model field? Adding custom fields
  17. 17. class SnailSerializer(serializers.ModelSerializer): extra_snail_fact = serializers.SerializerMethodField() class Meta: model = models.Snail fields = ('id', 'name', 'description', 'extra_snail_fact') def get_extra_snail_fact(self, obj): return 'snails really can’t swim:(' SerializerMethodField
  18. 18. Request: GET www.api.snails.com/snails/1 Reply: {'id': 1, 'name': 'Helix Aspersa', 'description': 'Common garden snail', 'extra_snail_fact': 'snails really can’t swim:('} Example
  19. 19. But what if we DON’T want to return all the fields from our model? class Snail(models.model): … super_embarrasing_hacky_field = 2 Removing fields
  20. 20. class SnailSerializer(serializers.ModelSerializer): class Meta: model = models.Snail fields = ('id', 'name', 'description') # Just don’t add it here SerializerMethodField
  21. 21. Django REST Framework is really powerful for making APIs out of Django applications. For something more lightweight I would probably recommend flask. Conclusion
  22. 22. Thanks for listening! Ping me later if you’ve got any questions! That’s it

×