How To Run External Script Inside Django Environment

How To Run External ScrIpt InsIde Django EnvIronment

Hello guys, I want to show you how to run an external Python script inside a Django environment for debugging, for data-crud operations, etc. You can use Django modules and your Django models inside the script and run and run without any error. The good thing here is you don’t need to create Django commands to run your script. This way is easier to run and debug an external script.

Now let’s look at how Django starts up.

We use runserver command to start up a Django project, we trigger it with python manage.py runserver as every Django people know. Inside this command, the runserver.inner_run method is called, and inside this method, the django.servers.get_internal_wsgi_application function is given to django.servers.run function as a parameter and called.

Here, a WSGIServer instantiated which will become the server part of the WSGI protocol. WSGIRequestHandler parameter is given because it will be called inside the WSGIServer to process the incoming requests.

There is also a set_app method run. Our WSGIHandler instance handler object is given as a parameter. This method sets the web application part of the WSGI protocol.

Lastly, the function executes the serve_forever method and starts to listen to the port.

Inside django.servers.get_internal_wsgi_application, django.setup() function is called, where the web application part is set.

from django.utils.version import get_version

VERSION = (4, 0, 0, 'alpha', 0)

__version__ = get_version(VERSION)


def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
        )
    apps.populate(settings.INSTALLED_APPS)

Here the logging is configured and the app registry is populated.

Now let’s get back to our main topic. Before we run django.setup in the script, we need to provide where is the settings.py in our project:

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")

Then we can call django.setup:

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings ")
django.setup()

Then we’re ready to go. We can run our fancy scripts now, like:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import django
from project.apps.myapp.models import MyModel

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django.setup()


def work():
    for i in range(10):
        m = MyModel.objects.get(pk=i)


if __name__ == '__main__':
    work()

Source:
How applications are loaded
How the WSGI protocol works

Leave a Reply

Your email address will not be published. Required fields are marked *