pip install djangorestframework INSTALLED_APPS = [ ... 'django_rest_framework', ] python from rest_framework.views import APIView from rest_framework.response import Response class HelloWorldView(APIView): def get(self, request): message = {'message': 'Hello, World!'} return Response(message) python from django.urls import path from api.views import HelloWorldView urlpatterns = [ path('hello/', HelloWorldView.as_view(), name='hello-world'), ] python from rest_framework import serializers class BookSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) author = serializers.CharField(max_length=100) publication_date = serializers.DateField() class BookView(APIView): def get(self, request): book_data = {'title': 'Django REST framework', 'author': 'John Smith', 'publication_date': '2022-01-01'} serializer = BookSerializer(book_data) return Response(serializer.data) python from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView class PrivateView(APIView): authentication_classes = [SessionAuthentication] permission_classes = [IsAuthenticated] def get(self, request): return Response({'message': 'This is a private view!'})


上一篇:
下一篇:
切换中文