I'm using fastAPI and uvicorn for my python app. I found out a tricky phenomenon using Uvicorn, which seems the way launching python code creating race condition.
My first trial is like below
# main.py
import uvicorn
app = App()
uvicorn.run(
"main:app",
host="127.0.0.1", port=8080, log_level="debug", reload="true")
After launch main.py with python main.py, I experienced
ERROR: [Errno 48] Address already in useerror.
I tried to find out any port or address bind with 127.0.0.1:8080 but there are no processes on my Mac.
However, my second trial like below:
import uvicorn
app = App()
if __name__ == "__main__":
uvicorn.run(
"main:app",
host="127.0.0.1", port=8080, log_level="debug", reload="true")
AFAIK, matching __name__ value means to check this module directly launched or just imported by other python module.
What does exactly happened behind this?
Address already in useerror.uvicornspecifically, but it looks like the"main:app"string you pass it means it is going to import yourmain.pyscript in order to access yourappobject. In that case you don't wantuvicorn.runto trigger again when that function imports your script. It doesn't seem like a race condition to me.main:appmodule for reloading and when without execution protection withif, python interpreter tried to execute uvicorn server(process) twice with same address. Thanks for advices:) @polka @kaya3 @electromeow