AttributeError: module 'requests' has no attribute 'ok' when using 'requests' inside a function
Question:
I am trying to grab match information from opendota.com API, but when I try with this code I get the following error:
import requests, json, time, os
#Download games
def get_match_by_id(match_id):
m_id = str(match_id)
#fetch match data
requests.get("https://api.opendota.com/api/matches/" + m_id)
if requests.ok:
print("GET:", m_id)
data = requests.json()
#save the match data
file = open("download" + os.sep + m_id + '_data.json', 'w')
json.dump(data, file)
file.close()
match_id = 6727193237
match_id = 6757193237
for i in range(0, 5000):
get_match_by_id(match_id + 1)
time.sleep(2)
AttributeError: module 'requests' has no attribute 'ok'
Can anybody help me figure out the reason for this? I tried to lookup various other questions similar but none of those uses ‘ok’ as method
Answers:
You are treating the requests
module as having the response returned from the request you sent with requests.get()
. It doesn’t have that information, which will cause unexpected behaviour. Instead, you need to assign the return value to a variable and use that to check the response.
def get_match_by_id(match_id):
m_id = str(match_id)
response = requests.get("https://api.opendota.com/api/matches/" + m_id)
if response.ok:
print("GET:", m_id)
data = response.json()
with open("download" + os.sep + m_id + '_data.json', 'w', encoding='utf-8') as f:
json.dump(data, f)
I am trying to grab match information from opendota.com API, but when I try with this code I get the following error:
import requests, json, time, os
#Download games
def get_match_by_id(match_id):
m_id = str(match_id)
#fetch match data
requests.get("https://api.opendota.com/api/matches/" + m_id)
if requests.ok:
print("GET:", m_id)
data = requests.json()
#save the match data
file = open("download" + os.sep + m_id + '_data.json', 'w')
json.dump(data, file)
file.close()
match_id = 6727193237
match_id = 6757193237
for i in range(0, 5000):
get_match_by_id(match_id + 1)
time.sleep(2)
AttributeError: module 'requests' has no attribute 'ok'
Can anybody help me figure out the reason for this? I tried to lookup various other questions similar but none of those uses ‘ok’ as method
You are treating the requests
module as having the response returned from the request you sent with requests.get()
. It doesn’t have that information, which will cause unexpected behaviour. Instead, you need to assign the return value to a variable and use that to check the response.
def get_match_by_id(match_id):
m_id = str(match_id)
response = requests.get("https://api.opendota.com/api/matches/" + m_id)
if response.ok:
print("GET:", m_id)
data = response.json()
with open("download" + os.sep + m_id + '_data.json', 'w', encoding='utf-8') as f:
json.dump(data, f)