FastAPI says missing folder name as module

Viewed 9867

I have a question related to FastAPI with uvicorn in pycharm. My project is having following structure:

LearningPy <folder name> 
 |  
 |-- apis <folder name>  
 -----|--modelservice <folder name>  
 ---------|--dataprovider.py  
 ---------|--main.py  
 ---------|--persondetails.py  
 -----|--config.py 

First I was using following path : D:\Learnings\apis and ran following code : uvicorn main:app --reload then it was giving error :

Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Started reloader process [23445]
Error loading ASGI app. Could not import module "apis".

However, after reading suggestion from here, I have changed the path to D:\Learnings\apis\modeservice and above error gone but now it started throwing a different error : ModuleNotFoundError: No module named 'apis'

Here are my main.py and config.py code files :

main.py --

import uvicorn
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from datetime import datetime

from apis import config
from apis.modelservice import dataprovider

app = FastAPI(debug=True)
def get_application() -> FastAPI:
    application = FastAPI(title="PersonProfile", description="Learning Python CRUD",version="0.1.0")
    origins = [
        config.API_CONFIG["origin_local_ip"],
        config.API_CONFIG["origin_local_url"]
    ]
    application.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    #application.include_router(processA.router)
    return application

app = get_application()

@app.get("/")
def read_root():
    return {"main": "API Server " + datetime.now().strftime("%Y%m%d %H:%M:%S")}

@app.get("/dbcheck")
def read_root():
    try:
        dataprovider.get_db().get_collection("Person")
    except Exception as e:
        return {"failed":e}
    else:
        return { "connected":True}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)

And here is config.py--

API_CONFIG = {
    "origin_local_ip": "http://127.0.0.1:3000",
    "origin_local_url": "http://localhost:3000"
}
 

This project is being built on React+Mongo+python (pymongo for connecting mongodb).

Thanks in advance.

2 Answers

The problem in your application is your module organization,firstly i tried your folder structring i get the same errors as yours, i debugged it a little bit, i found the error was on importing config so i dived more deeply to understand why Python can not import your config,

I created a script on the top folder to find out why. Also added in print line in the config.py and modelservice.main.py

print('__file__={0:<35} | __name__={1:<20} | __package__={2<20}'.format(__file__,__name__,str(__package__)))
import apis.config
import apis.modelservice.main

This was the structure

apis
├── config.py
└── modelservice
    └── main.py

I run the script in the top folder script named main.py, It ended up with this result:

 __file__=main.py | __name__=__main__ | __package__=None                
__file__=/home/yagiz/Desktop/test/apis/config.py | __name__=apis.config | package__=apis                
apis.config
__file__=/home/yagiz/Desktop/test/apis/modelservice/main.py | __name__=apis.modelservice.main | __package__=apis.modelservice  

It felt strange because i should be able to relative import, but when i tried to import that what

from .. import config 

it returned:

  File "./main.py", line 8, in <module>
    from .. import config
ImportError: attempted relative import with no known parent package

Just for the testing it out i tried this structure, also i used absolute import import config:

apis/
├── modelservice
    ├── config.py
    ├── main.py

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [14155] using statreload
__file__=./main.py  | __name__=main | __package__=                    
__file__=./config.py  | __name__=config   | __package__= config
INFO:     Started server process [14157]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Everything worked fine like that, so the problem is with your module organization and how you importing things so take a look at them again.

Added to what Yagizcan answered above, if anyone still getting module import error in pycharm then change the sources root to the code folder from File menu.

LearningPy <folder name> 
 |  
 |-- apis <folder name>  
 -----|--modelservice <folder name>  
 ---------|--dataprovider.py  
 ---------|--persondetails.py  
------|--main.py    
------|--config.py  

Here I have moved the main.py outside of modelservice folder. since main.py will be running as api. Then, to run the code I have added following code uvicorn path to apisfolder.main:app --reload. And now it ran without any problem.

Related