vendredi 5 juin 2020

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?




Aucun commentaire:

Enregistrer un commentaire