python flask before_request exclude / static目录

时间:2013-02-07 19:18:12

标签: python flask mod-wsgi

感谢下面的回答,我有一个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应用程序定义的路由?

3 个答案:

答案 0 :(得分:9)

您需要向Apache配置文件(或.htaccess文件,如果您无权访问.conf文件)添加AliasAliasMatch指令确保 Apache 提供静态文件,而不是Flask。确保您提供了Directoryallow 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