gpt4 book ai didi

python - 在 Flask 中有一种方法可以忽略对不存在的路由的请求

转载 作者:可可西里 更新时间:2023-11-01 16:30:05 24 4
gpt4 key购买 nike

我正在使用 Flask 编写应用程序。我有一组路线,它们有效。我想在客户端做的是忽略对无效 URL 的任何请求。也就是说,我不想在应用程序中呈现任何 404/错误页面。我想要一个警告,指出 URL 无效,并且浏览器只是停留在同一页面上。

我不想在客户端检查 JavaScript 中的 URL,因为这会暴露它们。

我有一个正确响应未知 URL 的路由:

@app.errorhandler(404) 
def non_existant_route(error):
return jsonify({"no":"such page"})

如果我删除 return 语句,我会收到 500 错误。我不能使用 abort()

这个想法是否违反了一些 HTTP 原则?

谢谢

最佳答案

听起来您需要一个“包罗万象”的端点。通常,一个包罗万象的端点似乎会返回一个通用的 404,但在您的情况下,您可能希望返回一个包含一些上下文信息的 200。基本上,您可以这样做(致谢 http://flask.pocoo.org/snippets/57/ ):

from flask import Flask
app = Flask(__name__)

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
# returns a 200 (not a 404) with the following contents:
return 'your custom error content\n'

# This is just one of your other valid routes:
@app.route('/stuff')
def stuff():
return 'stuff\n'


if __name__ == '__main__':
app.run()

如果您运行它并 curl 测试应用的各个端点,您将得到以下结果:

$ curl localhost:5000/stuff
stuff
$ curl localhost:5000/foo/bar
your custom error content
$ curl localhost:5000/otherstuff
your custom error content

如您所见,您的其他路由仍将按预期工作。

关于python - 在 Flask 中有一种方法可以忽略对不存在的路由的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35697367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com