FastAPI +依赖注入器





嗨,



我已经发布了新版本的Dependency Injector 4.4。它使您可以将Dependency Injector与FastAPI一起使用在这篇文章中,我将向您展示其工作原理。



集成的主要任务是通过Depends带有标记ProvideProviderDependency InjectorFastAPI指令结识朋友



在DI 4.4之前,它开箱即用。FastAPI使用输入法和Pydantic进行输入和响应验证。依赖注入器标记使他困惑。



该解决方案是在检查FastAPI的内部之后得出的。我必须对“依赖注入器”的接线模块进行一些更改。该指令Depends现在可以与标记Provide一起使用Provider





创建一个文件fastapi_di_example.py,并将以下行放入其中:



import sys

from fastapi import FastAPI, Depends
from dependency_injector import containers, providers
from dependency_injector.wiring import inject, Provide


class Service:
    async def process(self) -> str:
        return 'Ok'


class Container(containers.DeclarativeContainer):

    service = providers.Factory(Service)


app = FastAPI()


@app.api_route('/')
@inject
async def index(service: Service = Depends(Provide[Container.service])):
    result = await service.process()
    return {'result': result}


container = Container()
container.wire(modules=[sys.modules[__name__]])


要运行该示例,请安装依赖项:



pip install fastapi dependency-injector uvicorn


并运行uvicorn



uvicorn fastapi_di_example:app --reload


终端应显示以下内容:



INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [11910] using watchgod
INFO:     Started server process [11912]
INFO:     Waiting for application startup.
INFO:     Application startup complete.


http://127.0.0.1:8000应返回:



{
    "result": "Ok"
}




怎么测试?



在文件旁边创建一个文件tests.py,并将以下行放入其中:



from unittest import mock

import pytest
from httpx import AsyncClient

from fastapi_di_example import app, container, Service


@pytest.fixture
def client(event_loop):
    client = AsyncClient(app=app, base_url='http://test')
    yield client
    event_loop.run_until_complete(client.aclose())


@pytest.mark.asyncio
async def test_index(client):
    service_mock = mock.AsyncMock(spec=Service)
    service_mock.process.return_value = 'Foo'

    with container.service.override(service_mock):
        response = await client.get('/')

    assert response.status_code == 200
    assert response.json() == {'result': 'Foo'}


要运行测试,请安装依赖项:



pip install pytest pytest-asyncio httpx


并运行pytest



pytest tests.py


终端应显示:



======= test session starts =======
platform darwin -- Python 3.8.3, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: ...
plugins: asyncio-0.14.0
collected 1 item

tests.py .                                                      [100%]

======= 1 passed in 0.17s =======


整合能带来什么?



FastAPI是一个很酷的API构建框架。内置了基本的依赖项注入机制。



这种集成改进了FastAPI中的依赖项注入。它允许您在其中使用依赖项注入器的提供程序,替代,配置和资源。



下一步是什么?






All Articles