Adds Injector support to Flask.

Related tags

Flaskflask_injector
Overview

Flask-Injector

Build status Coverage status

Adds Injector support to Flask, this way there's no need to use global Flask objects, which makes testing simpler.

Injector is a dependency-injection framework for Python, inspired by Guice. You can find Injector on PyPI and Injector documentation on Read the Docs.

Flask-Injector is compatible with CPython 3.5+. As of version 0.12.0 it requires Injector version 0.13.2 or greater and Flask 1.0 or greater.

GitHub project page: https://github.com/alecthomas/flask_injector

PyPI package page: https://pypi.org/project/Flask-Injector/

Changelog: https://github.com/alecthomas/flask_injector/blob/master/CHANGELOG.rst

Features

Flask-Injector lets you inject dependencies into:

  • views (functions and class-based)
  • before_request handlers
  • after_request handlers
  • teardown_request handlers
  • template context processors
  • error handlers
  • Jinja environment globals (functions in app.jinja_env.globals)
  • Flask-RESTFul Resource constructors
  • Flask-RestPlus Resource constructors
  • Flask-RESTX Resource constructors

Flask-Injector supports defining types using function annotations (Python 3), see below.

Documentation

As Flask-Injector uses Injector under the hood you should find the Injector documentation, including the Injector API reference, helpful. The Injector README provides a tutorial-level introduction to using Injector.

The Flask-Injector public API consists of the following:

  • FlaskInjector class with the constructor taking the following parameters:
    • app, an instance of`flask.Flask` [mandatory] – the Flask application to be used
    • modules, an iterable of Injector modules [optional] – the Injector modules to be used.
    • injector, an instance of injector.Injector [optional] – an instance of Injector to be used if, for some reason, it's not desirable for FlaskInjector to create a new one. You're likely to not need to use this.
    • request_scope_class, an injector.Scope subclass [optional] – the scope to be used instead of RequestScope. You're likely to need to use this except for testing.
  • RequestScope class – an injector.Scope subclass to be used for storing and reusing request-scoped dependencies
  • request object – to be used as a class decorator or in explicit bind() calls in Injector modules.

Creating an instance of FlaskInjector performs side-effectful configuration of the Flask application passed to it. The following bindings are applied (if you want to modify them you need to do it in one of the modules passed to the FlaskInjector constructor):

  • flask.Flask is bound to the Flask application in the (scope: singleton)
  • flask.Config is bound to the configuration of the Flask application
  • flask.Request is bound to the current Flask request object, equivalent to the thread-local flask.request object (scope: request)

Example application using Flask-Injector

import sqlite3
from flask import Flask, Config
from flask.views import View
from flask_injector import FlaskInjector
from injector import inject

app = Flask(__name__)

# Configure your application by attaching views, handlers, context processors etc.:

@app.route("/bar")
def bar():
    return render("bar.html")


# Route with injection
@app.route("/foo")
def foo(db: sqlite3.Connection):
    users = db.execute('SELECT * FROM users').all()
    return render("foo.html")


# Class-based view with injected constructor
class Waz(View):
    @inject
    def __init__(self, db: sqlite3.Connection):
        self.db = db

    def dispatch_request(self, key):
        users = self.db.execute('SELECT * FROM users WHERE name=?', (key,)).all()
        return 'waz'

app.add_url_rule('/waz/<key>', view_func=Waz.as_view('waz'))


# In the Injector world, all dependency configuration and initialization is
# performed in modules (https://injector.readthedocs.io/en/latest/terminology.html#module).
# The same is true with Flask-Injector. You can see some examples of configuring
# Flask extensions through modules below.

# Accordingly, the next step is to create modules for any objects we want made
# available to the application. Note that in this example we also use the
# Injector to gain access to the `flask.Config`:

def configure(binder):
    binder.bind(
        sqlite3.Connection,
        to=sqlite3.Connection(':memory:'),
        scope=request,
    )

# Initialize Flask-Injector. This needs to be run *after* you attached all
# views, handlers, context processors and template globals.

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

# All that remains is to run the application

app.run()

See example.py for a more complete example, including Flask-SQLAlchemy and Flask-Cache integration.

Supporting Flask Extensions

Typically, Flask extensions are initialized at the global scope using a pattern similar to the following.

app = Flask(__name__)
ext = ExtClass(app)

@app.route(...)
def view():
    # Use ext object here...

As we don't have these globals with Flask-Injector we have to configure the extension the Injector way - through modules. Modules can either be subclasses of injector.Module or a callable taking an injector.Binder instance.

from injector import Module

class MyModule(Module):
    @provider
    @singleton
    def provide_ext(self, app: Flask) -> ExtClass:
        return ExtClass(app)

def main():
    app = Flask(__name__)
    app.config.update(
        EXT_CONFIG_VAR='some_value',
    )

    # attach your views etc. here

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

    app.run()

Make sure to bind extension objects as singletons.

Owner
Alec Thomas
Alec Thomas
A python package for integrating ripozo with Flask

flask-ripozo This package provides a dispatcher for ripozo so that you can integrate ripozo with Flask. As with all dispatchers it is simply for getti

Vertical Knowledge 14 Dec 03, 2018
Regex Converter for Flask URL Routes

Flask-Reggie Enable Regex Routes within Flask Installation pip install flask-reggie Configuration To enable regex routes within your application from

Rhys Elsmore 48 Mar 07, 2022
Flask-template - A simple template for make an flask api

flask-template By GaGoU :3 a simple template for make an flask api notes: you ca

GaGoU 2 Feb 17, 2022
Flask extension that takes care of API representation and authentication.

Flask-API-Utils Flask-API-Utils helps you to create APIs. It makes responses in appropriate formats, for instance, JSON. All you need to do is to retu

Marsel Mavletkulov 55 Aug 28, 2022
A live chat built with python(flask + gevent + apscheduler) + redis

a live chat room built with python(flask / gevent / apscheduler) + redis Basic Architecture Screenshot Install cd /path/to/source python bootstrap.py

Limboy 309 Nov 13, 2022
This is a small notes web app, with python and flask microframework. Using sqlite3

Python Notes App. This is a small web application maked with flask-python for add notes easily and quickly. Dependencies. You can create a virtual env

Eduard 1 Dec 26, 2021
a flask profiler which watches endpoint calls and tries to make some analysis.

Flask-profiler version: 1.8 Flask-profiler measures endpoints defined in your flask application; and provides you fine-grained report through a web in

Mustafa Atik 718 Dec 20, 2022
A web application for a fake pizza store, built in Python with Flask and PostgreSQL.

✨ Pizza Pizza - Pizza Store ✨ A web application for a fake Pizza Store, the app let you create an account and order pizza, complements or drinks. Buil

Bonnie Fave 6 Dec 18, 2022
Full Stack Web Development with Flask.

Discover Flask Full Stack Web Development with Flask. http://discoverflask.com Flask is a micro web framework powered by Python. Its API is fairly sma

Real Python 4.4k Jan 06, 2023
Flask Boilerplate - Paper Kit Design | AppSeed

Flask Paper Kit Open-Source Web App coded in Flask Framework - Provided by AppSeed Web App Generator. App Features: SQLite database SQLAlchemy ORM Ses

App Generator 86 Nov 29, 2021
SqlAlchemy Flask-Restful Swagger Json:API OpenAPI

SAFRS: Python OpenAPI & JSON:API Framework Overview Installation JSON:API Interface Resource Objects Relationships Methods Custom Methods Class Method

Thomas Pollet 365 Jan 06, 2023
A simple application builder. Made with python.

Python Flask Server Template Check the Github Repository for updates Flask is an application builder. It is very common in Python but can also be used

1 Jan 09, 2022
Flask + marshmallow for beautiful APIs

Flask-Marshmallow Flask + marshmallow for beautiful APIs Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmal

marshmallow-code 770 Jan 05, 2023
The Coodesh Python Backend Challenge (2021) written in Flask

Coodesh Back-end Challenge 🏅 2021 ID: 917 The Python Back-end Coodesh Challenge Description This API automatically retrieves users from the RandomUse

Marcus Vinicius Pereira 1 Oct 20, 2021
Flask-redmail - Email sending for Flask

Flask Red Mail: Email Sending for Flask Flask extension for Red Mail What is it?

Mikael Koli 11 Sep 23, 2022
docker-compose uWSGI nginx flask

docker-compose uWSGI nginx flask Note that this was tested on CentOS 7 Usage sudo yum install docker

Abdolkarim Saeedi 3 Sep 11, 2022
Companion code to my O'Reilly book "Flask Web Development", second edition.

Flasky This repository contains the source code examples for the second edition of my O'Reilly book Flask Web Development. The commits and tags in thi

Miguel Grinberg 8k Dec 27, 2022
Flask-app scaffold, generate flask restful backend

Flask-app scaffold, generate flask restful backend

jacksmile 1 Nov 24, 2021
flask extension for integration with the awesome pydantic package

Flask-Pydantic Flask extension for integration of the awesome pydantic package with Flask. Installation python3 -m pip install Flask-Pydantic Basics U

248 Dec 26, 2022
A caching extension for Flask

Flask-Caching Adds easy cache support to Flask. This is a fork of the Flask-Cache extension. Flask-Caching also includes the cache module from werkzeu

Peter Justin 774 Jan 02, 2023