感谢下面的回答,我有一个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应用程序定义的路由?
答案 0 :(得分:9)
您需要向Apache配置文件(或.htaccess文件,如果您无权访问.conf
文件)添加Alias
或AliasMatch
指令确保 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:
答案 1 :(得分:3)
我认为有一种解决方案比检查request.path
更清晰。
if 'logged_in' not in session and request.endpoint not in ('login', 'static'):
return redirect(url_for('login'))
答案 2 :(得分:0)
我同意Apache方法,但为了快速修复,我在before_request()函数的开头有以下逻辑:
if flask.request.script_root == "/static":
return