python-dependency-injector/tests/unit/samples/wiringfastapi/web.py

41 lines
969 B
Python
Raw Normal View History

2020-12-06 05:36:30 +03:00
import sys
from fastapi import FastAPI, Depends
from fastapi import Request # See: https://github.com/ets-labs/python-dependency-injector/issues/398
2020-12-06 05:36:30 +03:00
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from dependency_injector import containers, providers
from dependency_injector.wiring import inject, Provide
class Service:
async def process(self) -> str:
2021-10-01 03:09:42 +03:00
return "Ok"
2020-12-06 05:36:30 +03:00
class Container(containers.DeclarativeContainer):
service = providers.Factory(Service)
app = FastAPI()
security = HTTPBasic()
2021-10-01 03:09:42 +03:00
@app.api_route("/")
2020-12-06 05:36:30 +03:00
@inject
async def index(service: Service = Depends(Provide[Container.service])):
result = await service.process()
2021-10-01 03:09:42 +03:00
return {"result": result}
2020-12-06 05:36:30 +03:00
2021-10-01 03:09:42 +03:00
@app.get("/auth")
2020-12-06 05:36:30 +03:00
@inject
def read_current_user(
credentials: HTTPBasicCredentials = Depends(security)
):
2021-10-01 03:09:42 +03:00
return {"username": credentials.username, "password": credentials.password}
2020-12-06 05:36:30 +03:00
container = Container()
container.wire(modules=[sys.modules[__name__]])