Dmitrii Seleznev
Dmitrii Seleznev

Reputation: 1

Script for a requests to URL

I'm trying to make a custom script that will send a request to the page and test it for availability, if the answer is 200, then I want the answer to be 1, if any other 2, and the metric will not be recorded, tell me how best to do it? Sorry if this is a stupid question, I'm just learning python

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning 
import os
import datetime
import pytz

def get_status_ghe():
    url_list = [os.environ.get('http://testurl.com:8080')]
    for i in range(0, len(url_list)):
        if resp.status_code == 200:
            print('ghe0')
        elif resp.status_code != 200:
            print('ghe1')
        else:
            print('ghe2')  
def ghe_request():
    try:
        resp = requests.head('http://testurl.com:8080')
        if resp.status_code == 200:
            return 1
            print(resp)
            print('1')
        else:
            return 0
            print(resp)
            print('0')
    except:
        return 0 

Upvotes: 0

Views: 134

Answers (1)

Barmar
Barmar

Reputation: 782683

You need to call requests.head() in the loop.

Your second condition should just test for any 2xx value (I assume that's what you mean by "any 2"). Then the else: block will handle all other status codes.

Don't use for i in range(len(url_list)): when you can more simply use for url in url_list:

def get_status_ghe():
    url_list = [os.environ.get('http://testurl.com:8080')]
    for url in url_list:
        resp = requests.head(url)
        if resp.status_code == 200:
            print('ghe0')
        elif 201 <= resp.status_code <= 299:
            print('ghe1')
        else:
            print('ghe2')  

Upvotes: 1

Related Questions