[Answer]-How do I use python libraries inside django?

1πŸ‘

βœ…

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.

Leave a comment