How to re-call the function if the recursion is not an option?

Welcome.

Trying to figure out how to rewrite a piece of code to operate predictably. So I have a function that makes a request using requests. Often a request fails if not correct Protocol (http or https). I know the proper Protocol can't, so if an exception is thrown, then I make another stupid attempt replacing https to http or http to https. Here's the code function:

def makeRequestsGet(url, attempt=1):

 if attempt <= 2:

try:

 response = requests.get(url, headers=headers, verify=False, timeout=30)
response.close()

 return response

 except ConnectionError as e:

 if url.find('https') != -1:

 url = url.replace('https', 'http')

else:

 url = url.replace('http', 'https')

 makeRequestsGet(url, attempt=attempt+1)

else:

 return False

The problem appears when I call this function anywhere and in case if the first query attempt fails because of the wrong Protocol. Then the following happens:

  1. Call function makeRequestsGet
  2. The Protocol is not valid, returns None
  3. The script is running on, because None the same result
  4. The second attempt makeRequestsGet
  5. Comes the proper answer of the query results
  6. But it is no longer needed, because there were already None

can't figure out how to rewrite a function to a script from running until you made the second attempt of the request provided that the first was not successful. Tell me how to think.
April 3rd 20 at 17:24
2 answers
April 3rd 20 at 17:26
Solution
I do not quite understand claims about recursion. But this script can change that by adding return:
return makeRequestsGet(url, attempt=attempt+1)
Thank you, did not think himself... - Sarina.Corker commented on April 3rd 20 at 17:29
April 3rd 20 at 17:28
how to rewrite a function to a script from running until you made the second attempt of the request provided that the first was not successful.

It is not clear what is meant.

There is an option:
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry


def requests_retry_session(
retries=3,
backoff_factor=0.3,
 status_forcelist=(500, 502, 504),
session=None,
):
 session = session or requests.Session()
 retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
 adapter = HTTPAdapter(max_retries=retry)
 session.mount('http://', adapter)
 session.mount('https://', adapter)
 return session


response = requests_retry_session().get('https://toster.ru/')
print(response.status_code)

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

response = requests_retry_session(session=s).get(
'https://toster.ru'
)

Find more questions by tags Python