Python 服务统一响应格式工具类
·
一、基本介绍
在开发 RESTful API 服务时,保持一致的响应格式是非常重要的。统一的响应格式不仅能让前端开发者更容易处理返回数据,还能提高 API 的可维护性和可读性。本文将介绍一个简单的 Python 工具类,帮助你在 Flask 应用中实现统一的响应格式。
二、为什么需要统一响应格式?
- 前端处理更简单:前端可以按照固定的格式解析响应。
- 调试更方便:统一的错误格式有助于快速定位问题。
- API 文档更清晰:一致的格式让 API 文档更易于编写和理解。
- 更好的用户体验:客户端可以统一处理错误和成功情况。
三、实现代码
from flask import jsonify
from typing import Any, Optional
class ResponseUtil:
"""
统一响应格式工具类
参数:
data (any): 响应的数据对象,默认为 None
message (str): 响应的消息描述,默认为 "Success"
status (int): 响应的状态码,默认为 200
"""
@staticmethod
def success(data: Any = None, message: str = "Success", status: int = 200):
"""
成功响应
参数:
data: 返回的数据
message: 成功消息
status: HTTP状态码
"""
return jsonify({
'data': data,
'message': message,
'status': status
}), status
@staticmethod
def error(message: str = "Error", status: int = 400, data: Optional[Any] = None):
"""
错误响应
参数:
message: 错误消息
status: HTTP状态码
data: 可选的错误数据
"""
return jsonify({
'data': data,
'message': message,
'status': status
}), status
@staticmethod
def not_found(message: str = "Resource not found"):
"""
资源未找到响应
"""
return ResponseUtil.error(message=message, status=404)
@staticmethod
def server_error(message: str = "Internal server error"):
"""
服务器错误响应
"""
return ResponseUtil.error(message=message, status=500)
4、使用示例
成功响应
# 如果处理成功,添加结果图片路径到返回数据
if result.get("success", False):
result["result_image"] = result_image_path
return ResponseUtil.success(
data=result,
message="交叉点识别成功"
)
失败响应
if not data or 'image_path' not in data:
return ResponseUtil.error(
message="缺少 image_path 参数",
status=400
)
5、格式说明
所有响应都遵循以下格式:
成功响应
{
"data": {...}, // 实际返回的数据
"message": "Success",
"status": 200
}
失败响应
{
"data": null, // 或包含错误详情
"message": "Resource not found",
"status": 404
}
更多推荐


所有评论(0)