📜  django drf - Python (1)

📅  最后修改于: 2023-12-03 14:40:46.116000             🧑  作者: Mango

Django DRF - Python

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs, based on the Django web framework. It provides a set of reusable, modular components for building RESTful APIs. DRF is designed to work with Django, and provides a seamless integration with the Django ORM and authentication system.

Key Features
  • Browsable API: DRF provides a built-in view that generates a web-based UI for your API. You can browse, test, and interact with your API using a web browser, without any additional tools.
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from django.http import HttpResponse

class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)
  • Serialization: DRF provides a powerful serialization engine that allows you to easily convert complex data types (e.g., Django model instances) to and from JSON or other content types.
from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES

class SnippetSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(required=False, allow_blank=True, max_length=100)
    code = serializers.CharField(style={'base_template': 'textarea.html'})
    linenos = serializers.BooleanField(required=False)
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
    style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')

    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        return Snippet.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `Snippet` instance, given the validated data.
        """
        instance.title = validated_data.get('title', instance.title)
        instance.code = validated_data.get('code', instance.code)
        instance.linenos = validated_data.get('linenos', instance.linenos)
        instance.language = validated_data.get('language', instance.language)
        instance.style = validated_data.get('style', instance.style)
        instance.save()
        return instance
  • Authentication: DRF provides a flexible authentication system that supports a variety of authentication methods (e.g., token-based authentication, OAuth2).
from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response

class ExampleView(APIView):
    authentication_classes = [TokenAuthentication,]
    permission_classes = [IsAuthenticated,]

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)
  • Viewsets: DRF provides powerful viewsets that allow you to define CRUD (Create, Retrieve, Update, Delete) operations for a given model with minimal code.
from rest_framework import viewsets
from .models import Book, Author
from .serializers import BookSerializer, AuthorSerializer

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer
Conclusion

Django REST framework is a powerful and flexible toolkit for building Web APIs with Python. It provides a set of reusable, modular components that allow you to easily build RESTful APIs with minimal code. With its powerful features like serialization, authentication, and viewsets, DRF makes it easy to develop high-quality, well-documented APIs.