Jeffrey Tian
Jeffrey Tian

Reputation: 43

Flask initialize database with values

I have a simple question. When I run my flask app, I want to directly add an initial value to the database, like so:

if __name__ == '__main__':
    db.init_app(app)
    with app.app_context():
        db.create_all()

    user = UserModel.find_by_name('user')
    if not user:
        user = UserModel('name', 'password')
        user.save_to_db()
    app.run() 

Doing this gives me the following error:

Traceback (most recent call last):
  File "C:\Users\Jeffrey T\Documents\2019_2023UPenn\PennLabs\ChallengeSpr2020\PennLabsServerChallengeSpr2020\venv\lib\site-packages\sqlalchemy\util\_collections.py", line 1020, in __call__
    return self.registry[key]
KeyError: 48452

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Jeffrey T/Documents/2019_2023UPenn/PennLabs/ChallengeSpr2020/PennLabsServerChallengeSpr2020/index.py", line 18, in <module>
    jen = UserModel.find_by_name('jen')
  File "C:\Users\Jeffrey T\Documents\2019_2023UPenn\PennLabs\ChallengeSpr2020\PennLabsServerChallengeSpr2020\models\user.py", line 54, in find_by_name
    return cls.query.filter_by(username=username).first()
  File "C:\Users\Jeffrey T\Documents\2019_2023UPenn\PennLabs\ChallengeSpr2020\PennLabsServerChallengeSpr2020\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 514, in __get__
    return type.query_class(mapper, session=self.sa.session())
  File "C:\Users\Jeffrey T\Documents\2019_2023UPenn\PennLabs\ChallengeSpr2020\PennLabsServerChallengeSpr2020\venv\lib\site-packages\sqlalchemy\orm\scoping.py", line 78, in __call__
    return self.registry()
  File "C:\Users\Jeffrey T\Documents\2019_2023UPenn\PennLabs\ChallengeSpr2020\PennLabsServerChallengeSpr2020\venv\lib\site-packages\sqlalchemy\util\_collections.py", line 1022, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "C:\Users\Jeffrey T\Documents\2019_2023UPenn\PennLabs\ChallengeSpr2020\PennLabsServerChallengeSpr2020\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3286, in __call__
    return self.class_(**local_kw)
  File "C:\Users\Jeffrey T\Documents\2019_2023UPenn\PennLabs\ChallengeSpr2020\PennLabsServerChallengeSpr2020\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 136, in __init__
    self.app = app = db.get_app()
  File "C:\Users\Jeffrey T\Documents\2019_2023UPenn\PennLabs\ChallengeSpr2020\PennLabsServerChallengeSpr2020\venv\lib\site-packages\flask_sqlalchemy\__init__.py", line 987, in get_app
    raise RuntimeError(
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

Any ideas how to resolve this?

Upvotes: 3

Views: 3794

Answers (1)

CaffeinatedMike
CaffeinatedMike

Reputation: 1607

The proper way to add data to a table when it's first created is as follows

from sqlalchemy import event
# import your initialized db
from app import db

class Department(db.Model):
    __tablename__ = 'department'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(64), index=True)

@event.listens_for(Department.__table__, 'after_create')
def create_departments(*args, **kwargs):
    db.session.add(Department(name='Customer Service', email='[email protected]'))
    db.session.add(Department(name='IT', email='[email protected]'))
    db.session.commit()

The first time db.create_all() runs in your config setup sequence it will create your database schema and will trigger the create_departments function to populate the table with the data you want.

Upvotes: 7

Related Questions