环境搭建
新建项目
选择django框架+虚拟环境
image
数据库配置
修改settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1', # 数据库主机
'PORT': 3306, # 数据库端口
'USER': 'root', # 数据库用户名
'PASSWORD': 'admin1234', # 数据库用户密码
'NAME': 'api_test' # 数据库名字
}
}
安装相关库:
pip install mysqlclient==1.4.6
pip install wheel
中间件配置
前提:使用rest-framework框架
安装 :
pip install djangorestframework
修改settings.py :
在INSTALLED_APPS添加'rest_framework'
格式化响应输出
新建utils文件夹,新建custom_response_middleware.py
class CustomResponseMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# 配置和初始化
def __call__(self, request):
# 在这里编写视图和后面的中间件被调用之前需要执行的代码
# 这里其实就是旧的process_request()方法的代码
response = self.get_response(request)
# if "code" not in response.data:
#
# data = response.data
# response.data={
# "code":"0000",
# "message":"查询成功",
# "data":response.data
# }
# # 因返回时已经render过response,要想让这里的修改有效,需要手动在render一次
# response._is_rendered = False
# response.render()
# response["content-length"]=len(response.content)
# 在这里编写视图调用后需要执行的代码
# 这里其实就是旧的 process_response()方法的代码
return response
def process_template_response(self, request, response):# 推荐
if "code" not in response.data:
data = response.data
response.data={
"code":"0000",
"message":"操作成功",
"data":response.data
}
# 在这里编写视图调用后需要执行的代码
# 这里其实就是旧的 process_response()方法的代码
return response
修改settings.py :
在MIDDLEWARE中最前面增加'utils.custom_response_middleware.CustomResponseMiddleware'。(响应中间件放最前面,请求中间件放最后面)
重写异常类 utils/custom_exception.py
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.views import exception_handler as drf_exception_handler
from utils.custom_response import CustomResponse
def exception_handler(exc,context):
"""
自定义异常处理
:param exc: 别的地方抛的异常就会传给exc
:param context: 字典形式。抛出异常的上下文(即抛出异常的出处;即抛出异常的视图)
:return: Response响应对象
"""
response = drf_exception_handler(exc,context)
if response is None:
# drf 处理不了的异常
print('%s - %s - %s' % (context['view'], context['request'].method, exc))
return CustomResponse({'detail': '服务器错误'}, code=500,msg="服务器内部错误",status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
if isinstance(exc,ValidationError):
message = ""
data = response.data
for key in data:
message += ";".join(data[key])
return CustomResponse(None,code="9999",msg=message)
return response
修改settings.py
REST_FRAMEWORK = {
'EXCEPTION_HANDLER':'utils.custom_exception.exception_handler',
}
重写响应 utils/custom_response.py
from rest_framework.response import Response
# 重写响应
class CustomResponse(Response):
def __init__(self, *args, code='0000', msg="成功", **kwargs):
# 格式化data
data = {
"code": code,
"message": msg
}
if args is not None:
data["data"] = args[0]
kwargs["data"] = data
elif "data" in kwargs:
data["data"] = kwargs["data"]
kwargs["data"] = data
super().__init__(**kwargs)
新建应用
python manage.py startapp guoya_api
添加应用到settings.py的INSTALLED_APPS中
路由分发
主路由:
```
urlpatterns = [
path('admin/', admin.site.urls),
path('v01/', include('guoya_api.urls')),
]
```
子路由:
```
urlpatterns = [
]
```
models
文件位置:guoya_api>models
直接使用开源代码中的models:
数据迁移
生成迁移脚本:
python manage.py makemigrations
执行迁移标本:
python manage.py migrate
对模型创建序列化器
文件位置:guoya_api>serializers.py
直接使用开源代码中的serializers: