db.create_all() not creating tables in Flask-SQLAclchemy

Issue

I am trying to create a database table for a user class model using Flask-SQLAclchemy and Postgres.

My model class.

from app import db
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(70), index=True, nullable=False)
    email = db.Column(db.String(70), index=True, unique=True, nullable=False)
    password = db.Column(db.String(128))

My app initialisation.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('app.instance.config.DevelopmentConfig')
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:RandomPass@localhost/BrightEventDb'
SQLALCHEMY_TRACK_MODIFICATIONS = True
db = SQLAlchemy(app)

The following info is logged.

2018-01-06 11:53:09,978 INFO sqlalchemy.engine.base.Engine select version()
2018-01-06 11:53:09,979 INFO sqlalchemy.engine.base.Engine {}
2018-01-06 11:53:09,982 INFO sqlalchemy.engine.base.Engine select current_schema()
2018-01-06 11:53:09,982 INFO sqlalchemy.engine.base.Engine {}
2018-01-06 11:53:09,984 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2018-01-06 11:53:09,985 INFO sqlalchemy.engine.base.Engine {}
2018-01-06 11:53:09,986 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2018-01-06 11:53:09,987 INFO sqlalchemy.engine.base.Engine {}
2018-01-06 11:53:09,990 INFO sqlalchemy.engine.base.Engine show standard_conforming_strings
2018-01-06 11:53:09,991 INFO sqlalchemy.engine.base.Engine {}

Solution

If you were following the flask quick start minimal application, the command worked by default since the User class was in the same place as the db instance. In your case, however, you will have to import the User class as mentioned in the comments from models import User into your app initialization

Answered By – Esir Kings

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published