跳转到主要内容

为Flask添加了依赖注入框架Injector的支持。

项目描述

https://codecov.io/gh/alecthomas/flask_injector/branch/master/graph/badge.svg https://github.com/alecthomas/flask_injector/workflows/CI/badge.svg

为Flask添加了Injector支持,这样就不需要使用全局Flask对象,这使得测试更简单。

Injector是一个受Guice启发的Python依赖注入框架。您可以在PyPI上找到Injector,并在Read the Docs上找到Injector文档

Flask-Injector与CPython 3.7+兼容。截至版本0.15.0,它需要版本0.20.0或更高版本的Injector和版本2.2.0或更高版本的Flask。

GitHub项目页面: https://github.com/alecthomas/flask_injector

PyPI包页面: https://pypi.ac.cn/project/Flask-Injector/

变更日志: https://github.com/alecthomas/flask_injector/blob/master/CHANGELOG.rst

功能

Flask-Injector允许您注入依赖到

  • 视图(函数和基于类的)

  • before_request 处理器

  • after_request 处理器

  • teardown_request 处理器

  • 模板上下文处理器

  • 错误处理器

  • Jinja 环境全局变量(在 app.jinja_env.globals 中的函数)

  • Flask-RESTFul 资源构造函数

  • Flask-RestPlus 资源构造函数

  • Flask-RESTX 资源构造函数

Flask-Injector 支持(Python 3)使用函数注解定义类型,见下文。

文档

由于 Flask-Injector 在底层使用 Injector,您应该找到 Injector 文档,包括 Injector API 参考,这将非常有用。 Injector README 提供了使用 Injector 的教程级介绍。

Flask-Injector 的公共 API 由以下内容组成

  • FlaskInjector 类,其构造函数接受以下参数

    • app,`flask.Flask` 的实例 [必需] – 要使用的 Flask 应用程序

    • modules,一个 Injector 模块 的可迭代对象 [可选] – 要使用的 Injector 模块。

    • injectorinjector.Injector 的实例 [可选] – 如果出于某种原因,不希望 FlaskInjector 创建一个新实例,则可以使用的 Injector 实例。您可能不需要使用此参数。

    • request_scope_class,一个 injector.Scope 子类 [可选] – 要使用的范围,而不是 RequestScope。您可能需要使用此参数,除非是进行测试。

  • RequestScope 类 – 一个 injector.Scope 子类,用于存储和重用请求作用域的依赖项

  • request 对象 – 作为类装饰器或在使用 Injector 模块中的显式 bind() 调用时使用。

创建 FlaskInjector 的实例将对传递给它的 Flask 应用程序执行副作用配置。以下绑定将被应用(如果您想修改它们,您需要在传递给 FlaskInjector 构造函数的模块中执行此操作)

  • flask.Flask 被绑定到(作用域:单例)Flask 应用程序

  • flask.Config 被绑定到 Flask 应用程序的配置

  • flask.Request 被绑定到当前 Flask 请求对象,相当于线程本地的 flask.request 对象(作用域:请求)

使用 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()

请参阅 example.py 以获取更完整的示例,包括 Flask-SQLAlchemyFlask-Cache 集成。

支持 Flask 扩展

通常,Flask 扩展使用类似于以下模式的模式在全局范围内初始化。

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

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

由于我们没有 Flask-Injector 中的这些全局变量,我们必须以 Injector 的方式配置扩展 – 通过模块。模块可以是 injector.Module 的子类,或者是一个接受 injector.Binder 实例的可调用对象。

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()

请确保将扩展对象绑定为单例。

项目详细信息


下载文件

下载适合您平台的应用文件。如果您不确定该选择哪一个,请了解有关安装包的更多信息。

源代码分发

Flask-Injector-0.15.0.tar.gz (13.5 kB 查看哈希值)

上传时间 源代码

构建分发

Flask_Injector-0.15.0-py2.py3-none-any.whl (14.1 kB 查看哈希值)

上传时间 Python 2 Python 3

由以下支持