0
0
Flaskframework~5 mins

Extension initialization pattern in Flask

Choose your learning style9 modes available
Introduction

The extension initialization pattern helps you add extra features to your Flask app in a clean and organized way.

When you want to add a database to your Flask app using an extension like Flask-SQLAlchemy.
When you need to add user login support with Flask-Login.
When you want to add email support with Flask-Mail.
When you want to keep your app setup simple and flexible for different environments.
Syntax
Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb.sqlite'
    db.init_app(app)
    return app

First, create the extension object outside the app factory.

Then, inside the app factory, call init_app() on the extension with the app.

Examples
This example shows initializing the Flask-Login extension using the pattern.
Flask
from flask import Flask
from flask_login import LoginManager

login_manager = LoginManager()

def create_app():
    app = Flask(__name__)
    login_manager.init_app(app)
    return app
This example shows how to initialize Flask-Mail with configuration inside the app factory.
Flask
from flask import Flask
from flask_mail import Mail

mail = Mail()

def create_app():
    app = Flask(__name__)
    app.config['MAIL_SERVER'] = 'smtp.example.com'
    mail.init_app(app)
    return app
Sample Program

This program creates a Flask app using the extension initialization pattern. The database extension is created outside the app and initialized inside the factory. The app runs and shows a simple message at the home page.

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# Create the extension object
db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
    db.init_app(app)

    @app.route('/')
    def home():
        return 'Hello, Flask with extension!'

    return app

if __name__ == '__main__':
    app = create_app()
    app.run(debug=True)
OutputSuccess
Important Notes

Creating the extension outside the app lets you use it in multiple apps or scripts.

Calling init_app() inside the factory connects the extension to the app.

This pattern helps keep your code clean and easy to test.

Summary

The extension initialization pattern separates extension creation and app setup.

Use init_app() to connect extensions to your Flask app inside a factory function.

This makes your app flexible and organized.