我根据以下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
。
我该如何去做?关于这一点,文档不是很清楚。
使用什么表示形式取决于[[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
响应类允许您提供自定义标头(包括内容类型):http://flask.pocoo.org/docs/api/#response-objects
因此,在您的情况下,这也应该有效
class Foo(restful.Resource):
def get(self):
return something, 201, {'content-type': 'application/octet-stream'}
Flask-REstful的默认媒体类型为'application / json',因此put应该照常工作。