简体   繁体   中英

Removing global app reference from blueprint in Flask

I'm currently working on learning Flask and create a working page with login functions. Now I want to remove the global app instance and started using blueprints for the submodules.

My project is structured like this:

+ app
    + auth
        - __init__.py
        - forms.py
        - routes.py
    + main
    + models
    + templates
    - __init__.py
+ migrations
- index.py
- config.py

No I added a blueprint to the routes.py and used the decorators there:

from flask import render_template, flash, redirect, url_for, request, Blueprint
from app import app, db
from app.auth.forms import LoginForm, RegistrationForm
# ...
from app.models.User import User

blueprint = Blueprint('auth', __name__)

@blueprint.route('/login', methods=['GET', 'POST'])
def login():
    return "example login"

The __init__.py of the auth module:

from . import forms, routes

The blueprint gets added in the __init__.py of the app folder:

# ...
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
from app.auth.routes import blueprint as auth_bp
app.register_blueprint(auth_bp)

After using the @blueprint decorators, I don't need @app anymore, but how can I access the db when I want to remove the import app and the from app.models.User import User part?

from . import db
from ..models.User import User

There are two things to understand here. app as a module (the folder) and app the instance of flask inside __init__.py . When you do import app inside authentication blueprint then you are actually importing the whole app module and not the flask instance. When you do from app import app you are actually importing flask instance from app module. This can be confusing to eliminate this I advise you to change the name of app folder to something different like bacher then when you need to import db inside your authentication blueprint use from bacher import db and for User model from bacher.models.User import User

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