wookie919 wookie919 - 3 months ago 12
Python Question

flask and flask_login - organizing code

I am currently coding up a simple web application using flask and flask_login, and got stuck due to a code organisation problem.

import flask
import flask_login

app = flask.Flask(__name__)

login_manager = flask_login.LoginManager()
login_manager.init_app(app)


The above works. The problem arises because I want to separate authentication related code from the main flask application code. In other words, I want
my_auth.py
that imports
flask_login
and initializes the
login_manager
, and I want
main.py
to
import my_auth
, and NOT have to import
flask_login
.

The problem is that
login_manager.init_app(app)
requires the main flask
app
to be passed in, and this clear separation seems difficult. Thus my questions are:


  1. Is what I am asking for even possible? If so, how?

  2. If what I am asking for is not possible, what is currently accepted as the best practice in organising such code?


Answer

You can do something like the following, if main.py and my_auth.py reside on same directory:

my_auth.py:

import flask_login

login_manager = flask_login.LoginManager()

main.py:

from flask import Flask
from my_auth import login_manager

app = Flask(__name__)
login_manager.init_app(app)
Comments