Potential Usages

FastDepends is a great instrument to integrate with any frameworks you are already using. It can also be a part of your own tools and frameworks (HTTP or not* )

There are some usage examples with popular Python HTTP Frameworks:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from flask import Flask
from fast_depends import inject, Depends
from pydantic import Field

app = Flask(__name__)

def get_user(user_id: int = Field(..., alias="id")):
    return f"user {user_id}"

@app.get("/<id>")
@inject
def hello(user: str = Depends(get_user)):
    return f"<p>Hello, {user}!</p>"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Is that FastAPI???
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route
from pydantic import Field
from fast_depends import inject, Depends

def unwrap_path(func):
    async def wrapper(request):  # unwrap incoming params to **kwargs here
        return await func(**request.path_params)
    return wrapper

async def get_user(user_id: int = Field(..., alias="id")):
    return f"user {user_id}"

@unwrap_path
@inject  # cast incoming kwargs here
async def hello(user: str = Depends(get_user)):
    return PlainTextResponse(f"Hello, {user}!")

app = Starlette(debug=True, routes=[
    Route("/{id}", hello)
])

As you can see above, library, some middlewares and supporting classes... And you can use the whole power of typed Python everywhere.

Tip

FastDepends raises pydantic.error_wrappers.ValidationError at type casting exceptions.

You need to handle them and wrap them in your own response with your custom middleware if you want to use it in production.

Note

If you are interested in using FastDepends in other frameworks, please take a look at my own Propan framework for working with various Message Brokers.