如何返回带有错误 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 文件的情况下完成此操作?
答案 0 :(得分:0)
您从 Flask 视图返回的值应始终为 Response
:
from flask import Response
def logs():
...
return Response("WAF: Access Denied for this Host.", status=403)