How to check if server is available before request.urlopen in Python?

Asked

Viewed 838 times

3

I have the following HTTP request code on my server in my python code:

import urllib.request
import json

url= urllib.request.urlopen('http://ENDERECOIP/pasta/arquivo.php')
x= url.read()
y = json.loads(x.decode('utf-8'))
teste = y['valor']
print(teste)

The code works and returns the value but I wanted to do a previous check in case the server is not available it returns a message "Server unavailable".

  • 1

    If the server is available, what would be the response to your request?

2 answers

1


You can just use one try and except, thus:

import urllib.request
import json

try:
    url= urllib.request.urlopen('http://ENDERECOIP/pasta/arquivo.php')
    x= url.read()
    y = json.loads(x.decode('utf-8'))
    teste = y['valor']
    print(teste)

except Exception as e:
    print("Servidor indisponível. Erro:", e)

The urlopen can only complete the request with the active server.

  • 2

    Almost that. If the answer is not a valid JSON the "Unavailable Server" message will appear even if it is available.

  • 1

    It worked perfectly for what I needed! Thank you very much!

0

The easiest and easiest way to do this is by using the library requests. Use the function requests.get passing the url you want to check. This function will return an object of Response containing the attribute status_code. To know if everything is right, just check the code returned in the answer. Example:

import requests
url = "https://www.youtube.com"

if requests.get(url).status_code == 200:
    print("O servidor está disponível.")
else:
    print("O servidor está indisponível.")

Obviously there are many other ways to check whether a server is available or not, but in my opinion, this form is the simplest.

  • 1

    status_code == 200 is not the only server response available. With your idea, the most appropriate option would be status_code // 100 == 2. But this would also not guarantee a totally correct functioning, because not all responses other than 2xx indicate an unavailable server: 4xx indicates a "client error" and 1xx indicates "information", for example. With OP information I would consider server unavailable only 5xx responses. A wider option is to test the response with the function raise_for_status().

  • 1

    I know code 200 isn’t the only one for servers available, but that was just an example. It can make a list full of codes and check if the server response code is inside it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.