Sometimes I want to execute a file in the context of my Django project, just as if I were using the shell, but with the convenience of using a text editor. This is mainly to try something out, or quickly prototype some functionality before putting it into a view, test, recurring task, or management command.
I know I can stick these lines at the top of my .py file and it'll run in the Django context:
import sys
sys.path.append('/location/of/projet')
from django.core.management import setup_environ
import settings
setup_environ(settings)
I thought it'd be easier to make a management command that takes on argument, a python module to run, and executes it in the Django environment. Here's the 'runmodule' command I wrote:
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Runs an arbitrary module, in the Django environment, for quick prototyping of code that's too big for the shell."
def handle(self, *args, **options):
if not args:
return
module_name = args[0]
try:
__import__(module_name)
except ImportError:
print("Unable to import module %s. Check that is within Django's PYTHONPATH" % (module_name))
This looks like it works -- I can stick some code in a module, and pass it as an argument to this command, and it'll get executed, e.g.
python manage.py runmodule myapp.trysomethingout
which will execute myapp/trysomethingout.py. Is this the best way to do this?