创建项目目录
- mkdir tutorial
- cd tutorial
创建一个virtualenv来隔离我们本地的包依赖关系
- python -m venv venv
- env\Scripts\activate
创建项目
- pip install djangorestframework
创建一个新项目和一个单个应用
- django-admin startproject tutorial .
- django-admin startapp quickstart
- cd ..
同步数据库
- python manage.py migrate
创建超级用户
- python manage.py createsuperuser
编写序列化器
- tutorial/quickstart/serializers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
编写试图
- tutorial/quickstart/views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
允许用户查看或编辑的API路径。
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
允许组查看或编辑的API路径。
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
编写路由
- tutorial/urls.py
from django.conf.urls import include
from rest_framework import routers
from tutorial.quickstart import views
from django.urls import path
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# 使用自动URL路由连接我们的API。
# 另外,我们还包括支持浏览器浏览API的登录URL。
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
设置管理专属分页
- tutorial/settings.py
INSTALLED_APPS = (
...
'rest_framework',
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAdminUser',
],
'PAGE_SIZE': 10
}
启动项目
- python manage.py runserver
测试访问
curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
标签:python,py,rest,framework,虚拟环境,使用,import,class,tutorial From: https://www.cnblogs.com/guanchaoguo/p/16931799.html