vendredi 8 mai 2015

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.

Aucun commentaire:

Enregistrer un commentaire