0

I'm using this new framework I've created called PyNest, which is based on the architecture of nestJS but with an adaptation to Python. the web engine is a fastapi.

My controller looks like this:

from nest.core import Controller, Get, Post, Depends, Put, Delete

from src.product.product_service import ProductService
from src.product.product_model import Product

@Controller("product")
class ProductController:

    service: ProductService = Depends(ProductService)
    
    @Get("/get_products")
    def get_products(self):
        return self.service.get_products()

And my service looks like this:

from src.product.product_model import Product
from src.product.product_entity import Product as ProductEntity
from orm_config import config
from nest.core.decorators import db_request_handler

class ProductService:

    def __init__(self):
        self.orm_config = config
        self.session = self.orm_config.get_db()
        time.sleep(5)
    
    
    @db_request_handler
    def get_products(self):
        return self.session.query(ProductEntity).all()

The problem is that for each api call i make to the 'get_products' route, the controller re initialize the service, so in this example there is this overhead of 5 seconds for each request. of course that the time.sleep is only for demonstration of action that is requierd for the service init (loading staff to memory and etc).

i wish that the controller will initialize the service once whenever the app is creating.

any idea how can i solve this?

iv'e tried to work with redis, but this is quiet a work around and not very intuitive, thus i try to load from redis the object i wanted to load.

another option is to load the object on the global scope into a varible that the service will use, but it feels like a bad practice.

  • There many ways of caching the created service, for example by decorating a function with `functools.lru_cache` - that way it'll only take extensive time the first time the object is needed (which you can call and discard on startup if necessary). – MatsLindh Jul 12 '23 at 18:31
  • That works perfectly! thank you for that – ItayDar Jul 12 '23 at 19:58
  • You may find [this answer](https://stackoverflow.com/a/76322910/17865804) helpful as well – Chris Jul 13 '23 at 04:52

0 Answers0