FastAPI: " ImportError: attempted relative import with no known parent package"

FastAPI: " ImportError: attempted relative import with no known parent package"

我是 FastAPI 的新手,导入其他文件时遇到了这个问题。

我收到错误:‍‍‍‍

from . import schemas
ImportError: attempted relative import with no known parent package

对于上下文,我从中导入的文件是一个名为 Blog 的文件夹。我看到某些 Whosebug 答案说我应该写 from Blog import schemas 而不是 from . import schemas。即使他们的解决方案是正确的并且在 运行 python 程序时我没有收到任何错误,当我尝试使用 uvicorn 运行 FastAPI 时,我收到此错误并且我的本地主机页面没有加载。

  File "./main.py", line 2, in <module>
from Blog import schemas
ModuleNotFoundError: No module named 'Blog'

文件结构如下所示:

主文件的代码如下所示:

from fastapi import FastAPI
from Blog import schemas, models
from database import engine

app = FastAPI()

models.Base.metadata.create_all(engine)


@app.post('/blog')
def create(request: schemas.Blog):
    return request

schemas.py

from pydantic import BaseModel


class Blog(BaseModel):
    title: str
    body: str

database.py

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHAMY_DATABASE_URL = 'sqlite:///./blog.db'

engine = create_engine(SQLALCHAMY_DATABASE_URL, connect_args={"check_same_thread": False})

SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)

Base = declarative_base()

models.py

from sqlalchemy import *
from database import Base


class Blog(Base):
    __tablename__ = 'blogs'
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String)
    body = Column(String)

SwaggerUI 也未加载。

如有任何帮助,我们将不胜感激! :)

由于您的 schemas.py 和 models.py 文件与主文件位于同一目录中,因此您应该按如下方式导入这两个模块:

#from Blog import schemas, models
import schemas, models