I am trying to build a basic Flask project. Here is the app.py file.
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///my_database.db' db = SQLAlchemy(app) login = LoginManager(app) login.login_view = 'login' import routes, models
PyCharm is telling me that route, and models are unused imports. They are located in the same root directory together. I’m not sure how to get these imported another way without having a circular import error.
Advertisement
Answer
An ideal way would be to use this structure where each module is separately handled:
project_folder |---------- app.py |---------- config.py |---------- .env |---------- requirements.txt |---------- .flaskenv |---------- app/ |------ routes.py |------ models.py |------ __init__.py |------ forms.py |------ templates/ |-------- base.html |-------- index.html |-------- test.html |------ static/ |-------css/ |------- styles.css |-------js/ |------- app.js
From __init__.py
, you will create an instance of your flask app:
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager app = Flask(__name__) db = SQLAlchemy(app) login = LoginManager(app) login.login_view = 'login' from app import routes, models
Importing routes
and models
(and any other module you might have) at the bottom of __init__.py
helps avoid circular dependencies issue.
The app.py
is left as an entry point to your application:
from app import app
Your configurations will go the config.py
file:
import os class Config(object): SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL") # ...