Skip to content Skip to sidebar Skip to footer

Dependency Injection Problem With FastAPI On Python

Good day! Please tell me how you can solve the following problem in Python + FastAPI. There is a test project: app / main.py - main file app / routes / users.py -set of api methods

Solution 1:

As noted in the comments, a dependency can be anything that is a callable and thus a class as well. The only caveat in the latter case is that the class will only be initialized (i.e. only the __init__(...) function will be called).

So, in order to have a class as dependency, as in the example of https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/#shortcut you just need to call the target functions within the init and set the values as attributes of the class.

from ..domain.user import User

class UserRepository:
    def __init__(self):
        self.get_all()

    def get_all(self):
        self.users = [User(1, 'A'), User(2, 'B'), User(3, 'C')]


from fastapi import Depends
from ..repos.user_repository import UserRepository

def get_repo(repo=Depends(UserRepository)):
    print(repo.users) # This will print the list of users
    return repo

QUESTION 2

NB

This is a modelling question. Here I propose what I believe is suitable from my point of view. It does not necessarily have to be best or simplest approach.

Answering your second question, I would not advice for such complex dependencies. If the dependencies are at the router level, you can simply add them to the router, using the parameter depends=[...] and providing a list of dependency classes/functions.

Alternatively, you could declare all of the dependencies as function parameters of the endpoint, as you did for the factory. This method may lead to big chunks of code getting copied and pasted, so I advise for the above approach.

If you need to process the data parameters, then you add them to the request and access them from within the endpoint. See FastAPI get user ID from API key for a minimal example.


Solution 2:

The __call__ method must be implemented in the class.


Post a Comment for "Dependency Injection Problem With FastAPI On Python"