Search code examples
djangodjango-viewsdjango-manage.py

Running a Django Management command - triggered by site visitor


I have a web page that uses Ajax to fetch data every 10 seconds. I want to instead call it every 60 seconds and make the Ajax view to start a management command: "python manage.py collect_ticker -i". This way I can collect ticker data while the visitor has the page open, rather than check every 10 seconds for any new ticker data.

I am using the below code in the Ajax view:

import subprocess
import os
import sys

fulldirname = os.path.abspath('../tickerproject/')


p = subprocess.Popen([fulldirname, 'python manage.py collect_ticker -i%d' % (i_ticker)], 
                                            stdout=subprocess.PIPE, 
                                            stderr=subprocess.STDOUT)

The problem is that I am getting the response:

[Errno 13] Permission denied

Questions:

1) Is it even appropriate in Django to allow a site visitor to execute a management command?

2) If Yes, how do I fix the permission issue while being on the safe side security wise?


Solution

  • Solution1: You can use call_command to run the command from django view without having permission issues:

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

    Solution2: you can directly call the function instead of management command from ajax/django view when visitor has the page open

    ex: def page_view(request):
            management_command_replacement_function(params)
            return HttpResponse()
    
       def management_command_replacement_function(params)
           ####processing############