Django 的 REST framework 基础知识
Django REST framework 是一个建立在Django基础上的Web服务API工具。以下是一些基础概念和示例代码:
- 序列化: 将模型转换为JSON,以便可以通过API进行交互。
from rest_framework import serializers
from myapp.models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'
- 视图: 定义如何处理不同的HTTP请求。
from rest_framework import generics
class MyModelListView(generics.ListAPIView):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
- 视图集: 用于更快创建复杂API的工具。
from rest_framework import viewsets
class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
- 路由: 确保URLs指向正确的视图。
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myapp.views import MyModelListView, MyModelViewSet
router = DefaultRouter()
router.register(r'mymodel', MyModelViewSet)
urlpatterns = [
path('', include(router.urls)),
path('mymodel/list/', MyModelListView.as_view()),
]
- 认证和权限: 确保只有授权用户可以访问API。
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication', # 使用Token认证
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated', # 仅授权用户可访问
),
}
- 过滤、搜索、分页: 提高查询的灵活性。
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.pagination import PageNumberPagination
class MyModelListView(generics.ListAPIView):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
filter_backends = [SearchFilter, OrderingFilter]
search_fields = ['name', 'description']
ordering_fields = ['name', 'created_at']
pagination_class = PageNumberPagination
这些是Django REST framework中的基础概念和示例代码。它们展示了如何创建序列化器、视图、路由、认证、权限、过滤、搜索和分页,以构建功能齐全的API。
评论已关闭