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

Jon*_*han 5 python content-type httpresponse flask-restful

在特定情况下,我想以text/html内容类型响应错误,如下所示:

class MyResource(Resource):
    def get(self):
        if some_condition:
            return 'bad argument', 400
Run Code Online (Sandbox Code Playgroud)

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

如何强制flask-restful 响应text/html内容类型?

Mar*_*ers 4

您必须使用flask.make_response()返回“预烘焙”响应对象:

return flask.make_response('bad argument', 400)
Run Code Online (Sandbox Code Playgroud)

Flask-Restful 将传递未更改的完整Response对象,而不是尝试将它们转换为特定请求的 mime 类型。