Python Forum
Flask and SQLAlchemy question: Database is being created but tables aren't adding
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Flask and SQLAlchemy question: Database is being created but tables aren't adding
#1
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!
Reply
#2
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()
Reply
#3
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.
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Webscrape using RPi and SQlite database, always write the last value in database Armond 0 1,544 Jul-19-2023, 09:11 PM
Last Post: Armond
  Flask: sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) database is locked pythonpaul32 1 5,006 Apr-04-2023, 07:44 AM
Last Post: Larz60+
  Flask error sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint pythonpaul32 2 10,258 Feb-21-2023, 03:13 AM
Last Post: noisefloor
  Flask/non-flask database sharing MorganSamage 2 2,749 Feb-03-2023, 12:05 PM
Last Post: MorganSamage
  Error updating one to many relationship in Flask/ SQLAlchemy atindra 0 4,575 Apr-15-2021, 10:29 PM
Last Post: atindra
  Flask migrate sqlalchemy not found TomasAm 2 5,541 Dec-01-2020, 10:04 AM
Last Post: TomasAm
  python 3.7 on windows using flask and flask-sqlalchemy. Alpy 2 5,678 Aug-12-2020, 07:24 PM
Last Post: Alpy
  Flask export/upload database table in cvs/xlsx format steve87bg 4 11,557 Jun-19-2020, 01:46 PM
Last Post: steve87bg
  Flask - adding new page affects all other pages CMR 15 10,107 Mar-28-2020, 04:13 PM
Last Post: CMR
  Flask-Sqlalchemy count products in specific category imawesome 2 47,662 Mar-12-2020, 08:14 PM
Last Post: imawesome

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020