Troubleshooting · By Rivtor · Updated
Fix Uvicorn Could Not Import Module in a deployed API
Match Uvicorn’s module:attribute target to the files importable from the service’s working directory. Check the complete traceback for a nested dependency failure, then verify package installation and filename case in a clean runtime.
See the Rivtor deployment workflow →
Translate the target into a file and object
The target main:app means import the Python module main and obtain its app attribute. It is not a filesystem path such as main.py:app. A file under api/main.py can be imported differently depending on whether the working directory is the repository root or api.
| Runtime working directory | Example target |
|---|---|
| Directory containing main.py | main:app |
| Root containing an importable api package | api.main:app |
| Application factory module | Target and factory flag matching that project |
These are illustrative layouts. Inspect the real package structure and do not change module names blindly.
Read beyond the final error line
A module can exist but fail while importing one of its dependencies. Look for the first meaningful exception: missing driver, invalid configuration, circular import or syntax error. Installing an unrelated package named after the target file is not a fix.
Check whether Linux filename case differs from the local filesystem. MyApp and myapp can refer to different module names on the deployment host. Confirm source files and required package metadata were actually included in the build context.
Reproduce in the intended runtime
From the selected service directory, a small import check can locate the problem:
python -c "import main; print(hasattr(main, 'app'))"
Use the actual module name. Importing a module can execute its top-level code, so use a disposable environment without production side effects. A successful result establishes the import and attribute, not server health or database correctness.
Repair configuration at its source
Update the production command or service root when that is the mismatch. Install runtime dependencies from the committed manifest and lock workflow. Avoid a global PYTHONPATH workaround that hides an incorrectly packaged project.
On Rivtor, inspect service overrides and the detected startup command. Restart the corrected service, verify its public health route and exercise a synthetic API operation. If imports succeed but requests fail, continue with the actual runtime error rather than repeating the import diagnosis.