user11350030
user11350030

Reputation: 41

Flask-SQLAlchemy doesn't create table

I am trying to use PostgreSQL with Flask-SQLAlchemy. I made a database named data_collector using pgAdmin4. When I try to create a table it's not getting created. I think the connection to the database is not getting established.

I am trying to run it from cmd as:

from app import db
db.create_all()
from flask import Flask, render_template,request
from flask_sqlalchemy import SQLAlchemy

app=Flask(__name__)
app.config['SQLALCHEMY DATABASE_URI'] = 'postgresql://postgres:postgresql@localhost/data_collector'

db=SQLAlchemy(app)

class Data(db.Model):
    __tablename__="data"
    id=db.Column(db.Integer,primary_key=True)
    email_=db.Column(db.String(120),unique=True)
    height_=db.Column(db.Integer)

    def __init__(self,email_,height_):
        self.email_=email_
        self.height_=height_

db.create_all()

Upvotes: 1

Views: 2541

Answers (2)

Vaibhav Goyal
Vaibhav Goyal

Reputation: 1972

Finally got the solution after alot of Googling.

You must import all the models before calling db.create_all() function like this,

def create_db():

from src import models

db.create_all()
db.session.commit()

I have all my models in single file but if you have different files, make sure to import them all.

Upvotes: 0

AVX-42
AVX-42

Reputation: 775

You didn't commit to the database after creating the tables.
You can do that by:

with app.app_context():
    db.create_all()
    db.session.commit()

Do something like this.

from flask_sqlalchemy import SQLAlchemy
from flask import Flask


app = Flask(__name__)
db = SQLAlchemy(app)

# ---snip---

with app.app_context():
    db.create_all()
    db.session.commit()    # <- Here commit changes to database


@app.route("/")
def index():
    return "Hello, World!"

This should solve your problem.

If you want to reset(delete) your database then:

with app.app_context():
    db.drop_all()
    db.session.commit()

Nothing is written or deleted or updated in database unless you commit using
db.session.commit()

If you want to revert the changes before comitting use: db.session.rollback()

Upvotes: 1

Related Questions