亲爱的博友们,我周一回来了。上周的手术过程中出了一点点小意外,取钉的工具断了,还好有惊无险,感谢上苍。
一、依赖安装
这里需要安装djangorestframework、apiview。安装方法就不提了,见前面的分享。
二、详细步骤
我这里新建了一个车辆管理模块来演示本次进阶内容,新建子业务模块这里也不详细说了,建好表了,去看前面的分享。
1.settings.py修改
INSTALLED_APPS内容修改
代码如下:
INSTALLED_APPS = [
'simpleui', # 添加simpleui模块,先命令行安装pip install django-simpleui
'corsheaders', # 允许跨域
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# restfull支持
'rest_framework',
# 以下是业务模块 #
'user', # 添加user模块,用django-admin命令创建最好,django-admin startapp user
'car'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # 跨域中间件,要放在第一行
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware', # 接口权限校验中间件
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
2.urls配置
car子模块的urls.py
from django.urls import path
from . import views
urlpatterns = [
path('carList', views.carList),
]
项目的urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.static import serve
from rest_framework import routers
from user import views as user_views
from car import views as car_views
# 生成api交互的根视图
router = routers.DefaultRouter()
# router注册
router.register(r'carInfo', car_views.CarInfoViewSet)
urlpatterns = [
path('admin/', admin.site.urls), # django admin的url配置
re_path(r'upload/(?P<path>.*)$', serve, {
'document_root': 'upload'}), # 上传文件路径访问的url配置
# 子模块的接口url直接配置再根urls里-开始
path('userList', user_views.userList),
path('userLogin', user_views.userLogin),
path('carList', car_views.carList),
# 子模块的接口url直接配置再根urls里-结束
# restfull/引入子模块的urls配置
path('car/', include('car.urls')),
# api根视图、路由配置
path('api/', include(router.urls)), # 直接访问,可见注册模块的接口url
path('api/auth/', include('rest_framework.urls', namespace='rest_framework')),
]
3.自定义序列器
serializer.py
"""
Desc:实现序列化
"""
from rest_framework import serializers
from .models import CarInfo
# 车辆列表序列化
class CarInfoListSerializer(serializers.ModelSerializer):
class Meta:
model = CarInfo
fields = [
'id',
'car_no',
'car_color',
'car_type',
'memo',
'create_time'
]
4.views视图
# Create your views here.
from rest_framework import status as framework_status, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from car.models import CarInfo
from .serializer import CarInfoListSerializer
# viewset、路由方式,能提供基本的增删改查
class CarInfoViewSet(viewsets.ModelViewSet):
queryset = CarInfo.objects.all()
serializer_class = CarInfoListSerializer
# restful接口方式
@api_view(["GET", "POST"])
def carList(request):
# 查询数据
car_list = CarInfo.objects.all().order_by("-create_time")
serializer = CarInfoListSerializer(car_list, many=True) # many =True依次序列化每一项
# return Response(serializer.data,status=framework_status.HTTP_200_OK) 只返回了序列化的数据,没有接口成功标识再出参里
return Response({
'dode': framework_status.HTTP_200_OK, 'msg': 'SUCCESS', 'data': serializer.data},
status=framework_status.HTTP_200_OK)
这里代码上基本都有写注释,体会不明显就结合下面的各种访问路径体会,注释的return也可以打开试试效果。
三、效果
到这里,如果启动不报错,直接访问:http://127.0.0.1:8000/api/
你应该看到下面的界面:
注意:箭头所指是views里的路由视图,点击链接可以去做增删改查接口在线操作。
用postman访问效果:
这里我一个个截图给大家没有意义,我就直接分享这些接口的json,大家保存为文件,导入到postman自行体会吧。
{
"info": {
"_postman_id": "5d29815d-5be8-4d8e-8dcb-b4d1a4134aba",
"name": "python接口",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "django测试",
"item": [
{
"name": "用户登录",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"postman.setGlobalVariable(\"pythonApi\",\"http://127.0.0.1:8000\");"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \"mobile\": \"18607151930\",\r\n \"password\": \"123456\"\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{
{pythonApi}}/userLogin",
"host": [
"{
{pythonApi}}"
],
"path": [
"userLogin"
]
}
},
"response": []
},
{
"name": "用户列表",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"postman.setGlobalVariable(\"pythonApi\",\"http://127.0.0.1:8000\");"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \"page\": 1,\r\n \"size\": 10,\r\n \"name\": \"1\",\r\n \"mobile\": \"8\" \r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{
{pythonApi}}/userList",
"host": [
"{
{pythonApi}}"
],
"path": [
"userList"
]
}
},
"response": []
},
{
"name": "用户列表-restframework",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"postman.setGlobalVariable(\"pythonApi\",\"http://127.0.0.1:8000\");"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \"page\": 1,\r\n \"size\": 10,\r\n \"name\": \"1\",\r\n \"mobile\": \"8\" \r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{
{pythonApi}}/api/auth/userList",
"host": [
"{
{pythonApi}}"
],
"path": [
"api",
"auth",
"userList"
]
}
},
"response": []
},
{
"name": "车辆列表(走项目urls配置)",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"postman.setGlobalVariable(\"pythonApi\",\"http://127.0.0.1:8000\");"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{
{pythonApi}}/carList",
"host": [
"{
{pythonApi}}"
],
"path": [
"carList"
]
}
},
"response": []
},
{
"name": "车辆列表 (走子模块urls的配置)",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"postman.setGlobalVariable(\"pythonApi\",\"http://127.0.0.1:8000\");"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{
{pythonApi}}/car/carList",
"host": [
"{
{pythonApi}}"
],
"path": [
"car",
"carList"
]
}
},
"response": []
},
{
"name": "车辆列表(走路由)",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"postman.setGlobalVariable(\"pythonApi\",\"http://127.0.0.1:8000\");"
],
"type": "text/javascript"
}
}
],
"protocolProfileBehavior": {
"disableBodyPruning": true
},
"request": {
"method": "GET",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{
{pythonApi}}/api/carInfo/",
"host": [
"{
{pythonApi}}"
],
"path": [
"api",
"carInfo",
""
]
}
},
"response": []
},
{
"name": "车辆详情(走路由)",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"postman.setGlobalVariable(\"pythonApi\",\"http://127.0.0.1:8000\");"
],
"type": "text/javascript"
}
}
],
"protocolProfileBehavior": {
"disableBodyPruning": true
},
"request": {
"method": "GET",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{
{pythonApi}}/api/carInfo/6/",
"host": [
"{
{pythonApi}}"
],
"path": [
"api",
"carInfo",
"6",
""
]
}
},
"response": []
},
{
"name": "车辆新增(走路由)",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"postman.setGlobalVariable(\"pythonApi\",\"http://127.0.0.1:8000\");"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \"car_no\": \"鄂A1234\",\r\n \"car_color\": \"皓月灰\",\r\n \"car_type\": 1,\r\n \"memo\": \"梦中的\"\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{
{pythonApi}}/api/carInfo/",
"host": [
"{
{pythonApi}}"
],
"path": [
"api",
"carInfo",
""
]
}
},
"response": []
},
{
"name": "车辆修改(走路由)",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"postman.setGlobalVariable(\"pythonApi\",\"http://127.0.0.1:8000\");"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "PATCH",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \"car_color\": \"皓月灰\",\r\n \"car_type\": 2,\r\n \"memo\": \"梦中的a\"\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{
{pythonApi}}/api/carInfo/6/",
"host": [
"{
{pythonApi}}"
],
"path": [
"api",
"carInfo",
"6",
""
]
}
},
"response": []
},
{
"name": "车辆删除(走路由)",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
"postman.setGlobalVariable(\"pythonApi\",\"http://127.0.0.1:8000\");"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "DELETE",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{
{pythonApi}}/api/carInfo/7/",
"host": [
"{
{pythonApi}}"
],
"path": [
"api",
"carInfo",
"7",
""
]
}
},
"response": []
}
]
}
]
}
四、总结
- DRF路由方式真香,可惜所有的业务不可能都这么简单的单表操作
- 路由指定的序列器可重写,实际上可以部分解决上面的问题
- 最后讲句真话,这块我也还需要深入,所以这块的总结可能不准确
共同学习,今天比昨天优秀就行,加油。