Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

AttributeError: module 'requests' has no attribute 'ok' when using 'requests' inside a function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading