【问题标题】:python flask before_request exclude /static directorypython flask before_request 排除/静态目录
【发布时间】:2013-01-23 10:17:36
【问题描述】:

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

【问题讨论】:

  • 您现在如何尝试获取 css 文件?你能分享一些代码吗?

标签: python flask mod-wsgi


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我同意 Apache 的方法,但为了快速修复,我在 before_request() 函数的开头使用了以下逻辑:

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

    【讨论】:

    • flask.request.script_rootbefore_request 中给了我一个空字符串,而path 有一些价值。这对我不起作用。
    【解决方案3】:

    您需要将AliasAliasMatch 指令添加到您的Apache 配置文件(或.htaccess 文件,如果您无权访问.conf 文件)以确保Apache em> 为您的静态文件提供服务,而不是 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:
    

    【讨论】:

    • 你对 apache 配置和 request.path 的东西都是正确的。感谢您的帮助!
    • and not request.path.startswith('/static/') 可能会更好一些,因为这样可以避免与/something-else/static/ 之类的任何路线混淆
    • @Milimetric - 除了蓝图静态路径以/blueprintname/ 开头,然后包含/static ;-) 但你是对的,这取决于你在做什么:-)
    猜你喜欢
    • 2019-05-26
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    相关资源
    最近更新 更多