Last active
September 24, 2022 10:41
-
-
Save marcelohmariano/9470a0da70b53d2889b9865d74568e4b to your computer and use it in GitHub Desktop.
Python requests + retry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Dict, Any, Optional, Union | |
import requests.adapters | |
import uvicorn | |
from fastapi import FastAPI | |
from fastapi.responses import JSONResponse | |
app = FastAPI() | |
public_ip_apis = [ | |
{ | |
'name': 'myip', | |
# 'url': 'https://api.myip.com/404', | |
'url': 'http://httpstat.us/503' | |
}, | |
{ | |
'name': 'ipify', | |
'url': 'https://api.ipify.org?format=json', | |
}, | |
] | |
session = requests.Session() | |
retries = requests.adapters.Retry( | |
total=2, | |
backoff_factor=1, | |
status_forcelist=[429, 500, 501, 502, 503, 504] | |
) | |
session.mount('http://', requests.adapters.HTTPAdapter(max_retries=retries)) | |
exceptions = ( | |
requests.ConnectionError, | |
requests.HTTPError, | |
requests.adapters.RetryError, | |
) | |
def query_public_ip(url: str) -> Optional[str]: | |
try: | |
response = session.get(url) | |
response.raise_for_status() | |
response_as_json = response.json() | |
return response_as_json['ip'] | |
except exceptions: | |
return None | |
@app.get('/') | |
def get_public_ip() -> Union[Dict[str, Any], JSONResponse]: | |
for api in public_ip_apis: | |
public_ip = query_public_ip(api['url']) | |
if public_ip is not None: | |
return {'ip': public_ip, 'provider': api['name']} | |
return JSONResponse({'error': 'Bad Gateway'}, status_code=502) | |
if __name__ == '__main__': | |
uvicorn.run('__main__:app', reload=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment