For example, let's take simple FastAPI app:
import uvicorn
from fastapi import FastAPI
print("calling main!")
app = FastAPI()
@app.get('/test', status_code=200)
async def test():
return True
if __name__ == "__main__":
uvicorn.run("main:app", use_colors=True, workers=2)
If we run it, we get following output:
calling main!
INFO: Uvicorn running on http://0.0.0.0:8020 (Press CTRL+C to quit)
INFO: Started parent process [143621]
calling main!
calling main!
INFO: Started server process [143832]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Started server process [143829]
INFO: Waiting for application startup.
INFO: Application startup complete.
calling main!
calling main!
So, for app with two workers (parent + 2 server process) we have 5 (!) execution of main. Why? Maybe I'm missing something simple, but it confuses me. Thanks in advance for answers!
Based on this answer about miltiprocessing.
Uvicorn start new processes to create workers. It will import parent, that gives you 1 "calling main!" for each worker. Than the worker will start new server, which gives you 1 more "calling main!" for each. worker.
You can try
print('worker pid: {}, module name: {}'.format(os.getpid(), __name__))
instead of your print to check processes.