DEV Community

Discussion on: Django view doesn't output correctly

Collapse
 
vergeev profile image
Pavel Vergeev

If your end goal is to check website availability, I would suggest making a HEAD request to it, like so:

import requests  # requests library https://github.com/psf/requests

def pingDomain(request, page):
    page_object = get_object_or_404(Table, page=page)
    response = requests.head(url=page_object.page)
    context = {
         'online': response.ok
    }
    return render(request, 'home.html', context)

Here are the advantages:

  • does not rely on the presence of the ping command in the os
  • the above code checks whether the server responds to a HTTP request, but ping checks whether the service responds to a ICMP request
  • the code is shorter :)

Is there any particular reason you've decided to use subprocess.check_call(['ping', '-c', '1', page_object.page])?

Collapse
 
highcenburg profile image
Vicente G. Reyes

I'll definitely try this!

I just saw

subprocess.check_call(['ping', '-c', '1', page_object.page])
on stackoverflow so I used. Big lesson for me to understand code before using it.
Collapse
 
highcenburg profile image
Vicente G. Reyes

uhhh this doesn't return the online domains.

Collapse
 
vergeev profile image
Pavel Vergeev

Wow :O

OK, at this point I can only suggest two things.

  1. Use breakpoint() to inspect the variables inside the view;

  2. Use this code for your reference: github.com/vergeev/17_sites_monito....

Tell me if something new comes up. :)

Thread Thread
 
highcenburg profile image
Vicente G. Reyes

Here's what I did

def pingDomain(request, page, url):
    page_object = get_object_or_404(Table, page=page)
    url = page_object.page
    response = requests.head(url)
    try:
        return requests.head(url).ok
    except requests.exceptions.ConnectionError:
        return False
    context = {
        'online': response.ok
    }
    return render(request, 'home.html', context)

Returns nothing :(

Collapse
 
highcenburg profile image
Vicente G. Reyes

I'm not really sure if you understood what I wanted to output on the template since you've mentioned that my end goal was to check the availability of the website or I'm not sure if you meant online/offline with website availability