多亏了下面的答案,我有了一个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应用程序定义的路由?
发布于 2013-02-08 01:40:29
您需要将Alias
或AliasMatch
指令添加到Apache配置文件(或.htaccess文件,如果您没有访问.conf
文件的权限),以确保Apache服务于您的静态文件,而不是Flask。确保您提供了allow the Apache web server to access your static path的Directory
。(另外,如果您正在编辑.conf
文件,请不要忘记重新启动Apache,这样您的更改就会生效)。
作为临时权宜之计(或者为了便于在开发中使用),您还可以检查以确保字符串/static/
不在request.path
中
if 'logged_in' not in session \
and request.endpoint != 'login' \
and '/static/' not in request.path:
发布于 2015-02-10 09:33:18
我认为有一个比检查request.path
更干净的解决方案。
if 'logged_in' not in session and request.endpoint not in ('login', 'static'):
return redirect(url_for('login'))
发布于 2014-07-25 16:39:04
我确实同意Apache方法,但为了快速修复,我在before_request()函数的开头使用了以下逻辑:
if flask.request.script_root == "/static":
return
https://stackoverflow.com/questions/14759186
复制相似问题