python - Flask-RESTplus 中的响应类
问题描述
在 Flask-RESTplus 中处理响应类的正确方法是什么?我正在尝试一个简单的 GET 请求,如下所示:
i_throughput = api.model('Throughput', {
'date': fields.String,
'value': fields.String
})
i_server = api.model('Server', {
'sessionId': fields.String,
'throughput': fields.Nested(i_throughput)
})
@api.route('/servers')
class Server(Resource):
@api.marshal_with(i_server)
def get(self):
servers = mongo.db.servers.find()
data = []
for x in servers:
data.append(x)
return data
我想将我的数据作为响应对象的一部分返回,如下所示:
{
status: // some boolean value
message: // some custom response message
error: // if there is an error store it here
trace: // if there is some stack trace dump throw it in here
data: // what was retrieved from DB
}
我是 Python 的新手,也是 Flask/Flask-RESTplus 的新手。那里有很多教程和信息。我最大的问题之一是我不确定要准确搜索什么来获取我需要的信息。另外,这如何与编组一起工作?如果有人可以发布好的文档或优秀 API 的示例,将不胜感激。
解决方案
https://blog.miguelgrinberg.com/post/customizing-the-flask-response-class
from flask import Flask, Response, jsonify
app = Flask(__name__)
class CustomResponse(Response):
@classmethod
def force_type(cls, rv, environ=None):
if isinstance(rv, dict):
rv = jsonify(rv)
return super(MyResponse, cls).force_type(rv, environ)
app.response_class = CustomResponse
@app.route('/hello', methods=['GET', 'POST'])
def hello():
return {'status': 200, 'message': 'custom_message',
'error': 'error_message', 'trace': 'trace_message',
'data': 'input_data'}
结果
import requests
response = requests.get('http://localhost:5000/hello')
print(response.text)
{
"data": "input_data",
"error": "error_message",
"message": "custom_message",
"status": 200,
"trace": "trace_message"
}
推荐阅读
- druid - 如何在使用 imply 时限制 druid 生成的日志文件的大小?
- python - Python:列表理解以访问多个列表
- html - 让 div 的背景延伸到页面的两侧
- emacs - authinfo.gpg 中的 Emacs “Tramp” sudo 设置:特定于机器的 sudo 认证
- javascript - Javascript 工作,但不在 Vue 组件中
- facebook-graph-api - Facebook 支付 API 仅在 created_time 不返回支付信息
- python - Python:在同一个包中的两个不同文件中导入标准模块?
- python - 如何在cmd中将python添加为命令?
- ocaml - 关键字 in 在 OCaml 中的工作原理
- notepad++ - 如何在 1 行中合并 2 行单独的行?