3

I'm currently starting up the server with the following Uvicorn command:

main:app --host 0.0.0.0 --port 8003 --access-log

And I would like to add an extra argument --foo such that it works as argparse's "store_true" action so I can optionally execute a function during my startup.

With Python, using argparse I can achieve this executing the command main.py --migrate:

parser = argparse.ArgumentParser(description="Startup")
parser.add_argument("--foo", dest="run_foo", action="store_true")
args = parser.parse_args()

@app.on_event("startup")
async def startup_event():
    if args.run_foo:
        foo()

Where app is my FastAPI instance. However, I get an uvicorn: error: unrecognized arguments: main:app --host 0.0.0.0 --port 8003 --access-log when I try to execute it using Uvicorn. Is there a way to do this?

DDCA567
  • 31
  • 4
  • Can you please explain more what you are asking? It sounds like you want to extend the Uvicorn CLI by using argparse...? Is that right? – Alexander Nov 29 '22 at 18:11
  • @Alexander yes and no. I posted my Python solution which uses argparse, but I don't know if something similar could be done in Uvicorn. So yes, I imagine this would be considered expanding the CLI. – DDCA567 Nov 29 '22 at 21:59

1 Answers1

1

You can do a trick by calling your service in python and using argparse as:

import uvicorn
from fastapi import FastAPI
import argparse
app: FastAPI = FastAPI()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--foo')
    args = parser.parse_args()
    foo(args.foo)
    #run server
    uvicorn.run(app)

Then run you server using normal python command and pass the argument:

python main.py --foo foo
user3322581
  • 155
  • 6