是否可以检查发送到Flask的网址是否为404? [英] Is it possible to check if a url sent to Flask will 404?
问题描述
我有一个URL列表,需要找到所有不会转到Flask的404 not found页面的URL.有办法检查吗?
I have a list of urls and need to find all the ones that will not go to Flask's 404 not found page. Is there a way to check this?
推荐答案
使用底层URL映射来模拟如果Flask尝试将每个URL作为请求进行分派,将会发生什么情况.这就要求路径,HTTP方法(例如GET)和任何查询参数是已知的且独立的.
Use the underlying url map to simulate what would happen if Flask tried to dispatch each url as a request. This requires that the path, HTTP method (such as GET) and any query args are known and separate.
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
这不会给出完整的图片,因为在处理过程中实际视图可能会引发404(或其他错误).最终,除非您真正向路径提出请求,否则您将无法真正知道路径是否正确.
This won't give the whole picture though, as the actual view could raise a 404 (or other error) during processing. Ultimately, you can't really know if a path is good unless you actually make a request to it.
这篇关于是否可以检查发送到Flask的网址是否为404?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!