Reputation: 1844
I want to execute various commands and display/process their output to a django template. For example:
All I am searching for is a mindset to think on. I'm stuck where I import subprocess
inside views.py and do not know how to go on. How should I continue ?
Upvotes: 0
Views: 814
Reputation: 7555
To ping a host on linux from a Django view:
import subprocess
def view(request):
try:
subprocess.check_call(['ping', '-c', '1', "1.2.3.4"])
except subprocess.CalledProcessError:
host_online = False
else:
host_online = True
return render(request, "template.html", {'online': host_online,})
This runs the command ping -c 1 1.2.3.4
which will try to ping the host once only. ping
will exit with a return code of 0 if it succeeded, and 1 if it did not. subprocess.check_call(...)
translates that 1 or 0 into an exception or no exception (respectively).
This solution will cause the page load to be held up while the ping is in progress, which will be a few seconds if the host is in fact down. If that is a problem, consider instead putting the ping in a view that is requested via AJAX from the page once it has loaded.
You can do similar things for your other commands.
Upvotes: 1