Django REST framework教程——快速搭建项目

Django REST framework

文档/教程

快速搭建项目,简单展示一下如何使用django rest framework
我们将创建一个简单的API,能看到用户和组。

# 创建项目文件夹
mkdir tutorial
cd tutorial

# 创建环境并进入
python -m venv env
# win环境,linux source activate env
.\env\Scripts\activate.bat

# 安装包
pip install django
pip install djangorestframework

# 开启django项目,并创建了一个django-app
django-admin startproject tutorial
cd tutorial
django-admin startapp quickstart
cd ..


# 第一次同步数据库
python manage.py migrate
# 创建超级账户,admin 密码 password123
python manage.py createsuperuser --email admin@example.com --username admin

创建文件 tutorial/quickstart/serializers.py

from django.contrib.auth.models import User, Group
from rest_framework import serializers

# User Group 应该是django自带的表结构,这里直接使用django自带的

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User  
        fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group 
        fields = ['url', 'name']

HyperlinkedModelSerializer 是超链接关系,还有主键和其他的各种关系,现在可以不必纠结这里,先继续往下做,后续学习再进行补充。

创建 tutorial/quickstart/views.py

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer

# 这里就是熟悉的django的views
class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined') # 排序查询集
    serializer_class = UserSerializer    # 这是我们上面写的辣个类


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

创建 tutorial/urls.py

from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

tutorial/settings.py

# 设置分页
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

# 添加app
INSTALLED_APPS = [
    ...
    'rest_framework',
]

测试我们的API

# 启动程序
python manage.py runserver

# 浏览器访问
http://127.0.0.1:8000/users/

注意右上角的 Login 点击登录刚刚的账号

如果可以,说明我们的配置没有问题

系列教程
快速启动
1-序列化
2-请求与相应
3-基于类的views
4-身份验证和权限
5-关系和超链接API
6-视图和路由

你可能感兴趣的:(Django)