I am new to FastAPI and I've been having this problem with importing my other files.
I get the error:
from . import schemas
ImportError: attempted relative import with no known parent package
For context, the file I am importing from is a Folder called Blog. I saw certain StackOverflow answers saying that instead of from . import schemas
I should write from Blog import schemas
. And even though their solution is right and I don't get any errors while running the python program, When I try running FastAPI using uvicorn, I get this error and my localhost page doesn't load.
File "./main.py", line 2, in <module>
from Blog import schemas
ModuleNotFoundError: No module named 'Blog'
The file structure looks like this:
The code to the main file looks like this:
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)
The SwaggerUI is not loading either.
Any help would be greatly appreciated! :)
Since your schemas.py
and models.py
files are in the same directory as your main.py
file, you should import those two modules as follows, instead of using from Blog import schemas, models
:
import schemas, models
For more details and examples please have a look at this answer, as well as this answer and this answer.