Files
boss_dp/server/core/response.py
2026-02-26 01:27:35 +08:00

30 lines
974 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- 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)