L. Quastana
L. Quastana

Reputation: 1336

Create all tables with Flask-SQLAlchemy

I have some difficulties with the library lask-sqlalchemy, I tried to create my database with the code bellow, i have no error but no table created.

_init.py

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

app.config.from_json("C:/Users/lquastana/PycharmProjects/flask_demo/conf/api-config.json")
app.app_context().push()

db.py

from flask_sqlalchemy import SQLAlchemy
from api_lab import app
db = SQLAlchemy(app)

member.py

from api_lab.models.db import db

class Member(db.Model):
    __table_args__ = {"schema": "public"}
    id = db.Column(db.BigInteger,
                   primary_key=True,
                   autoincrement=True)
    id_company = db.Column(db.BigInteger,
                       db.ForeignKey("compagny.id"),
                       index=True,
                       nullable=False)
    nom = db.Column(db.String(80), unique=True, nullable=False)
    age = db.Column(db.Integer, unique=True, nullable=False)

    def __repr__(self):
        return '<Member %r>' % self.nom

run_api.py

from api_lab import app
from api_lab.models.db import db

def main():
    host = app.config["ENV"]["HOST"]
    port = app.config["ENV"]["PORT"]
    debug = app.config["ENV"]["DEBUG"]
    app.run(host=host, port=port, debug= debug)


if __name__ == '__main__':
    db.create_all()
    #main()

Upvotes: 0

Views: 149

Answers (1)

Karl
Karl

Reputation: 531

You should put all initialization related logic into init.py Use SQLAlchemy to setup a db connection with your app.config

init.py

from api_lab import app
from api_lab.models.db import db
from flask_sqlalchemy import SQLAlchemy

app.config.from_json("C:/Users/lquastana/PycharmProjects/flask_demo/conf/api-config.json")
    app.app_context().push()

    db = SQLAlchemy(app)
    # initialize the DB
    db.create_all()

Upvotes: 2

Related Questions