DRF 入门教程 01
环境
# windows
python version python3.7
django version 4.1
django-rest-framewrok 4.1
下载
pip install markdown # API 的 Markdown 的支持 version 3.4.3
pip install djangorestframework==3.14.0
pip install django==3.2.19
pip install django-filter # 过滤支持 version 23.2
创建程序
# windows win+r 打开终端
# 创建项目
django-admin startproject DjangoRestDemo
# 创建一个应用
cd DjangoRestDemo
python manage.py startapp appdemo
# 现在的目录是这样的
/*
+--- DjangoRestDemo
| +--- appdemo
| | +--- admin.py
| | +--- apps.py
| | +--- migrations
| | | +--- __init__.py
| | +--- models.py
| | +--- tests.py
| | +--- views.py
| | +--- __init__.py
| +--- DjangoRestDemo
| | +--- asgi.py
| | +--- settings.py
| | +--- urls.py
| | +--- wsgi.py
| | +--- __init__.py
| | +--- __pycache__
| | | +--- settings.cpython-37.pyc
| | | +--- __init__.cpython-37.pyc
| +--- manage.py
*/
配置
# 配置
DjangoRestDemo/DjanoRestDemo/setttings.py
# 添加如下内容。。。
INSTALLED_APPS = [
....
'rest_framework',
'appdemo.apps.AppdemoConfig',
]
启动
# 要在 manage.py 同级目录启动 DjangoRestDemo 下启动
python manage.py runserver
启动之后, 浏览器访问 http://127.0.0.1:8000/
# 你会看到一个火箭, 提示你 Django 创建成功
创建表
# /appdemo/models.py
# 添加如下内容
from django.db import models
class User(models.Model):
GENDER_CHOICES = (
(u'M', u'Male'),
(u'F', u'Female'),
)
u_name = models.CharField(max_length=20, unique=True, verbose_name='用户名称')
u_password = models.CharField(max_length=255, verbose_name='用户密码')
u_phone = models.CharField(max_length=11, verbose_name='用户手机号')
u_age = models.IntegerField(verbose_name='用户年龄')
u_gender = models.CharField(max_length=2, choices=GENDER_CHOICES, verbose_name='用户性别')
生成表
# 打开终端
# 我这里使用的是 sqlite3 所以没有配置数据库连接 sqlite3 是自带的,也不需要创建!
# 生成 models 的迁移文件
python manage.py makemigrations
/*
Migrations for 'appdemo':
appdemo\migrations\0001_initial.py
- Create model User
*/
# 将迁移文件同步到数据库中
python manage.py migrate
/*
Operations to perform:
Apply all migrations: admin, appdemo, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
.....
*/
创建第一个 Views
# 在 appdemo/views.py
# 添加如下入内
from rest_framework.views import APIView
from rest_framework.response import Response
class IndexViews(APIView):
def get(self, request, *args, **kwargs):
return Response('Test, Index, Views')
配置路由
# /DjangoRestDemo/DjangoRestDemo/urls.py
# 增加如下内容:
from appdemo.views import IndexViews
urlpatterns = [
...
path('', IndexViews.as_view())
]
# 启动
python manage.py runserver
# 浏览器访问 http://127.0.0.1:8000/
# 如果出现 Django REST framework 画面表示成功 并且浏览器上面有这句话 'Test, Index, Views'
对User表进行 APIView CURD(增删改查)
新增加序列化器
# 创建文件 appdemo/serializers.py
# 添加如下内容
# -*- coding: utf-8 -*-
from appdemo.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
增查
# 在 appdemo/views.py
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_404_NOT_FOUND, HTTP_201_CREATED, HTTP_400_BAD_REQUEST
from rest_framework.views import APIView
from appdemo.models import User
from appdemo.serializers import UserSerializer
class UserViewApi(APIView):
def get(self, request, *args, **kwargs):
"""
user: 是一个 QuerySet 对象!
序列化: 将一个 QuerySet 变为一个可以传递给前端的数据、
many=True 表示有多条数据 默认为 False 表示单条数据!
"""
user = User.objects.all()
if user.exists():
"""
UserSerializer 进行序列化!
user_serializer.data 这个就是传递给前端的值
type: <class 'rest_framework.utils.serializer_helpers.ReturnList'>
"""
user_serializer = UserSerializer(user, many=True)
print(type(user_serializer.data))
data = {"msg": "get user info success",
"status": HTTP_200_OK,
"user_list": user_serializer.data,
}
return Response(data)
else:
return Response(data={
"msg": "is null",
"status": HTTP_404_NOT_FOUND
}, )
def post(self, request, *args, **kwargs):
"""
反序列化: 将获取的转为python对象
"""
user_serializer = UserSerializer(data=request.data)
# is_valid 校验数据是否合法!
if user_serializer.is_valid():
# save 保存数据到数据库中!
user_serializer.save()
return Response(status=HTTP_201_CREATED, data=user_serializer.data)
return Response(data={"msg": "create Error", "status": HTTP_400_BAD_REQUEST})
添加路由
# /DjangoRestDemo/DjangoRestDemo/urls.py
# 注意:这里已经把 Index 的路由已经删掉了。。
# 增加如下内容:
from appdemo.views import UserViewApi
urlpatterns = [
path('', UserViewApi.as_view())
]
# 浏览器访问:
http://127.0.0.1:8000/
# 提交 post 请求, 使用 postman, 或者 http://127.0.0.1:8000/ rest 的 application/json 提交表单数据
# 测试数据
{
"u_name": "snake",
"u_password": "123456",
"u_phone": "110",
"u_age": 12,
"u_gender": "M"
}
新增
查询
修改
# 这里我没有拆分写 要获取用户的id,所以, 要修改一下路由。
class UserViewApi(APIView):
....
# 修改
def put(self, request, pk, *args, **kwargs):
try:
user = User.objects.get(id=pk)
except ObjectDoesNotExist:
return Response({'error': 'User not found'}, status=HTTP_404_NOT_FOUND)
serializer = UserSerializer(instance=user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"msg": " update successful", "status": HTTP_201_CREATED, "data": user.u_name})
# /DjangoRestDemo/DjangoRestDemo/urls.py
from appdemo.views import UserViewApi
urlpatterns = [
path('<int:pk>', UserViewApi.as_view())
]
先查询原先的数据是什么
修改u_name
在查询一下, 看一下有没有修改
修改不存在的 id 会提示用户不存在.
删除数据
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_404_NOT_FOUND, HTTP_201_CREATED, HTTP_400_BAD_REQUEST, \
HTTP_204_NO_CONTENT
from rest_framework.views import APIView
from appdemo.models import User
from appdemo.serializers import UserSerializer
class UserViewApi(APIView):
...
# 删除
def delete(self, request, pk, *args, **kwargs):
try:
user = User.objects.get(id=pk)
except ObjectDoesNotExist:
return Response({'error': 'User not found'}, status=HTTP_404_NOT_FOUND)
user.delete()
return Response({"status": HTTP_204_NO_CONTENT, "msg": "del successful", "id": user.id})
删除id=6数据之后, 在进行删除 就会提示, 用户没有找到!
以上就是 Rest APIView 对用户表的, 增删改查
postman 下载地址:https://www.postman.com/downloads/
后续会针对 user 表, 进行展开深入了解
笔记截图