In Python 3, the only thing I had to change to make it work is remove the () after .content (and add imports)
import time
import requests
def get_url(url, retries=2):
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
# Server error, retry request
if response.status_code >= 500 and retries >= 0:
time.sleep(0.1)
get_url(url, retries - 1)
else:
print(str(e))
except Exception as e:
print(str(e))
return response.content.decode('utf-8')
if __name__ == '__main__':
result = get_url('jsonplaceholder.typicode.com/posts/1')
print(type(result))
print(result)
Which gives
<class 'str'>
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Requests already give strings (or bytes really) as response.
If what you're asking is instead to get the objects from this string, then you can import the json package (do not use simplejson if json is available) and do
print(json.loads(result))
Shameless self-promotion: if you want to serialize class instances, arrays, datetimes etc, and have comments, have a look at my library json_tricks.