0

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 
4
  • 1
    The for loop is missing the call to requests.head. Commented Jul 21, 2022 at 10:55
  • 1
    None of the print() calls after return will execute, since return exits the function. Move return after the print statements. Commented Jul 21, 2022 at 10:56
  • 1
    Is http://testurl.com:8080 really the name of your environment variable? It looks more like the value. Commented Jul 21, 2022 at 10:57
  • 1
    Either the status code is equal to 200 or it's not equal to 200. What's the other possibilities that you think would trigger ghe2? Commented Jul 21, 2022 at 10:58

1 Answer 1

1

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')  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.