简体   繁体   中英

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:

flask before request - add exception for specific route

Here is a copy of my 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 .

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.

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?

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. Make sure that you have provided a Directory to allow the Apache web server to access your static path . (Also, don't forget to restart Apache if you are editing the .conf files so your changes will be picked up).

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 :

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 .

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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