flask and flask_login - organizing code

旧街凉风 提交于 2019-12-08 07:19:01

问题


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?

回答1:


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)


来源:https://stackoverflow.com/questions/38930604/flask-and-flask-login-organizing-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!