简体   繁体   English

python flask before_request exclude / static目录

[英]python flask before_request exclude /static directory

Thanks to the answer below, I have a before_request function which redirects a user to /login if they have not yet logged in: 感谢下面的答案,我有一个before_request函数,如果用户还没有登录,它会将用户重定向到/login

flask before request - add exception for specific route 请求前烧瓶 - 为特定路线添加例外

Here is a copy of my before_request: 这是我的before_request的副本:

@app.before_request
def before_request():
    if 'logged_in' not in session and request.endpoint != 'login':
        return redirect(url_for('login'))

Files in my static directory are not being served however unless the user is logged in. 除非用户已登录,否则不会提供静态目录中的文件。

On my /login page I am sourcing a css file from the /static directory but it can not be loaded because of this before_request . 在我的/login页面上,我从/static目录中获取一个css文件,但由于这个before_request它无法加载。

I have deployed this application using apache mod_wsgi and in my apache configuration file I have even included the /static directory as the site's DocumentRoot. 我使用apache mod_wsgi部署了这个应用程序,在我的apache配置文件中,我甚至将/static目录作为站点的DocumentRoot包含在内。

How can I add an exception to serve my application's /static files without the user logging in, but still use this before_request for the routes defined by my flask application? 如何在没有用户登录的情况下添加异常来提供我的应用程序的/static文件,但是对于我的flask应用程序定义的路由仍然使用此before_request

You'll need to add an Alias or AliasMatch directive to your Apache config file (or .htaccess file, should you not have access to the .conf files) to ensure that Apache serves your static files, rather than Flask. 您需要向Apache配置文件(或.htaccess文件,如果您无权访问.conf文件)添加AliasAliasMatch指令,以确保Apache提供静态文件,而不是Flask。 Make sure that you have provided a Directory to allow the Apache web server to access your static path . 确保您提供了一个Directory允许Apache Web服务器访问您的静态路径 (Also, don't forget to restart Apache if you are editing the .conf files so your changes will be picked up). (另外,如果您正在编辑.conf文件,请不要忘记重新启动Apache,以便更改您的更改)。

As a temporary stop-gap measure (or to make it easy to work with in development) you could also check to make sure that the string /static/ is not in request.path : 作为临时的间隙措施(或者为了便于在开发中使用),您还可以检查以确保字符串/static/不在request.path

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

I think that there is a solution cleaner than checking request.path . 我认为有一个解决方案比检查request.path更清晰。

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

I do agree with the Apache approach, but for a quick fix I the following logic at the start of the before_request() function: 我同意Apache的方法,但为了快速修复,我在before_request()函数的开头有以下逻辑:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM