30 lines
974 B
Python
30 lines
974 B
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
统一 API 响应格式:code、data、msg。
|
||
"""
|
||
from rest_framework.response import Response
|
||
from rest_framework import status
|
||
|
||
|
||
def api_response(code: int = 0, data=None, msg: str = "success", http_status: int = None):
|
||
"""
|
||
统一接口响应格式。
|
||
- code: 0 表示成功,非 0 表示错误(通常与 HTTP 状态码对应)
|
||
- data: 业务数据
|
||
- msg: 提示信息
|
||
"""
|
||
resp = {"code": code, "data": data, "msg": msg}
|
||
if http_status is None:
|
||
http_status = status.HTTP_200_OK if code == 0 else min(code, 599)
|
||
return Response(resp, status=http_status)
|
||
|
||
|
||
def api_success(data=None, msg: str = "success", http_status: int = status.HTTP_200_OK):
|
||
"""成功响应。"""
|
||
return api_response(code=0, data=data, msg=msg, http_status=http_status)
|
||
|
||
|
||
def api_error(code: int, msg: str, data=None):
|
||
"""错误响应。"""
|
||
return api_response(code=code, data=data, msg=msg, http_status=code)
|