python flask before_request排除/ static目录

python flask before_request exclude /static directory

感谢下面的回答,我有一个before_request函数,如果用户尚未登录,该函数会将用户重定向到/login

请求前先进行烧瓶-为特定路线添加例外

这是我的before_request的副本:

1
2
3
4
@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应用程序定义的路由?


您需要向Apache配置文件(或.htaccess文件,如果您无权访问.conf文件)中添加AliasAliasMatch指令,以确保Apache服务于您的静态文件,而不是Flask 。 确保提供了Directory以允许Apache Web服务器访问您的静态路径。 (此外,如果您正在编辑.conf文件,请不要忘记重新启动Apache,这样您的更改就会被接受)。

作为临时的权宜之计(或使其易于在开发中使用),您还可以检查以确保字符串/static/不在request.path中:

1
2
3
if 'logged_in' not in session \\
    and request.endpoint != 'login' \\
    and '/static/' not in request.path:


我认为有一个比检查request.path更清洁的解决方案。

1
2
if 'logged_in' not in session and request.endpoint not in ('login', 'static'):
    return redirect(url_for('login'))

我确实同意Apache的方法,但是为了快速解决,我在before_request()函数开始时使用了以下逻辑:

1
2
if flask.request.script_root =="/static":
  return