I am trying to build a basic Flask project. Here is the app.py file.
JavaScript
x
15
15
1
from flask import Flask
2
from flask_sqlalchemy import SQLAlchemy
3
from flask_login import LoginManager
4
5
6
app = Flask(__name__)
7
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///my_database.db'
8
9
db = SQLAlchemy(app)
10
login = LoginManager(app)
11
12
login.login_view = 'login'
13
14
import routes, models
15
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:
JavaScript
1
21
21
1
project_folder
2
|---------- app.py
3
|---------- config.py
4
|---------- .env
5
|---------- requirements.txt
6
|---------- .flaskenv
7
|---------- app/
8
|------ routes.py
9
|------ models.py
10
|------ __init__.py
11
|------ forms.py
12
|------ templates/
13
|-------- base.html
14
|-------- index.html
15
|-------- test.html
16
|------ static/
17
|-------css/
18
|------- styles.css
19
|-------js/
20
|------- app.js
21
From __init__.py
, you will create an instance of your flask app:
JavaScript
1
13
13
1
from flask import Flask
2
from flask_sqlalchemy import SQLAlchemy
3
from flask_login import LoginManager
4
5
app = Flask(__name__)
6
7
db = SQLAlchemy(app)
8
login = LoginManager(app)
9
login.login_view = 'login'
10
11
12
from app import routes, models
13
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:
JavaScript
1
2
1
from app import app
2
Your configurations will go the config.py
file:
JavaScript
1
6
1
import os
2
3
class Config(object):
4
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
5
# ...
6