k4kuz0
k4kuz0

Reputation: 1045

Database created empty when models are in a separate file?

I am reading a book about flask development, and I'm pretty new to python generally.

File layout:

Project
|
|-- App
|   |-- __init__.py
|   |-- models.py
|
| main.py

Code inside __init__.py:

from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.sqlalchemy import SQLAlchemy
import os
from config import options

basedir = os.path.abspath(os.path.dirname(__file__))
bootstrap = Bootstrap()
db = SQLAlchemy()

def create_app():   
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] =\
        'sqlite:///' + os.path.join(basedir, 'database_test.sqlite')

    bootstrap.init_app(app)
    db.init_app(app)

    with app.app_context():
            db.create_all()
            print("DB created")

    return(app)

I have been researching other people's issues on the site, mostly here where I found to use the with app.app_context(), and to instantiate the db without using app as part of the constructor.

Here is my models.py file:

from . import db


class User(db.Model):
    __tablename__ = 'Users'
    account_id = db.Column(db.Integer, primary_key=True)
    personaname = db.Column(db.String(50), unique=False)
    steamid = db.Column(db.String(64))
    avatar = db.Column(db.String(200))
    profileurl = db.Column(db.String(128))
    is_personaname_real = db.Column(db.Integer)

    def __repr__(self):
        return '<User {0}>'.format(self.personaname)

I then rune the code from main.py which is just:

from app import create_app

app = create_app()

If I move the User class into the __init__.py function, everything is created fine. However, when the User class is inside it's own file, the database is created empty. I have tried using other ways of importing, maybe something like From app.__init__.py Import db, but that didn't work either.

Upvotes: 0

Views: 951

Answers (2)

mhawke
mhawke

Reputation: 87084

Since defining your model directly in __init__.py works, it follows that you need to import your model(s) into __init__.py.

You can add an import in __init__.py after you create an SQLAlchemy object:

db = SQLAlchemy()
from .models import User

This works, but it feels horribly wrong and dirty to me. I don't know Flask that well, but this answer suggests that this is normal for Flask: https://stackoverflow.com/a/19008403/21945

Upvotes: 2

nadermx
nadermx

Reputation: 2776

This should work, seem you are missing the if statement

from app import create_app

app = create_app()

if __name__ == "__main__":
    app.run()

Upvotes: 0

Related Questions