Edoardo Zucchelli
Edoardo Zucchelli

Reputation: 77

UWSGI - Launch script with manage.py

I need to run a script into my Django project.

I'm using this approach, that works, but I'm looking for more valid alternatives.

uwsgi.py

import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyApp.settings")
application = get_wsgi_application()

__import__('myapp.script')
import os

os.environ = {'DJANGO_SETTINGS_MODULE': 'MyApp.settings'}

import django

django.setup()

def main():

    # some script using django db
    pass

main()

I've already look on uwsgi documentation and django, but can't find a way to run the manage.py.

I don't like to use this approach because every time I need to set DJANGO_SETTINGS_MODULE, because I also want to run it locally.

I prefere using the runscript. So, there is a way to call the manage.py from the wsgi module in order to use the runscript to run the script.py?

Or, do you know another approach like the uwsgi.ini or something else?

Upvotes: 0

Views: 448

Answers (1)

Leeuwtje
Leeuwtje

Reputation: 345

You can also create your own management commands: https://docs.djangoproject.com/en/4.0/howto/custom-management-commands/

When you have a command, you can execute it with python manage.py your_command and also from within a view or other location in you code with the call_command function:

from django.core.management import call_command
call_command('your_command')

This way you don't have to worry about the settings module or other django related overhead or setup

Upvotes: 1

Related Questions