Skip to content

Instantly share code, notes, and snippets.

@sm-Fifteen
Created October 13, 2019 00:05
Show Gist options
  • Save sm-Fifteen/2ceb7b453463b828dc1bb42077fdce63 to your computer and use it in GitHub Desktop.
Save sm-Fifteen/2ceb7b453463b828dc1bb42077fdce63 to your computer and use it in GitHub Desktop.
FastAPI lifetime tests
from fastapi import FastAPI
from lock import FileLock
app = FastAPI()
lock = FileLock("fastapi")
@app.get("/")
async def root():
return {"message": "Hello World"}
# Already, the lock doesn't get released anymore,
# even when shutting down uvicorn properly
from fastapi import FastAPI
from lock import FileLock
app = FastAPI()
lock: FileLock
@app.on_event("startup")
def take_lock():
global lock
lock = FileLock("fastapi")
@app.on_event("shutdown")
def release_lock():
global lock
del lock
@app.get("/")
async def root():
return {"message": "Hello World"}
import sys
from pathlib import Path
class FileLock:
def __new__(cls, lockname: str):
lockpath = Path(sys.path[0]) / f'{lockname}.lock'
try:
lockpath.touch(exist_ok=False)
print("Lock taken!")
self = super(FileLock,cls).__new__(cls)
self.lockpath = lockpath
return self
except FileExistsError as ex:
print("Someone else has the lock :(")
raise ex
def __del__(self):
try:
self.lockpath.unlink()
print("Lock released!")
except FileNotFoundError as ex:
print("What happenned to the lock??")
raise ex
from lock import FileLock
from time import sleep
lock = FileLock("test_lock")
print("You'd better not try to start another instance of this, now! No siree!")
sleep(3600)
print("Ok, all done!")
# The lock should release itself once garbage collected
# before the interpreter exits.
@sm-Fifteen
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment