Skip to content

Command line arguments and di #95

@dineshbvadhia

Description

@dineshbvadhia

@adriangb Came across this comment of yours from a while back: fastapi/fastapi#4035 (comment)

The problem I want to solve is passing command line parameters to a dependency injection. In this spirit and also by way of comparison:

a. How can command line arguments be passed to app.state via on_startup (or lifespan)?
b. How can this be achieved with di?

Your code with a command line argument (s: str) to illustrate the problem is:

from fastapi import FastAPI, Depends, Request

class MyObj:
    def __init__(self, something: str) -> None:
        self.something = something

# Pass the command line argument s here and into MyObj()
async def on_startup() -> None:
    app.state.myobj = MyObj(s)

app = FastAPI(on_startup=[on_startup])

def get_myobj(request: Request) -> MyObj:
    return request.app.state.myobj

@app.get("/")
async def index(myobj: MyObj = Depends(get_myobj)) -> None:
    assert isinstance(myobj, MyObj)
    assert myobj.something == 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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions