I am VERY new to coding and am trying to set up a Flask App with a SQLAlchemy Database that uses Twilio to schedule daily text messages at 5 PM. I am stuck on circular imports and scheduled tasks not working properly when I try to run them in my main.py file or in my init.py file.
I am too junior to know really what is going on, but I have a feeling that it is related to this article:
Circular import of db reference using Flask-SQLAlchemy and Blueprints
My Directory so far is:
website
__init__.py
main.py
auth.py
keys.py
models.py
views.py
static
#Java code here
templates
#many html templates here
Here is my main.py file:
if __name__ == '__main__':
app = create_app()
app.run(debug=True)
Here is my models.db file:
from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func
class User(db.Model, UserMixin):
# Defining class attributes/columns
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(150), unique=True)
password = db.Column(db.String(150))
first_name = db.Column(db.String(150))
phone_number = db.Column(db.String(20))
gratitude_text_opt_in_status = db.Column(db.Boolean)
Here is my init.py file:
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
from flask import Flask
# create SQLAlchemy object
db = SQLAlchemy()
# set database name
DB_NAME = "database.db"
# define function to create database
def create_database(app):
# if database file does not exist
if not path.exists('website/' + DB_NAME):
# create all database tables with Flask app instance
db.create_all(app=app)
# print message to indicate database creation
print('Created Database!')
# define function to create Flask application
def create_app():
# create Flask app instance with current module name
app = Flask(__name__)
# set secret key for app
app.config['SECRET_KEY'] = #SECRET KEY#
# set URI for database
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
# initialize SQLAlchemy object with Flask app instance
db.init_app(app)
# import 'views' blueprint module
from .views import views
# import 'auth' blueprint module
from .auth import auth``your text``
# register 'views' blueprint with app instance
app.register_blueprint(views, url_prefix='/')
# register 'auth' blueprint with app instance
app.register_blueprint(auth, url_prefix='/')
# import User models
from .models import User
# create all database tables
with app.app_context():
db.create_all()
# create LoginManager object
login_manager = LoginManager()
# set login view for app
login_manager.login_view = 'auth.login'
# initialize LoginManager object with Flask app instance
login_manager.init_app(app)
# define function to load user from User model by ID
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
return app