越用越熟,以此为典型实现,复杂的视图,可以基于此之上进行实现。
一,安装配置基础
1,安装django-filters
pip install django-filter
2,实现PageNumber分页
from rest_framework.pagination import PageNumberPagination
class PNPagination(PageNumberPagination):
page_size = 10
max_page_size = 100
page_size_query_param = 'pageSize'
page_query_param = 'currentPage'
'''
age_query_param:表示url中的页码参数
page_size_query_param:表示url中每页数量参数
page_size:表示每页的默认显示数量
max_page_size:表示每页最大显示数量,做限制使用,避免突然大量的查询数据,数据库崩溃
'''
3,配置settings
INSTALLED_APPS = [
'account.apps.AccountConfig',
'app.apps.AppConfig',
'cmdb.apps.CmdbConfig',
'deploy.apps.DeployConfig',
'env.apps.EnvConfig',
'log.apps.LogConfig',
'release.apps.ReleaseConfig',
'server.apps.ServerConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'django_filters',
'corsheaders',
'drf_yasg',
'simple_history',
]
...
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'utils.pagination.PNPagination',
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
4,定义统一返回
import json
from django.http import HttpResponse
OP_SUCCESS = 0
THROW_EXP = 1000
OP_DB_FAILED = 1001
CHECK_PARAM_FAILED = 1002
FILE_FORMAT_ERR = 1003
NOT_POST = 1004
NOT_GET = 1005
ERR_CODE = {
0: '操作成功',
1000: "抛出异常",
1001: "数据库操作失败",
1002: "参数检查失败",
1003: "文件格式有误",
1004: "非post请求",
1005: "非get请求",
}
def build_ret_data(ret_code, data=''):
return {'code': ret_code, 'message': ERR_CODE[ret_code], 'data': data}
def render_json(dictionary={}):
response = HttpResponse(json.dumps(dictionary), content_type="application/json")
response['Access-Control-Allow-Origin'] = '*'
response["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type"
response["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS"
return response
二,视图实现
1,定义url
from django.urls import path
from . import views
urlpatterns = [
path('list/', views.ReleaseListView.as_view(), name='list'),
]
`
2,定义序列化serializer
from rest_framework import serializers
from cmdb.models import Release
class ReleaseSerializer(serializers.ModelSerializer):
class Meta:
model = Release
fields = '__all__'
3,定义filters
from django_filters import OrderingFilter
from django_filters.rest_framework import FilterSet
from django_filters import filters
from cmdb.models import Release
class ReleaseFilter(FilterSet):
name = filters.CharFilter(field_name='name', lookup_expr='icontains',)
begin_time = filters.DateTimeFilter(field_name='create_date', lookup_expr='gte',)
end_time = filters.DateTimeFilter(field_name='create_date', lookup_expr='lte',)
sort = OrderingFilter(fields=('create_date',))
class Meta:
model = Release
fields = ['name', 'begin_time', 'end_time']
4,合成views
from cmdb.models import Release
from .serializers import ReleaseSerializer
from rest_framework.generics import ListAPIView
from utils.ret_code import *
from .filters import ReleaseFilter
class ReleaseListView(ListAPIView):
queryset = Release.objects.all()
serializer_class = ReleaseSerializer
filter_class = ReleaseFilter
def get(self, request, *args, **kwargs):
res = super().get(self, request, *args, **kwargs)
return_dict = build_ret_data(OP_SUCCESS, res.data)
return render_json(return_dict)
四,先认证,取个token
http://localhost:8000/jwt_auth/
post发送个请求头
{
"username": "admin",
"password": "password"
}
返回值
{
"code": 0,
"message": "欢迎回来",
"data": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjQxMjAyMDk4LCJlbWFpbCI6IiIsIm9yaWdfaWF0IjoxNjA5NjY2MDk4fQ.H5sXlTZvHHUXxE2TSgJPKpl8MOxrYV1PVCL543BDwtM",
"expireAt": "2022-01-03T09:28:18.553004",
"user_id": 1,
"user": {
"id": 1,
"name": "admin",
"email": "",
"avatar": ""
},
"is_superuser": true,
"permissions": [
{
"id": "queryForm",
"operation": [
"add",
"edit"
]
}
],
"roles": [
{
"id": "admin",
"operation": [
"add",
"edit",
"delete"
]
}
]
}
}
五,测试
1,无搜索过滤的分页
访问http://localhost:8000/release/list/
,要带上authorization bear token。
返回分页数据
{
"code": 0,
"message": "操作成功",
"data": {
"count": 100,
"next": "http://localhost:8000/release/list/?currentPage=2",
"previous": null,
"results": [
{
"id": 1,
"name": "20210103162030443444OI",
"description": "20210103162030443444OI",
"update_date": "2021-01-03T16:20:30.444438+08:00",
"create_date": "2021-01-03T16:20:30.444438+08:00",
"base_status": true,
"deploy_no": 0,
"git_branch": "master",
"git_commit": "449df93bb",
"salt_path": "salt://a/b/c",
"nginx_url": "http://192.168.1.213:8080/a/b/c",
"create_user": 1,
"app": 2,
"env": 1,
"deploy_status": 3
},
{
"id": 2,
"name": "20210103162030458234RQ",
"description": "20210103162030458234RQ",
"update_date": "2021-01-03T16:20:30.458234+08:00",
"create_date": "2021-01-03T16:20:30.458234+08:00",
"base_status": true,
"deploy_no": 0,
"git_branch": "master",
"git_commit": "449df93bb",
"salt_path": "salt://a/b/c",
"nginx_url": "http://192.168.1.213:8080/a/b/c",
"create_user": 1,
"app": 1,
"env": 1,
"deploy_status": 2
},
{
"id": 3,
"name": "20210103162030459322HB",
"description": "20210103162030459322HB",
"update_date": "2021-01-03T16:20:30.459322+08:00",
"create_date": "2021-01-03T16:20:30.459322+08:00",
"base_status": true,
"deploy_no": 0,
"git_branch": "master",
"git_commit": "449df93bb",
"salt_path": "salt://a/b/c",
"nginx_url": "http://192.168.1.213:8080/a/b/c",
"create_user": 1,
"app": 2,
"env": 2,
"deploy_status": 5
},
{
"id": 4,
"name": "20210103162030474970WQ",
"description": "20210103162030474970WQ",
"update_date": "2021-01-03T16:20:30.474970+08:00",
"create_date": "2021-01-03T16:20:30.474970+08:00",
"base_status": true,
"deploy_no": 0,
"git_branch": "master",
"git_commit": "449df93bb",
"salt_path": "salt://a/b/c",
"nginx_url": "http://192.168.1.213:8080/a/b/c",
"create_user": 1,
"app": 3,
"env": 1,
"deploy_status": 6
},
{
"id": 5,
"name": "20210103162030490588MC",
"description": "20210103162030490588MC",
"update_date": "2021-01-03T16:20:30.490588+08:00",
"create_date": "2021-01-03T16:20:30.490588+08:00",
"base_status": true,
"deploy_no": 0,
"git_branch": "master",
"git_commit": "449df93bb",
"salt_path": "salt://a/b/c",
"nginx_url": "http://192.168.1.213:8080/a/b/c",
"create_user": 1,
"app": 2,
"env": 2,
"deploy_status": 3
},
{
"id": 6,
"name": "20210103162030506198RT",
"description": "20210103162030506198RT",
"update_date": "2021-01-03T16:20:30.506198+08:00",
"create_date": "2021-01-03T16:20:30.506198+08:00",
"base_status": true,
"deploy_no": 0,
"git_branch": "master",
"git_commit": "449df93bb",
"salt_path": "salt://a/b/c",
"nginx_url": "http://192.168.1.213:8080/a/b/c",
"create_user": 1,
"app": 2,
"env": 2,
"deploy_status": 3
},
{
"id": 7,
"name": "20210103162030521837MI",
"description": "20210103162030521837MI",
"update_date": "2021-01-03T16:20:30.521837+08:00",
"create_date": "2021-01-03T16:20:30.521837+08:00",
"base_status": true,
"deploy_no": 0,
"git_branch": "master",
"git_commit": "449df93bb",
"salt_path": "salt://a/b/c",
"nginx_url": "http://192.168.1.213:8080/a/b/c",
"create_user": 1,
"app": 5,
"env": 2,
"deploy_status": 3
},
{
"id": 8,
"name": "20210103162030537465LQ",
"description": "20210103162030537465LQ",
"update_date": "2021-01-03T16:20:30.537465+08:00",
"create_date": "2021-01-03T16:20:30.537465+08:00",
"base_status": true,
"deploy_no": 0,
"git_branch": "master",
"git_commit": "449df93bb",
"salt_path": "salt://a/b/c",
"nginx_url": "http://192.168.1.213:8080/a/b/c",
"create_user": 1,
"app": 1,
"env": 1,
"deploy_status": 4
},
{
"id": 9,
"name": "20210103162030553101UQ",
"description": "20210103162030553101UQ",
"update_date": "2021-01-03T16:20:30.553101+08:00",
"create_date": "2021-01-03T16:20:30.553101+08:00",
"base_status": true,
"deploy_no": 0,
"git_branch": "master",
"git_commit": "449df93bb",
"salt_path": "salt://a/b/c",
"nginx_url": "http://192.168.1.213:8080/a/b/c",
"create_user": 1,
"app": 1,
"env": 2,
"deploy_status": 5
},
{
"id": 10,
"name": "20210103162030553101UP",
"description": "20210103162030553101UP",
"update_date": "2021-01-03T16:20:30.553101+08:00",
"create_date": "2021-01-03T16:20:30.553101+08:00",
"base_status": true,
"deploy_no": 0,
"git_branch": "master",
"git_commit": "449df93bb",
"salt_path": "salt://a/b/c",
"nginx_url": "http://192.168.1.213:8080/a/b/c",
"create_user": 1,
"app": 2,
"env": 1,
"deploy_status": 2
}
]
}
}
2,有搜索过滤的分页
访问http://localhost:8000/release/list/?name=R&sort=-create_date
,其中sort用于定义排序。返回同样分页OK。
3,swagger显示
2021-01-03 17_34_42-悬浮球.png2021-01-03 17_36_13-悬浮球.png
网友评论