Flask-RESTful - Return custom Response format

爷,独闯天下 提交于 2019-12-20 09:37:20

问题


I have defined a custom Response format as per the Flask-RESTful documentation as follow.

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

I have the following Resource class.

class Foo(restful.Resource):

    def get(self):
        return something

    def put(self, fname):
        return something

I want the get() function to return the application/octet-stream type and the put() function to return the default application/json.

How do I go about doing this? The documentation isn't very clear on this point.


回答1:


What representation is used is determined by the request, the Accept header mime type.

A request of application/octet-stream will be responded to by using your binary function.

If you need a specific response type from an API method, then you'll have to use flask.make_response() to return a 'pre-baked' response object:

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



回答2:


Just return Flask response objects in your methods.

A response class allows you to provide custom headers (including the content-type): http://flask.pocoo.org/docs/api/#response-objects



来源:https://stackoverflow.com/questions/20243850/flask-restful-return-custom-response-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!