簡體   English   中英

Flask-RESTplus 中的響應類

[英]Response class in 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"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM