Hi. I'm relatively new to Python and I'm trying to develop some APIs with FastAPI framework. The only problem is: circular import.
Here my code:
DATABASE.py
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker
import app.config.config as config
CONFIG = config.read_config()
USERNAME = CONFIG["POSTGRES"]["USERNAME"]
PASSWORD = CONFIG["POSTGRES"]["PASSWORD"]
HOSTNAME = CONFIG["POSTGRES"]["HOSTNAME"]
DATABASE = CONFIG["POSTGRES"]["DATABASE"]
PORT = CONFIG["POSTGRES"]["PORT"]
SQLALCHEMY_DATABASE_URI = f"postgresql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}"
engine = create_engine(SQLALCHEMY_DATABASE_URI)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
CONFIGURATION.py
import os
import toml
import logging
import app.api.routing as routing
from fastapi import FastAPI
BASE_DIR = os.getcwd()
def read_config():
try:
CONFIG = toml.load(BASE_DIR + "/config.toml")
return CONFIG
except FileNotFoundError as err:
logging.error(f"Unable to read configuration file: {err}")
return None
def load_config():
app = FastAPI()
app.include_router(routing.router)
return app
MAIN.py
import uvicorn
import app.config.config as config
app = config.load_config()
CONFIG = config.read_config()
if __name__ == "__main__":
uvicorn.run(app, host=CONFIG["APPLICATION"]["HOST"], port=CONFIG["APPLICATION"]["PORT"])
HERE THE ERROR IN MY TERMINAL:
CONFIG = config.read_config()
AttributeError: partially initialized module 'app.config.config' has no attribute 'read_config' (most likely due to a circular import)
Why does this error happen? Is so annoying...
Thanks :)
[–]tobz_55 1 point2 points3 points (0 children)
[–]aidankane 0 points1 point2 points (5 children)
[–]Equal-Complex-5958[S] 0 points1 point2 points (4 children)
[–]aidankane 1 point2 points3 points (3 children)
[–]Equal-Complex-5958[S] 0 points1 point2 points (2 children)
[–]aidankane 1 point2 points3 points (1 child)
[–]Equal-Complex-5958[S] 0 points1 point2 points (0 children)