使用flask-restful返回text/html内容类型

5 投票
1 回答
5113 浏览
提问于 2025-04-28 14:59

在一个特定的情况下,我想要对一个错误的响应使用 text/html 的内容类型,具体如下:

class MyResource(Resource):
    def get(self):
        if some_condition:
            return 'bad argument', 400

上面的代码返回的是 application/json 的内容类型:'"bad argument"'
而不是 text/html 的内容类型:'bad argument'

我该如何强制 flask-restful 返回 text/html 的内容类型呢?

暂无标签

1 个回答

4

你需要使用 flask.make_response() 来返回一个“预先准备好的”响应对象:

return flask.make_response('bad argument', 400)

Flask-Restful 会直接传递完整的 Response 对象,而不是尝试把它们转换成特定请求的 MIME 类型。

撰写回答