26 lines
1.3 KiB
Python
26 lines
1.3 KiB
Python
|
|
from rest_framework.response import Response
|
||
|
|
|
||
|
|
|
||
|
|
def ok(data, message="ok"):
|
||
|
|
return Response({"code": 200, "data": data, "message": message})
|
||
|
|
|
||
|
|
|
||
|
|
class EnvelopeMixin:
|
||
|
|
"""错误信封统一收口(Task7 同款裁剪,无 ACAO——管理台与 API 同源,跨域由 nginx 层面不存在)。
|
||
|
|
|
||
|
|
simplejwt 认证失败 401 / 权限 403 / 限流 429 等由 DRF 异常处理器产出的响应
|
||
|
|
body 是 {detail},管理台前端(Task17)按 {code,data,message} 信封对接——
|
||
|
|
在此统一转换,视图自身的 ok/4xx 响应不受影响(只动含 detail 的 dict)。
|
||
|
|
"""
|
||
|
|
|
||
|
|
def finalize_response(self, request, response, *args, **kwargs):
|
||
|
|
response = super().finalize_response(request, response, *args, **kwargs)
|
||
|
|
if response.status_code >= 400 and isinstance(response.data, dict):
|
||
|
|
if "detail" in response.data:
|
||
|
|
response.data = {"code": response.status_code, "data": None,
|
||
|
|
"message": response.data["detail"]}
|
||
|
|
elif "code" not in response.data: # simplejwt 序列化器字段错误 {"password": [...]} 等
|
||
|
|
response.data = {"code": response.status_code, "data": response.data,
|
||
|
|
"message": "invalid_input"}
|
||
|
|
return response
|