FastAPI: ModuleNotFoundError: No module named 'uvicorn'

Viewed 18465

I will admit I never used gunicorn before. When I run the command gunicorn main:app -k uvicorn.workers.UvicornWorker gives error:

Error: class uri 'uvicorn.workers.UvicornWorker' invalid or not found: 

[Traceback (most recent call last):
  File "/Users/AdnanAhmad/Data/anaconda3/lib/python3.7/site-packages/gunicorn/util.py", line 135, in load_class
    mod = import_module('.'.join(components))
  File "/Users/X/Data/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'uvicorn'
2 Answers

Check if you are calling the correct Gunicorn using which gunicorn (on Linux, or use where on Powerbash from Windows) from the terminal. If you are using a venv it should print a path pointing inside your venv directory.

It happend to me also, because I followed the instruction from the Gunicorn page and installed using sudo apt install gunicorn. It could be a good option for your production container, where you'll probably run the application without a venv, but in developer mode on you machine it will work better if you install gunicorn inside your venv directory using the pip install gunicorn, using the pip from your venv.

Then you can call it with python -m gunicorn main:app -k uvicorn.workers.UvicornWorker

The FastApi docs I had to install uvicorn separately, so

This didn't work:

poetry add "fastapi[uvicorn]"
# you won't see uvicorn in the logs

This worked

poetry add fastapi uvicorn
# you can see in the logs uvicorn is installed
Related