问题描述
我有一个与pycharm中带有uvicorn的FastAPI有关的问题.我的项目具有以下结构:
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
首先,我使用以下路径: D:\ Learnings \ apis 并运行以下代码:uvicorn main:app --reload然后它给出了错误:
First I was using following path : D:\Learnings\apis and ran following code : uvicorn main:app --reloadthen 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".
但是,在阅读了,我已将路径更改为 D:\ Learnings \ apis \ modeservice ,但上面的错误消失了,但现在它开始引发另一个错误: ModuleNotFoundError:没有名为"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'
这是我的main.py和config.py代码文件:
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)
这是config.py-
And here is config.py--
API_CONFIG = {
"origin_local_ip": "http://127.0.0.1:3000",
"origin_local_url": "http://localhost:3000"
}
该项目基于React + Mongo + python(用于连接mongodb的pymongo)构建.
This project is being built on React+Mongo+python (pymongo for connecting mongodb).
谢谢.
推荐答案
您的应用程序中的问题是您的模块组织,首先我尝试了您的文件夹结构,发现与您的错误相同,我对其进行了一些调试,发现错误在于导入配置,因此我更深入地了解了为什么Python无法导入您的配置,
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,
我在最上面的文件夹中创建了一个脚本,以找出原因.还在打印行中的 config.py
和 modelservice.main.py
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
这是结构
apis
├── config.py
└── modelservice
└── main.py
我在名为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
它返回:
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.
这篇关于FastAPI说缺少文件夹名称作为模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!