感谢下面的答案,我有一个 before_request
函数,如果用户还没有登录,它会将用户重定向到 /login
:
flask before request - add exception for specific route
这是我的 before_request 的副本:
@app.before_request
def before_request():
if 'logged_in' not in session and request.endpoint != 'login':
return redirect(url_for('login'))
除非用户登录,否则我的静态目录中的文件不会被提供。
在我的 /login
页面上,我正在从 /static
目录中获取一个 css 文件,但是由于这个 before_request
而无法加载它.
我已经使用 apache mod_wsgi 部署了这个应用程序,并且在我的 apache 配置文件中我什至包含了 /static
目录作为站点的 DocumentRoot。
如何在用户未登录的情况下为我的应用程序的 /static
文件添加异常,但仍将此 before_request
用于我的 flask 应用程序定义的路由?
最佳答案
您需要添加 Alias
或 AliasMatch
指令到您的 Apache 配置文件(或 .htaccess 文件,如果您无权访问 .conf
文件)以确保 Apache 服务于您的静态文件,而不是 Flask。确保您提供了 Directory
至 allow the Apache web server to access your static path . (此外,如果您正在编辑 .conf
文件,请不要忘记重新启动 Apache,这样您的更改就会生效)。
作为临时的权宜之计(或者为了便于在开发中使用),您还可以检查以确保字符串 /static/
不在 request.path
中。 :
if 'logged_in' not in session \
and request.endpoint != 'login' \
and '/static/' not in request.path:
关于python flask before_request 排除/静态目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14759186/