Meryem
Meryem

Reputation: 487

Django - subprocess call not working properly

I have these following views:

class MiniView(generic.DetailView):
    model = Automata
    template_name = 'convert/mini.html'
    context_object_name = 'automata'
    command = "python MiniDFA.py"
    subprocess.call(command, shell=True)

class DFAView(generic.DetailView):
    model = Automata
    template_name = 'convert/dfa.html'
    context_object_name = 'automata'
    command = "python NFAtoDFA.py"
    subprocess.call(command, shell=True)

class TransitionCreate(UpdateView):
    model = Automata
    fields = []
    [...]
    command = "python make_graph.py"
    subprocess.call(command, shell=True)
    [...]

For I would like the commands to execute everytime I call the view, but for some reason only the last one seems to be working properly I'm not sure why.. the script by itself seems to be working fine.

I also noticed that the scripts execute everytime the server runs, not sure why either..

Upvotes: 0

Views: 1077

Answers (1)

Penguin Brian
Penguin Brian

Reputation: 2131

These are classes, not functions. If you want something to happen on every request, you will need to override one of the relevant functions in the class. For example:

class MiniView(generic.DetailView):
    ...

    def get(self, request):
        ...
        command = "python make_graph.py"
        subprocess.call(command, shell=True)
        ...
        return HttpResponse(...)

As two notes:

  • Using shell=True is probably a bad idea here. Don't use the shell if at all possible, it adds complexity when complexity is not required.
  • If the shell script takes too long, the web client will timeout. Or the user will hammer the server by constantly clicking reload.

Upvotes: 3

Related Questions