Run python script under Django server

Hello All,

I have a script that should run independently and basically do a network scan, and in the end of process will populate Django database with scan result.

My question is how can i make the script run and import all Django settings recognize models and able to save results into it.

Or any other suggestion to run the script task will be appreciate

Please advice

Thanks

The easiest path is to implement the script as a Django management
command. Supposing your Django application name is “foo”, there should
be a directory:

foo/management/commands

in your project source tree. Make the script as the file:

foo/management/commands/your-script-name.py

in there. Then you can run the script as:

manage.py your-script-name whatever-arguments...

You’ll need to provide a class in the script called “Command”
subclassing “BaseCommand”, with a “handle” method (your main function).
Minimal sketch:

from django.core.management import BaseCommand

class Command(BaseCommand):

    help = "help or usage message here"

    def handle(self, *argv, **options):
        ... do your thing ...

Documentation here: Writing custom django-admin commands | Django documentation | Django

Argument parsing follows the argparse library approach via an
“add_arguments” method.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like