Warm tip: This article is reproduced from serverfault.com, please click

Creating tables in Flask using SQLAlchemy does not work

发布于 2020-11-28 11:22:12

I try to write a web-application with Python Flask and SQLAlchemy in PyCharm. I linked my project to a PostgreSQL-Database in Heroku and am now trying to create the tables I coded. My main site argos.py looks like this:

from flask import Flask, render_template, redirect, url_for, flash
from flask_login import LoginManager, login_user, current_user, logout_user
from models import *
from forms import *


app = Flask(__name__)


app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.secret_key = 'replace later'

app.config['SQLALCHEMY_DATABASE_URI']='postgres://[my heroku link]'
db = SQLAlchemy(app)


@app.route('/')
def hello_world():
    return render_template('start.html')
[...]

My models.py looks like this:

from flask_login import UserMixin
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import JSON

db = SQLAlchemy()


own = db.Table('own',
    db.Column('user_id', db.Integer, db.ForeignKey('user.user_id')),
    db.Column('text_id', db.Integer, db.ForeignKey('text.text_id'))
)


class User(UserMixin, db.Model):

    __tablename__ = "user"

    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    email = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(50), nullable=False)
    owning = db.relationship('Text', secondary=own, backref=db.backref('owners', lazy='dynamic'))


class Text(db.Model):

    __tablename__ = "text"

    text_id = db.Column(db.Integer, primary_key=True)
    text_data = db.Column(JSON, nullable=False)

I try to create the tables in the python shell of PyCharm by running:

from argos import db
db.create_all()

The import seems to work nicely, but when I enter the create-command, nothing happens, not even an ErrorMessage. I tried the same thing from my Windows CMD terminal and also with only one table to create (the text-table with only two columns) but still nothing happens. I am sure I am making a beginners mistake and I am sorry for that, but I didn't manage to solve that problem for several hours now and it totally drives me crazy.

Thank you very much in advance.

Questioner
Pastor Nolte
Viewed
11
van 2020-11-29 22:17:09

Keep the models.py as it is, but change the argos.py as per below:

# ...
from models import *  # @NOTE: <- this also includes 'db'

# ...
app.config['SQLALCHEMY_DATABASE_URI']='postgres://[my heroku link]'

# now "link" the Models (db) to the App (app) [not create a fresh db]
db.init_app(app)  # <- instead of: db = SQLAlchemy(app)

# ...