Is there a way to import all db.models for my shell?
rlam3 opened this issue · 7 comments
Is there a way to import all db.models for my shell when going interactive shell? I'm using sqlalchemy.
I'm using make_context and only able to pass models into the dictionary.... I want to be able to use the shell without having to do
from app.models.user import User
etc...
every time I go into interactive shell
Thanks!
db.Model._decl_class_registry
maps names to models. You can use the shell
decorator to define your own context that includes these.
FWIW, here's how I handle auto-imports of my models when I run python manage.py shell
:
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
def make_shell_context():
from pprint import pprint
from flask_sqlalchemy import get_debug_queries
return dict(
app=app, db=db,
pprint=pprint, gq=get_debug_queries,
Article=Article,
ArticleCategory=ArticleCategory,
ArticleComment=ArticleComment)
manager.add_command('shell', Shell(make_context=make_shell_context))
Works fine for me
Jeff's example should end up in docs.
@jeffwidman this would mean that if my models are in different folders, i would have to import them individually. I was hoping to import all models from a model folder and then each class within each module... more like a for loop
I agree it's a pain. My wife was working on a somewhat similar problem recently around looping through imports
and found the stdlib importlib
useful. Afraid I haven't zero experience with it myself, so can't comment, but if you do explore and figure out a way to get it working, I'm definitely open to a PR putting an example in the docs.
Just if somebody ends up here and don't know how to import shell
from flask_script import Shell
FWIW, here's how I handle auto-imports of my models when I run
python manage.py shell
:app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) def make_shell_context(): from pprint import pprint from flask_sqlalchemy import get_debug_queries return dict( app=app, db=db, pprint=pprint, gq=get_debug_queries, Article=Article, ArticleCategory=ArticleCategory, ArticleComment=ArticleComment) manager.add_command('shell', Shell(make_context=make_shell_context))
Works fine for me
if someone would like to import all models from a package:
import inspect
from app import db, models
def make_shell_context():
return dict(
db=db,
**dict(inspect.getmembers(models, inspect.isclass)))