Flask-RESTplus中的响应类

时间:2019-12-12 00:43:07

标签: python mongodb flask flask-restful 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的示例,将不胜感激。

1 个答案:

答案 0 :(得分:0)

https://blog.miguelgrinberg.com/post/customizing-the-flask-response-class

entrySet()

结果

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'}