how to run fastapi project in debug mode auto reload in vscode

Viewed 11417

Started with fastapi python.

this is how I am string my server

class Server:
    def __init__(self):
        self.app = FastAPI()

    def runServer(self, host: str, port: int,is_dev:bool):
        uvicorn.run(self.app, host=host, port=port,debug=is_dev)


if __name__ == "__main__":
    server = Server()
    # read the environment variables
    host: str = os.environ['host']
    port: int = int(os.environ['port'])
    is_dev: bool = bool(os.environ['dev'])

    server.runServer(host, port, is_dev)

this ups the server but not running in auto reload mode if i make any changes.

even I tried

uvicorn.run(self.app, host=host, port=port, reload=is_dev)

reload is i guess not an option, thus causing the server to break.

i tried passing --reload args in launch.json even but still not working

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: FastAPI",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/main.py",
            "jinja": true,
            "args": ["--reload"],
            "env": {
                "host": "127.0.0.1",
                "port": "5555",
                "dev": "true"
            }
        }
    ]
}

any idea? am i missing something?

1 Answers

uvicorn will start in the reload mode only if the app argument is a string in the format <module>:<app_instance> and reload or debug argument are true. Like this:

if __name__ == "__main__":
    uvicorn.run("example:app", host="127.0.0.1", port=5000, reload=True)

Excerpt from the documentation:

Note that the application instance itself can be passed instead of the app import string.

uvicorn.run(app, host="127.0.0.1", port=5000, log_level="info")

However, this style only works if you are not using multiprocessing (workers=NUM) or reloading (reload=True), so we recommend using the import string style.

Related