Wednesday, July 21, 2010

Bpython + Django

Hi,

If you'd like to use the bpython interpreter with django, and auto-load your models, here's how you can do it.

install bpython using pip or whatever, make sure it's in your path
example:
pip install bpython

create a file in (django location)/core/management/
commands/ (I use virtualenv so for me it's in (env)/lib/python2.6/site-packages/django/core/management/ )

Name the file bpshell.py containing the code below.

and now you can run ./manage.py bpshell !!!


# Copy this file to (django location)/core/management/commands/bpshell.py
# make sure that bpython is somewhere in your path (virtual env?)
# run using ./manage.py bpshell

import os
from django.core.management.base import NoArgsCommand
from django.db.models.loading import get_models, get_apps
from optparse import make_option

class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--plain', action='store_true', dest='plain',
help='Tells Django to use plain Python, not bpython.'),
)
help = "Runs a Python interactive interpreter. Tries to use bpython, if it's available."

requires_model_validation = False


def handle_noargs(self, **options):
# XXX: (Temporary) workaround for ticket #1796: force early loading of all
# models from installed apps.
from django.db.models.loading import get_models
loaded_models = get_models()

use_plain = options.get('plain', False)

imported_objects = {}

for app_mod in get_apps():
app_models = get_models(app_mod)
if not app_models:
continue
model_labels = ", ".join([model.__name__ for model in app_models])
print self.style.SQL_COLTYPE("From '%s' autoload: %s" % (app_mod.__name__.split('.')[-2], model_labels))
for model in app_models:
try:
imported_objects[model.__name__] = getattr(__import__(app_mod.__name__, {}, {}, model.__name__), model.__name__)
except AttributeError, e:
print self.style.ERROR_OUTPUT("Failed to import '%s' from '%s' reason: %s" % (model.__name__, app_mod.__name__.split('.')[-2], str(e)))
continue

try:
if use_plain:
raise ImportError
from bpython.cli import main
locals_=imported_objects
args=['-i', '-q']
banner=None
main(args, locals_, banner)

except ImportError:
import code
imported_objects = {}
try: # Try activating rlcompleter, because it's handy.
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try', because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(imported_objects).complete)
readline.parse_and_bind("tab:complete")

# We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
# conventions and get $PYTHONSTARTUP first then import user.
if not use_plain:
pythonrc = os.environ.get("PYTHONSTARTUP")
if pythonrc and os.path.isfile(pythonrc):
try:
execfile(pythonrc)
except NameError:
pass
# This will import .pythonrc.py as a side-effect
import user
code.interact(local=imported_objects)

0 comments: