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
This repo contains the Flask API to expose model and get predictions.

Tea Leaf Quality Srilanka Chapter This repo contains the Flask API to expose model and get predictions. Expose Model As An API Model Trainig will happ

DuKe786 2 Nov 12, 2021
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 870 Jan 08, 2023
Live Corona statistics and information site with flask.

Flask Live Corona Info Live Corona statistics and information site with flask. Tools Flask Scrapy Matplotlib How to Run Project Download Codes git clo

Mohammad Dori 5 Jul 15, 2022
Track requests to your Flask website with Matomo

Flask-Matomo Flask-Matomo is a library which lets you track the requests of your Flask website using Matomo (Piwik). Installation pip install flask-ma

Lucas Hild 13 Jul 14, 2022
This is a repository for a playlist of videos where I teach building RESTful API with Flask and Flask extensions.

Build And Deploy A REST API with Flask This is code for a series of videos in which we look at the various concepts involved when building a REST API

Ssali Jonathan 10 Nov 24, 2022
Flask webassets integration.

Integrates the webassets library with Flask, adding support for merging, minifying and compiling CSS and Javascript files. Documentation: https://flas

Michael Elsdörfer 433 Dec 29, 2022
A web application made with Flask that works with a weather service API to get the current weather from all over the world.

Weather App A web application made with Flask that works with a weather service API to get the current weather from all over the world. Uses data from

Christian Jairo Sarmiento 19 Dec 02, 2022
A simple way to demo Flask apps from your machine.

flask-ngrok A simple way to demo Flask apps from your machine. Makes your Flask apps running on localhost available over the internet via the excellen

117 Dec 27, 2022
A simple FastAPI web service + Vue.js based UI over a rclip-style clip embedding database.

Explore CLIP Embeddings in a rclip database A simple FastAPI web service + Vue.js based UI over a rclip-style clip embedding database. A live demo of

18 Oct 15, 2022
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
Beautiful Interactive tables in your Flask templates.

flask-tables Beautiful interactive tables in your Flask templates Resources Video demonstration: Go to YouTube video. Learn how to use this code: Go t

Miguel Grinberg 209 Jan 05, 2023
OpenTracing instrumentation for the Flask microframework

Flask-OpenTracing This package enables distributed tracing in Flask applications via The OpenTracing Project. Once a production system contends with r

3rd-Party OpenTracing API Contributions 133 Dec 19, 2022
Full text search for flask.

flask-msearch Installation To install flask-msearch: pip install flask-msearch # when MSEARCH_BACKEND = "whoosh" pip install whoosh blinker # when MSE

honmaple 197 Dec 29, 2022
Python web-app (Flask) to browse Tandoor recipes on the local network

RecipeBook - Tandoor Python web-app (Flask) to browse Tandoor recipes on the local network. Designed for use with E-Ink screens. For a version that wo

5 Oct 02, 2022
A template themes for phyton flask website

Flask Phyton Web template A template themes for phyton flask website

Mesin Kasir 2 Nov 29, 2021
Map Matching & Weight Completion service - Java (Springboot) & Python(Flask)

Map Matching service to match coordinates to roads using Java and Springboot. Weight Completion service to fill in missing weights in a graph, using Python and Flask.

2 May 13, 2022
Alexa Skills Kit for Python

Program the Amazon Echo with Python Flask-Ask is a Flask extension that makes building Alexa skills for the Amazon Echo easier and much more fun. Flas

John Wheeler 1.9k Dec 30, 2022
A service made with Flask and Python to help you find the weather of your favorite cities.

Weather-App A service made with Flask and Python to help you find the weather of your favorite cities. Features Backend using Flask and Jinja Weather

Cauã Rinaldi 1 Nov 17, 2022
5 Flask Projects To Get Started

5 Flask Projects Projects Made By Using Flask Projects List Rock Paper Scissor Game - A Simple Game Weather App - A OpenWeatherMap Scraper Task List -

Root_Arch 59 Dec 18, 2022
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