Flask-RESTful-返回自定义响应格式

问题描述 投票:17回答:3

我根据以下Flask-RESTful文档定义了自定义响应格式。

app = Flask(__name__)
api = restful.Api(app)

@api.representation('application/octet-stream')
def binary(data, code, headers=None):
    resp = api.make_response(data, code)
    resp.headers.extend(headers or {})
    return resp

api.add_resource(Foo, '/foo')

我有以下资源类。

class Foo(restful.Resource):

    def get(self):
        return something

    def put(self, fname):
        return something

我希望get()函数返回application/octet-stream类型,并且put()函数返回默认的application/json

我该如何去做?关于这一点,文档不是很清楚。

python python-2.7 flask flask-restful
3个回答
18
投票

使用什么表示形式取决于[[request,Accept标头mime类型。

将使用您的application/octet-stream功能来回复binary的请求。

如果您需要API方法中的特定响应类型,则必须使用flask.make_response()返回“预烘焙”响应对象:

def get(self): response = flask.make_response(something) response.headers['content-type'] = 'application/octet-stream' return response


3
投票
只需在您的方法中返回Flask响应对象。

响应类允许您提供自定义标头(包括内容类型):http://flask.pocoo.org/docs/api/#response-objects


0
投票
除了@Martijin Pieters在这里的答案-https://stackoverflow.com/a/20246014/1869562。在返回原始响应对象的地方,Flask-Restful还允许您直接在返回值中设置状态代码和标头。

因此,在您的情况下,这也应该有效

class Foo(restful.Resource): def get(self): return something, 201, {'content-type': 'application/octet-stream'}

Flask-REstful的默认媒体类型为'application / json',因此put应该照常工作。
© www.soinside.com 2019 - 2024. All rights reserved.