Search code examples
pythonflask.htpasswd

Flask authentication using htpassword with routes in seperate files


I'm working on updating an existing university department internal website to run using Flask. Before we completely release the project where it will use shibboleth to manage authentication, I've been trying to setup authentication for testing using htpassword using this tutorial. I'm able to get authentication using htpasswords working for a single file, but I can't figure out how to add the authentication to separate files. Currently, the project looks like this:

This is my main file called app.py:

#app.py
from flask import Flask
from flask_htpasswd import HtPasswdAuth

app = Flask(__name__)
app.config['FLASK_HTPASSWD_PATH'] = '.htpasswd'
app.config['FLASK_SECRET'] = "Super secret key that I will change later"

htpasswd = HtPasswdAuth(app)

import exampleRoute

@app.route('/')
@htpasswd.required
def home(user):
    return "This is the homepage"

This is an example of one of my route files called exampleRoute.py:

# exampleRoute.py
from app import app
from flask import Flask

@app.route('/exampleRoute')
def exampleRoute():
    return "This is an example route in another file"

When I place the @htpassword.required decorator in front of exampleRoute(), I get an error saying that htpassword is not defined (which makes sense). I've tried to import the app configuration a few different ways and at best, I end up with a circular dependency. I know that I could place the authentication code in a separate file and then import that into all my endpoints, but I didn't think this was possible since this method is incorporated into the app configuration.


Solution

  • I ended up getting an answer from the reddit user alexisprince. The solution was to use Blueprints that import htpasswd from another file (called extensions.py).