Issue
I configured the app for using Application Factories. App goes well, I can login, create users, query information from Postgres DB, Migrate tables, etc.
I used to query data from models in python console for check status and test some ORM configuration before Application Factories changes, I used to run these commands and get response
PC:~/exercises/$ python
Python 3.8.5 (default, Sep 4 2020, 07:30:14)
>>> from app.models import *
>>> User.query.all()
After applying configuration I tried to retrieve queries. Import tables do not return any error however query returns this error:
>>> from app.models import *
>>> User.query.all()
Traceback (most recent call last):
File "/home/dannisis/dock_exercise/emailservices/env/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 1008, in __call__
return self.registry[key]
KeyError: <greenlet.greenlet object at 0x7f0cb7196bf0 (otid=0x7f0cb818dd40) current active started main>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/dannisis/dock_exercise/emailservices/env/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 552, in __get__
return type.query_class(mapper, session=self.sa.session())
File "/home/dannisis/dock_exercise/emailservices/env/lib/python3.8/site-packages/sqlalchemy/orm/scoping.py", line 129, in __call__
return self.registry()
File "/home/dannisis/dock_exercise/emailservices/env/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 1010, in __call__
return self.registry.setdefault(key, self.createfunc())
File "/home/dannisis/dock_exercise/emailservices/env/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 4044, in __call__
return self.class_(**local_kw)
File "/home/dannisis/dock_exercise/emailservices/env/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 174, in __init__
self.app = app = db.get_app()
File "/home/dannisis/dock_exercise/emailservices/env/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py", line 1042, 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/.
I tried import models' tables with `from create_app.models import *' it returns error too. How can I retrieve queries in terminal or console
Tree application simplified and the related app configurations below:
├── app
│ ├── admin
│ │ ├── forms.py
│ │ ├── __init__.py
│ │ └── views.py
│ ├── config.py
│ ├── errors
│ │ ├── forms.py
│ │ └── __init__.py
│ ├── __init__.py
│ ├── main
│ │ ├── forms.py
│ │ ├── __init__.py
│ │ ├── utils.py
│ │ └── views.py
│ ├── models.py
│ ├── static
│ │ ├── css
│ │ │ └── styles.css
│ │ ├── img
│ │ │ └── favicon.ico
│ │ └── js
│ │ └── scripts.js
│ └── templates
│ ├── account.html
│ ├── home.html
│ ├── index.html
│ └── layout.html
├── migrations
│ ├── alembic.ini
│ ├── script.py.mako
│ └── versions
│ ├── 1de2ece5a3da_initial_commit.py
│ └── 9815b2f43f0a_tabla_dependientes.py
├── requirements.txt
├── run.py
└── tree.txt
Run file is:
from app import create_app
app = create_app()
if __name__ == "__main__":
app.run(debug=True)
Models file simplified too is:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
username = db.Column(db.String(30), unique=True, nullable=False)
Init file in app directory include imports and db, migrate, bcrypt, etc instantiation and application function is
def create_app(config_class = Config):
app = Flask(__name__)
app.config.from_object(Config)
app.config['SQLALCHEMY_DATABASE_URI'] = db_prefix + f'{Config.POSTGRES_DBNAME2}'
db.init_app(app)
migrate.init_app(app, db)
bcrypt.init_app(app)
login_manager.init_app(app)
mail.init_app(app)
from app.main.views import main
from app.admin.views import admin
app.register_blueprint(main)
app.register_blueprint(admin)
return app
Solution
Use the flask shell
command to access your application. The purpose of this command is to start a Python interpreter in the context of the application. What do I mean:
$ python
>>> from app.models import *
>>> User.query.all()
# Output
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
#...
But:
$ flask shell
>>> from app.models import *
>>> User.query.all()
# Output
# ... no traceback
With a regular interpreter session, app
is not known unless explicitly imported, but flask shell
pre-imports your application instance.
How to configure flask shell
In your application's entry point, which is run.py
, configure a shell context, which is a list of other symbols to pre-import.
# run.py
from app import create_app, db
from app.models import User
app = create_app()
@app.shell_context_processor
def make_shell_context():
return {
'db': db,
'User': User
}
if __name__ == "__main__":
app.run(debug=True)
In your terminal, run:
$ flask shell
>>> from app.models import *
>>> User.query.all()
# Output
# ... no traceback
Answered By - Gitau Harrison
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.