How to use lru_cache in a Python coroutine?

49 Views Asked by At

I need to implement lru_cache from Python's functools library in a coroutine, so I have this:

async def send_logs_simulation(self, simulation_id: int, logs: str):
        company_id = await self.get_company_id(simulation_id=simulation_id)
        data_room = {
            "id": simulation_id,
            "logs": logs,
        }
        data = MessageToRoom(
            event="update-logs",
            room=f"{simulation_id}-{company_id}",
            namespace="/dhog/simulation/logs",
            data=data_room,
        )
        await service_sockets.send_message_room(obj_in=data)
        return {"logs_sent": True}
    
    @lru_cache(maxsize=8)
    async def get_company_id(self, simulation_id: int):
        simulation_in_db = await self.get_by_id(_id=simulation_id)
        if not simulation_in_db:
            raise ValueError("Simulation not found")
        company_id = simulation_in_db["company_id"]
        return company_id

On the first call, the method runs fine, however, when I try to use the cache I get:

docker-ds-backend-service-1  | RuntimeError: cannot reuse already awaited coroutine

Why does this happen? Is there any way to implement it in a coroutine?

0

There are 0 best solutions below