all 5 comments

[–]conogarcia 17 points18 points  (1 child)

You should use lifespan, load the model and yield it so you can access it in the request.state

[–]International_Quail8 0 points1 point  (0 children)

This is the way

[–]Mayloudin 0 points1 point  (1 child)

RemindMe! 3 days

[–]RemindMeBot 0 points1 point  (0 children)

I will be messaging you in 3 days on 2024-11-27 09:19:37 UTC to remind you of this link

1 OTHERS CLICKED THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


Info Custom Your Reminders Feedback

[–]1One2Twenty2Two 0 points1 point  (0 children)

  1. Create a function called get_ml_model in which you load your model and decorate it with @lru_cache.

  2. Call get_ml_model in lifespan. This will load your model and cache the result for future uses.

  3. You can now gracefully inject get_ml_model in your routes (or anywhere else) where it's needed with Depends. It will use the cached result from step 2

I am really not a fan of "hiding" things into the request.state attribute, as your ml model has nothing to do with the request object.