-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
Description
Hey community,
I don't know if this feature is available, but I want to ask if I can use dependencies outside endpoint path decorators and functions..
I have this repository, when inside some function on that, I need another repository function to perform the full task.
What I want to do is to inject that as a dependency, and not to create an instance of it, since that is best way to do that here in python, because I come from background of Java and I always used to initialize a instance of that Class.
So basically..I have a function to get an instance of SynonymCrud()
def get_synonym_crud():
return synonym_crud
the function in to create a word, in #word_crud.py
def create_word(self, word: WordCreate, dictionary_id: int, synonym: List[SynonymCreate],synonym_crud:SynonymCrud = Depends(get_synonym_crud)):
w_dict = word.dict()
w_dict.update({"word": word.word.lower()})
db_word = Word(**w_dict, dictionary_id=dictionary_id)
self.database.add(db_word)
self.database.commit()
self.database.refresh(db_word)
synonyms_to_create = synonym_crud.create_many_synonyms(synonym, db_word.id)
return db_word
Here I tried to inject: synonym_crud:SynonymCrud = Depends(get_synonym_crud),
but when I try to execute this on the endpoint I get an error, that says:
AttributeError: 'Depends' object has no attribute 'create_many_synonyms', even tho I got this function in the SynonymRepository.
This is not the only case, even when I try to inject anything else like database dependency outside the endpoint I get like: AttributeError: 'Depends' object has no attribute 'query' or something similar.
endpoint..
@router.post("/tests/words/", response_model=Word)
def create_word(request: Request, word: WordCreate, dictionary_id: int,
synonym: List[SynonymCreate],
logger: logging.Logger = Depends(get_logger_test),
word_repo: WordCrud = Depends(get_word_crud),
current_user: User = Depends(get_curr_active_superuser)):
word_to_create = word_repo.find_by_name(word.word)
if word_to_create:
raise HTTPException(status_code=400, detail="Word already exists")
word_created = word_repo.create_word(word, dictionary_id, synonym)
return word_created
Here the other dependency word_repo, works without any error, but when I try to inject anything outside the endpoint functions( like the example with synonym).
Is this possible, or what am I doing wrong?
Thank you in advance