I'm trying to create 3 tables on my postgreSQL database using Flask. I've defined the models, configured the database to start when Flask starts and defined the URI for the connection. Apparently everything works out fine and the connection is established, but the tables never show up on the db. I receive no errors whatsoever.
Here is my code.
app.py:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from storage import database
from dotenv import load_dotenv
import os
load_dotenv() # unused at the moment
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://postgres:password@localhost/cosmo'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
database.init_db(app)
@app.route('/')
def home():
return 'O servidor de automação de respostas está online.'
return app
if __name__ == '__main__':
app = create_app()
app.run(debug=True)
and database.py:
from flask_sqlalchemy import SQLAlchemy
from storage.models import *
db = SQLAlchemy()
def init_db(app):
""" Start the database with flask application """
db.init_app(app)
with app.app_context():
db.create_all() # creates all the tables from the models
My models:
from database import db
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=True)
phone = db.Column(db.String(15), unique=True, nullable=False)
created_at = db.Column(db.Datetime, nullable=False, default=db.func.now())
class Message(db.Model):
__tablename__ = 'messages'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
content = db.Column(db.Text, nullable=False)
directoin = db.Column(db.String(10), nullable=False)
created_at = db.Column(db.Datetime, nullable=False, default=db.func.now())
class InteractionLogs(db.Model):
__tablename__ = 'interaction_logs'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
session_id = db.Column(db.String(50), nullable=False, unique=True)
log_content = db.Column(db.Text, nullable=False)
created_at = db.Column(db.Datetime, nullable=False, default=db.func.now())
At first I was trying to create the tables without using the default user of postgreSQL(postgres). Didn't work. Then, I tried using the default(in case of permission issues), also did not work. Asked chatgpt for help and it's now on a loop of suggestions and I can't figure this out for the life of me lmao
First question here, and I'm also a noob at programming, so my bad if this is obvious...
db = SQLAlchemy()should only be executed once. Modules that requiredbshould import it from the module where it is executed.