Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Command line arguments and di #95

Open
dineshbvadhia opened this issue Feb 24, 2023 · 1 comment
Open

Command line arguments and di #95

dineshbvadhia opened this issue Feb 24, 2023 · 1 comment

Comments

@dineshbvadhia
Copy link

dineshbvadhia commented Feb 24, 2023

@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)
@dineshbvadhia
Copy link
Author

Close

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant