Flask-RESTful - 返回自定义响应格式 [英] Flask-RESTful - Return custom Response format
问题描述
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或{})
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
。
我该怎么做呢?这个文件不是很清楚。
使用什么表示形式由请求,接受 header mime type。
application / octet-stream
通过使用你的二进制
函数。如果你需要API方法的特定响应类型,必须使用 flask.make_response()
来返回一个预先烘焙的响应对象:
def get(self):
response = flask.make_response(something)
response.headers ['content-type'] ='application / octet-stream'
返回回应
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.
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
这篇关于Flask-RESTful - 返回自定义响应格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!