我有一个网址列表,需要找到所有不会进入 Flask 的 404 未找到页面的网址。有办法检查吗?
最佳答案
使用底层 url 映射来模拟 Flask 尝试将每个 url 作为请求分派(dispatch)时会发生的情况。这要求路径、HTTP 方法(例如 GET)和任何查询参数都是已知且独立的。
from werkzeug.routing import RequestRedirect, MethodNotAllowed, NotFound
to_test = (
('/user/1', 'GET', {}),
('/post/my-title/edit', 'POST', {}),
('/comments', 'GET', {'spam': 1}),
)
good = []
adapter = app.create_url_adapter(None)
if adapter is None:
raise Exception('configure a SERVER_NAME for the app')
for path, method, args in to_test:
try:
adapter.match(path, method, query_args=args)
except RequestRedirect:
pass
except (MethodNotAllowed, NotFound):
continue
good.append((path, method, args))
# good list now contains all tuples that didn't 404 or 405
但这并不能提供完整的图片,因为实际 View 在处理过程中可能会引发 404(或其他错误)。最终,除非您实际向某个路径发出请求,否则您无法真正知道该路径是否良好。
关于python - 是否可以检查发送到 Flask 的 url 是否会出现 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28861440/