'application not registered on db instance' after user table truncation

880 views Asked by At

I deleted all the info in my users table during testing. Now when I try to run a manage.py command to recreate the admin user, I get RuntimeError: application not registered on db instance and no application bound to current context. I've been reading about Flask contexts, especially What is the purpose of Flask's context stacks?, but it's not clear to me how to fix this. How do I fix this error?

$ python manage.py db create_admin
Traceback (most recent call last):
  File "manage.py", line 58, in <module>
    manager.add_command("create_admin", create_admin())
  File "manage.py", line 47, in create_admin
    confirmed_on=datetime.datetime.now()
  File "c:\envs\virtalenvs\flask_mini\lib\site-packages\sqlalchemy\orm\scoping.py", line 150, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "c:\envs\virtalenvs\flask_mini\lib\site-packages\sqlalchemy\util\_collections.py", line 878, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "c:\envs\virtalenvs\flask_mini\lib\site-packages\flask_sqlalchemy\__init__.py", line 704, in create_session
    return SignallingSession(self, **options)
  File "c:\envs\virtalenvs\flask_mini\lib\site-packages\flask_sqlalchemy\__init__.py", line 149, in __init__
    self.app = db.get_app()
  File "c:\envs\virtalenvs\flask_mini\lib\site-packages\flask_sqlalchemy\__init__.py", line 845, in get_app
    raise RuntimeError('application not registered on db '
RuntimeError: application not registered on db instance and no application bound to current context

manage.py:

import os
from flask_script import Manager
from myflaskapp.app import create_app
from myflaskapp.models.user import User
from myflaskapp.database import db

manager = Manager(app)

@manager.command
def create_admin():
    db.session.add(User(
        username="admin1",
        email="[email protected]",
        password="admin",
        admin=True,
        confirmed=True,
        confirmed_on=datetime.datetime.now()
    ))
    db.session.commit()

manager.add_command("create_admin", create_admin())
manager.run()
1

There are 1 answers

0
davidism On BEST ANSWER

You're using @manager.command, so you shouldn't also use manager.add_command. Completely remove the line manager.add_command('create_admin', create_admin()).

If you want to use add_command, then remove @manager.command and use manager.add_command('create_admin', Command(create_admin)).

You get the error because the app context is only active when the manager is running, but you're calling the function prematurely.