Python Forum

Full Version: Flask and SQLAlchemy question: Database is being created but tables aren't adding
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am trying to make an e-commerce app using Flask and SQLAlchemy. Whenever I create the databases in my program, the database is getting created, but without the tables from models.py.

Whenever I do

Quote:>>> from app import app, db
>>> app.app_context().push()
>>> db.create_all()

The database is created, but when I check it there are no tables in the database. Here are the relevant files:

models.py

from app import db
from flask_login import UserMixin

class User(db.Model, UserMixin):
    id = db.Column(db.Integer(), primary_key=True)
    username = db.Column(db.String(20), nullable=False, unique=True)
    email = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)
app.py

from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from forms import RegisterForm
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SECRET_KEY'] = 'secretly'
Bootstrap(app)
db = SQLAlchemy(app)


@app.route('/')
def homepage():
    return render_template('index.html')

@app.route('/login', methods=['POST','GET'])
def login_page():
    pass

@app.route('/register', methods=['POST','GET'])
def register_page():
    form = RegisterForm()
    return render_template('register.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)
When I put the User model in app.py rather than in models.py, I notice that the database is created.

I have had a lot of trouble with using databases with Flask in the past, so any advice here would be much appreciated. Thank you!
Flask-SQLAlchemy has change how do make database from previous versions,you are using thre old way which will not work anymore.
Like this.
db = SQLAlchemy()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['SECRET_KEY'] = 'secretly'
Bootstrap(app)
db.init_app(app)

from models import User

def create_db():
    with app.app_context():
        db.create_all()
    print('Created Database!')
So now in same folder from command line,also in same folder as app.py and models.py.
G:\all_flask\2023\cr_db
λ python
Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from app import create_db
>>> create_db()
Created Database!
So look at doc eg Create the Tables
See now that it requires an application contex,then need do this as i done in code over.
with app.app_context():
    db.create_all()
There are several reasons why tables may not be adding Link removed to a database:
1. Incorrect SQL syntax: Ensure that the SQL statements used to create tables are written correctly and follow the syntax of the database management system being used.
2. Missing privileges: The user may not have sufficient privileges to create tables in the database. Check the user's privileges and grant the necessary privileges if required.
3. Connectivity issues: Ensure that the database management system is running and that there are no connectivity issues that are preventing the tables from being added.
4. Database file corruption: In some cases, the database file may become corrupted, causing tables to fail to be added. Check the database file for corruption and restore a backup if necessary.
5. Table name conflict: Make sure that the table names are unique and do not conflict with any existing tables in the database.
Hi,

Thanks for all the replies. It appears like I got it working. For some reason, it wasn't showing when the table was empty, but once I started adding content to the tables, it worked just fine?

I will try using create_db next time to see if it works.