From a8dd94bf2053e9943e6638bc1f7283e534161b9e Mon Sep 17 00:00:00 2001 From: DingZQ Date: Sat, 21 Oct 2023 08:59:10 +0800 Subject: [PATCH] Refine --- main.py | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/main.py b/main.py index 8972ba7..2d3161c 100644 --- a/main.py +++ b/main.py @@ -33,6 +33,8 @@ if not os.path.exists(inpDir): if not os.path.exists(tmpDir): os.mkdir(tmpDir) +lock_simulation = asyncio.Lock() + app = FastAPI() app.add_middleware(GZipMiddleware, minimum_size=1000) @@ -146,19 +148,21 @@ async def fastapi_dump_inp(network: str, inp: str) -> bool: dump_inp(network, inp) return True -app.state.is_simulation = False - # 必须用这个PlainTextResponse,不然每个key都有引号 @app.get("/runproject/", response_class = PlainTextResponse) -def fastapi_run_project(network: str) -> str: - if app.state.is_simulation: - raise HTTPException(status_code=409, detail="is in simulation") - else: - app.state.is_simulation = True - result = run_project(network) - app.state.is_simulation = False - return result +async def fastapi_run_project(network: str) -> str: + if lock_simulation.locked(): + raise HTTPException(status_code=409, detail="is in simulation") + + await lock_simulation.acquire() + + try: + result = run_project(network) + return result + finally: + lock_simulation.release() # Release the lock + # put in inp folder, name without extension @app.get("/runinp/") async def fastapi_run_inp(network: str) -> str: