Starting fastapi with on_event() from user-supplied CLI arguments #6055
-
First Check
Commit to Help
Example Codeapp = FastAPI()
@app.get("/item")
def do_get_item(p3):
return get_item()
@app.on_event("startup")
def app_startup(p1, p2):
do_startup_stuff(p1, p2)
@app.on_event("shutdown")
def app_shutdown(p4):
do_shutdown_stuff(p4)
def main(args):
p1 = args[0]
p2 = args[1]
uvicorn.run(app)
if __name__ == "__main__":
main(sys.argv)
Command Line
> python myapp.py --p1 avatar2 --p2 wateryDescriptionThis question is (sort-of) related to #4706 (comment). I want to startup fastapi with user-supplied command line arguments and also initiate the on_event('startup') function. The arguments p1 and p2 differ depending on user/usage. The error is: How can this be achieved? Thanks Operating SystemWindows Operating System DetailsNo response FastAPI Versionfastapi-0.88.0, starlette-0.22.0 Python Version3.10.7 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
In this case you can just do something like this. app = FastAPI()
@app.get("/item")
def do_get_item(p3):
return get_item()
@app.on_event("startup")
def app_startup():
p1 = sys.argv[0]
p2 = sys.argv[1]
print(p1, p2)
# do_startup_stuff(p1, p2)
@app.on_event("shutdown")
def app_shutdown():
p4 = sys.argv[1]
print(p4)
# do_shutdown_stuff(p4)
if __name__ == "__main__":
uvicorn.run(app)If these require a more complicated configuration usually in fast api this is done by using a settings/config object which you can learn more about here https://fastapi.tiangolo.com/advanced/settings/#create-the-settings-object |
Beta Was this translation helpful? Give feedback.
In this case you can just do something like this.
If these require a more complicated configuration usually in fast api this is done by using a settings/config object which you can learn more about here https://fastapi.tiangolo.com/advanced/settings/#create-the-settings-object