0

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.

7
  • You need to import your models. The classes aren't created, and as a result not registered with SQLAlchemy, until you do. Commented May 8, 2015 at 13:16
  • I tried adding from . import models to the import lists in __init__.py, but now It gave these errors: here I know I imported wrong but how should I import the models? Commented May 8, 2015 at 13:22
  • plus if you look at THIS stack overflow question, the answer did not require importing the models, unless I'm looking wrong? Commented May 8, 2015 at 13:38
  • You have a circular import. __init__ is importing your models, which import db, before db is combined. Define db before the import. Commented May 8, 2015 at 13:48
  • That question already had the models imported so it required a different answer. Commented May 8, 2015 at 13:49

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

There are a few common application layouts. Some require things like this to avoid circular imports. Some don't. The OP's layout falls into the former.
Thanks for your answer. How and when were the models imported in this answer? Because as far as I can see, theirs ended up working fine without having to import after the instantiation of db.
You were right about having to import the Models. I imported them into my main.py with the line from app.models import user
0

This should work, seem you are missing the if statement

from app import create_app

app = create_app()

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

1 Comment

Database is still empty when running.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.