I have a simple Uvicorn application (built with FastAPI). In development, uvicorn server:app --reload
. The --reload
paramter means two threads will be started, one with the server, one to monitor file changes—when a file change is detected, the thread with the server is restarted.
Nothing special thus far. This is common in Flask, Django, and other dev servers as well. The catch is, I want to open a tunnel using pyngrok
when I start the dev server, and I want that tunnel to be as long lived as the parent of these two threads. That is to say, when a file change is detected and the dev server is restarted, I do not want the tunnel to be restarted (since with ngrok
this would cause a new public URL to be generated and break existing connections).
With Flask and Django this is relatively easy to accomplish. For example, with Flask I simply do os.environ.get("WERKZEUG_RUN_MAIN") != "true"
, with Django I similarly evaluate the RUN_MAIN
environment variable, and in either case I only instantiate the tunnel when this these are set to true
. I can't find a similar variable to use with Uvicorn. Can anyone help out here?
In FastAPI applications running with Uvicorn, you can check if the
--reload
option is enabled by examining thesys.argv
list. Thesys.argv
list contains the command-line arguments passed to the script, and when the--reload
option is used, it will be present in the list.You can use the following code to determine if the
--reload
option is enabled: