bobthemighty / punq

An IoC container for Python 3.8+
MIT License
307 stars 14 forks source link

Question: Capture command line arguments to create Singleton for FastApi service #174

Closed dineshbvadhia closed 1 year ago

dineshbvadhia commented 1 year ago

I want to capture the command line arguments to create a Singleton and make it available to all the endpoints in a FastApi service. The (non-working) code below is for illustration only: the command line argument s: str is transformed into the Singleton thisobj and made available to the routes. Is this possible with punq?

ffrom fastapi import FastAPI, Depends, Request

class ThisObj:
    def __init__(self, thing: str) -> None:
        self.thing = thing

# Want to pass CLI arguments to on_startup here
async def on_startup() -> None:
    app.state.thisobj = ThisObj(s)

app = FastAPI(on_startup=[on_startup])

def get_thisobj(request: Request) -> ThisObj:
    return request.app.state.thisobj

@app.get("/")
async def index(thisobj: ThisObj = Depends(get_thisobj)) -> None:
    assert isinstance(thisobj, ThisObj)
    assert thisobj.thing == s

def main(args):
    params: list[str] = args[2].split()
    s: str = params[0]

    uvicorn.run('main:app', host="127.0.0.1", port=8000, reload=True)

if __name__ == "__main__":
    main(sys.argv)
dineshbvadhia commented 1 year ago

Close