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?
This aesthetic nature of websites is achieved by using static files, which comprise of Images, CSS files, and JS scripts. We save these static files in a separate folder called static located beside our main Flask application. Now that we have some knowledge about static files let’s see implement them.
Python Flask.before_first_request - 19 examples found. These are the top rated real world Python examples of flask.Flask.before_first_request extracted from open source projects.
Python Flask.before_first_request - 19 examples found. These are the top rated real world Python examples of flask.Flask.before_first_request extracted from open source projects. You can rate examples to help us improve the quality of examples.
A Flask application objects comes with 2 methods- after_request () and before_request ()- that can be assigned a function to run in the specified situation. From both of these functions you can make use of the request context, meaning you can access headers and other data from each 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. 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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With