我注意到@use_kwargs在flask-apispec中更改了响应内容类型。在下面的"hello“示例中,@use_kwargs的使用将响应内容类型从text/html更改为application/json。我觉得这有点令人惊讶,因为烧瓶-尖部没有提到它,我也不认为注入args也会改变响应类型:
from flask import Flask
from flask_apispec import use_kwargs
from marshmallow import fields
app = Flask(__name__)
@app.route('/')
@use_kwargs({'email': fields.Str()}, location="query")
def hello_world(**kwargs):
return 'Hello, World!curl -v http://127.0.0.1:5000/\?email\=abc显示响应
> GET /?email=abc HTTP/1.1
> Host: 127.0.0.1:5000
> User-Agent: curl/7.64.1
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 16
< Server: Werkzeug/1.0.1 Python/3.8.2
< Date: Tue, 12 Jan 2021 06:09:25 GMT
<
"Hello, World!"请注意,Content-Type: application/json和value是引用的。但是,如果没有@use_kwargs行,则响应为Content-Type: text/html,并且没有引用hello的内容:
~ curl -v http://127.0.0.1:5000/\?email\=abc
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
> GET /?email=abc HTTP/1.1
> Host: 127.0.0.1:5000
> User-Agent: curl/7.64.1
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: text/html; charset=utf-8
< Content-Length: 13
< Server: Werkzeug/1.0.1 Python/3.8.2
< Date: Tue, 12 Jan 2021 06:09:42 GMT
<
* Closing connection 0
Hello, World!%改变反应的理由是什么?即使使用@use_kwargs,如何设置响应内容类型"text/html“?谢谢!
更新:
只需添加一些关于@Diego Miguel给出的答案的更多细节:更改内容的效果是由打电话中的逻辑引起的。
def __call__(self, *args, **kwargs):
response = self.call_view(*args, **kwargs)
if isinstance(response, werkzeug.Response):
return response
rv, status_code, headers = unpack(response)
mv = self.marshal_result(rv, status_code)
response = packed(mv, status_code, headers)
return flask.current_app.make_response(response)marshal_result调用flask.jsonify,它生成一个带有"application/json“mimetype的响应对象,并引入上面的"hello”示例的额外引号。
发布于 2021-01-12 19:18:29
我不太清楚为什么使用@use_kwargs会改变内容类型。通过查看源代码,它似乎返回了一个dict,从这个函数 (由activate调用)判断。因此,我最好的猜测是,在执行app.route时,使用的是dict,即默认行为。此时,content-type被更改为application/json。但是,hello_world在use_kwargs之后执行,最后返回一个字符串,即"Hello!“。
无论如何,我不认为这种行为实际上是flask-apispec的意图。
您可以更改响应的content-type (和任何其他字段),用make_reponse创建一个Flask.Response对象,然后将其content-type设置为"text/html" (但是,在将字符串传递给make_response时,这是默认设置的,因此没有必要):
from flask import Flask, make_response
from flask_apispec import use_kwargs
from marshmallow import fields
app = Flask(__name__)
@app.route('/')
@use_kwargs({'email': fields.Str()}, location="query")
def hello_world(**kwargs):
response = make_response("Hello World!")
response.content_type = 'text/html' # can be omitted
return responsecurl -v http://127.0.0.1:5000/\?email\=abc输出
> GET /?email=abc HTTP/1.1
> Host: 127.0.0.1:5000
> User-Agent: curl/7.74.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: text/html
< Content-Length: 13
< Server: Werkzeug/1.0.1 Python/3.9.1
< Date: Tue, 12 Jan 2021 19:08:05 GMT
<
Hello World!https://stackoverflow.com/questions/65679086
复制相似问题