Flask-Injector

raw JSON →
0.15.0 verified Mon Apr 27 auth: no python

Adds Injector, a Dependency Injection framework, support to Flask. Current version 0.15.0, maintained irregularly.

pip install flask-injector
error ImportError: cannot import name 'FlaskInjector' from 'flask.ext.injector'
cause The flask.ext namespace is deprecated and removed in Flask 2.3.
fix
Use 'from flask_injector import FlaskInjector' instead.
error TypeError: 'module' object is not callable when using @inject
cause Importing @inject from flask_injector instead of injector.
fix
Import inject: from injector import inject
error AssertionError: No application found
cause FlaskInjector not initialized or app object not passed correctly.
fix
Ensure FlaskInjector(app=app) is called after app creation and before first request.
deprecated The 'flask.ext.injector' import pattern is deprecated and will break in Flask 2.3+. Use 'flask_injector' directly.
fix Replace 'from flask.ext.injector import FlaskInjector' with 'from flask_injector import FlaskInjector'.
gotcha Injector uses static type hints for injection. If you omit type hints or use incorrect ones, injection may fail silently.
fix Always annotate parameters with the exact class type expected, not strings or unions.
gotcha You must call FlaskInjector(app=app) before any request is handled. If called after route registration, dependencies may not be resolved inside views.
fix Initialize FlaskInjector right after creating the Flask app and before returning it from the factory function.
breaking Injector 0.18+ changed the way modules are configured. If you use older patterns like 'modules=[lambda binder: binder.bind(...)]', this still works, but future versions may drop support.
fix Use a function with a binder parameter, or a class implementing configure().

Basic integration with Flask and Injector.

from flask import Flask, jsonify
from flask_injector import FlaskInjector
from injector import inject, singleton

class Greeter:
    def greet(self, name: str) -> str:
        return f'Hello, {name}!'

app = Flask(__name__)

@app.route('/')
@inject
def home(greeter: Greeter):
    return jsonify({'greeting': greeter.greet('World')})

def configure(binder):
    binder.bind(Greeter, to=Greeter, scope=singleton)

FlaskInjector(app=app, modules=[configure])

if __name__ == '__main__':
    app.run()