A
A
Antosha Styazhkin2021-02-06 15:58:02
Flask
Antosha Styazhkin, 2021-02-06 15:58:02

Why is the database not being created in Flask-SQLAlchemy?

My project looks like this:

web-app
  app
    __init_.py
    config.py
    models.py


models.py
from app import db


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(35), nullable=False)
    email = db.Column(db.String(256), unique=True, nullable=False)
    password = db.Column(db.String(256), nullable=False)


__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from app.components import (
    account,
    dashboard,
    error
)

app = Flask(__name__)
app.config.from_pyfile('config.py')

db = SQLAlchemy(app)

app.register_blueprint(account)
app.register_blueprint(dashboard)
app.register_blueprint(error)


and config.py
from os import environ

SECRET_KEY = environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = environ.get('SQLALCHEMY_DATABASE_URI')
SQLALCHEMY_TRACK_MODIFICATIONS = environ.get('SQLALCHEMY_TRACK_MODIFICATIONS')


Here's the problem:
For some reason, I'm getting an empty database.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Antosha Styazhkin, 2021-02-06
@desulaid

Solved the problem. The bottom line is that before creating a database, you must first import the tables BEFORE calling create_all ().
I work in PyCharm and here is my (possibly ugly) solution. Open the Python Console and import the tables first, then everything else.

from app.models import *
from app import app, db
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db.create_all()

I write app.config['SQLALCHEMY_DATABASE_URI'] manually because env variables are not picked up.

W
Wispik, 2021-02-06
@Wispik

Because you don't create a database anywhere in your code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question