3

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?

1
  • what is your app? give us more explanation Commented Jun 6, 2020 at 1:53

1 Answer 1

8

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.

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

1 Comment

Your decorator looks like needs a table argument (Department). What if I have more than one table?

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.