How do I execute an arbitrary script in the context of my Django project?

Viewed 5497

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?

3 Answers

Here's the simplest solution:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

import django
django.setup()

Be sure to include this at the top of your python file, before importing any of your models.

Alternatively, you could use the solution pointed out by @beyondfloatingpoint:

import os, sys

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
sys.path.append("mysite")
os.chdir("mysite")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Best solution is provided in this article.

Hints: Make sure you are using correct path to settings module, in my case, I missed nested dirs named the same way. The best way to avoid my mistake is to use something like this template to start with.

Related