django-rest-framework
网址:
https://www.django-rest-framework.org/
支持:
- Python (3.6, 3.7, 3.8, 3.9, 3.10)
- Django (2.2, 3.0, 3.1, 3.2, 4.0)
安装:
-
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
- 或
git clone https://github.com/encode/django-rest-framework
注册:
Add 'rest_framework' to your INSTALLED_APPS setting.
INSTALLED_APPS = [
...
'rest_framework',
]
url:
urlpatterns = [
...
path('api-auth/', include('rest_framework.urls'))
]
权限:
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
实例:
# 序列化Serializers
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets
class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'is_staff'class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # 路由Routers
from django.urls import path, include
from rest_framework import routers
router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
实例截图:
settings设置:
序列化设置:
视图设置:
路由设置:
关联下一层:
多个处理:many=True