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.