【问题标题】:Make flask return NON-json response custom message with error code使烧瓶返回带有错误代码的 NON-json 响应自定义消息
【发布时间】:2021-06-03 00:43:51
【问题描述】:

如何返回自定义响应消息,错误 403 不是 json。 我试过用这个:

    def bad_request(message):
        response = jsonify({'message': message})
        response.status_code = 403
        return response

   @app.route("/logs")
    def logs():
        if request.remote_addr == "127.0.0.1":
            return f"Heres your logs!"
        else:
            return bad_request('WAF: Access Denied for this Host.')

这会返回我不想要的 json。另外,我不喜欢使用 abort,因为它包含 HTML。我只希望响应为 403,并且只打印纯文本。

我尝试将response = jsonify({'message': message}) 更改为response = message,但出现“AttributeError: 'str' object has no attribute 'status_code'”的内部服务器错误

我怎样才能做到这一点?

编辑: 终于可以让它工作了

 return render_template('error.html'), 403

只需将平面文本放入error.html。 是否有任何其他方法可以在无需创建模板 html 文件的情况下完成此操作?

【问题讨论】:

    标签: json flask request response http-status-code-403


    【解决方案1】:

    从 Flask 视图返回的值应该始终是 Response:

    from flask import Response
    
    def logs():
       ...
       return Response("WAF: Access Denied for this Host.", status=403)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-30
      • 2011-08-28
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      相关资源
      最近更新 更多