【问题标题】:Loop through a list and call API in python循环遍历列表并在python中调用API
【发布时间】:2021-11-12 10:11:17
【问题描述】:

我有作者姓名列表(超过 1k),我的 google api 引用限制是 20k 我想将作者姓名传递到 API 以获取书籍信息。当我测试我的代码时,我得到“429 客户端错误:对 url 的请求太多...”错误,如何在不停止应用程序的情况下减慢运行时间。 (我在 google colab 中使用 Python)

author_List = ["J. K. Rowling", "mark twain","Emily Dickinson"] #there are more around 1k - 2k
author_List = author_List.to_dict()

newList = []
for key in author_List:
  author = author_List[key]
  newList.append(searchData(author))


print(newList)



def searchData(authorName):
     try:

        key= "**********************************"
        api = f'https://www.googleapis.com/books/v1/volumes?q={author}&key={key}'
        response = requests.get(api)
        response.raise_for_status()
        print(response)
    except requests.RequestException as e: 
        raise sys.exit(e)





Updated Code
author_List = ["J. K. Rowling", "mark twain","Emily Dickinson"] 
connGoogleAPI(author_List)
def connGoogleAPI(booksData):
  key= "**************************"
  books_list = []
  col= ['Title', 'Authors', 'published Date', 'Description','ISBN']
  books_list.append(col)  
  res = ""
  err = None
  with requests.Session() as session:
      #err= ""
      for Authors in booksData:
        params = {"q": Authors,"key": key,"maxResults": 1}
        delays = 65 # approximately 1 minute total delay time for any given author
        while True:
          try:
              url = "https://www.googleapis.com/books/v1/volumes?"
              response = requests.get(url,params=params)
              print(type(response.raise_for_status()))
              err = response.raise_for_status()
              res = response.json()
              break # all good :-)
          except Exception as e:
              if err.status_code == 429:
                  #print("******")
                  if delays <= 0:
                      raise(e) # we've spent too long delaying
                  time.sleep(1)
                  delays -= 1
              else:
                  print("-----=")
                  raise(e) # some other status code     

   
        books_list.append(lookup(res,Authors))

  return books_list

【问题讨论】:

  • 列表没有 to_dict 属性

标签: python api google-api


【解决方案1】:

你可以import time然后加:

time.sleep(1)

在 for 循环结束时,在每次迭代之间暂停一秒钟。

【讨论】:

  • 这可能会不必要地减慢速度。最好等到 429 发生然后引入延迟
【解决方案2】:

你可以像这样放慢你的 for 循环: 首先,你需要import time

delay = 2
for key in author_List:
   author = author_List[key]
   newList.append(searchData(author))
   time.sleep(delay)

你可以设置一个数字循环延迟多少秒(这里是2秒)

【讨论】:

    【解决方案3】:

    您可能不希望无条件延迟会不必要地减慢您的处理速度。另一方面,如果您开始收到 HTTP 429,您无法确定服务器何时甚至是否允许您继续。因此,您需要一种仅在需要时/如果需要时引入延迟但也不会陷入无限循环的策略。考虑一下:

    import requests
    import time
    
    listofauthors = ['Mark Twain', 'Dan Brown', 'William Shakespeare']
    
    with requests.Session() as session:
        for author in listofauthors:
            params = {'q': author}
            delays = 60 # approximately 1 minute total delay time for any given author
            while True:
                try:
                    r = session.get('https://www.googleapis.com/books/v1/volumes', params=params)
                    r.raise_for_status()
                    print(r.json())
                    break # all good :-)
                except Exception as e:
                    if r.status_code == 429:
                        if delays <= 0:
                            raise(e) # we've spent too long delaying
                        time.sleep(1)
                        delays -= 1
                    else:
                        raise(e) # some other status code
    

    【讨论】:

    • 感谢您的帮助,我在 google colab 中的 python 无法识别 := 所以我把它放在一个单独的变量中但是,我不断得到 NoneType' 对象没有属性 'status_code' 我已经3 小时以来一直试图解决这个问题(在密钥中添加了额外的数字只是为了测试代码,我在主帖中更新了代码)
    • 我对 Google Colab 一无所知,但所谓的“海象”运算符依赖于 Python 3.7+ 版本。话虽如此,您所说的含义是 session.get() 正在返回 None ,我认为这是不对的。您可以编辑原始问题以显示更新后的代码吗?同时,我将为 3.7 之前的 Python 版本编辑我的答案
    • 我编辑了问题,我没有使用 session.get 我使用 request.get 坚持
    • 您编辑的代码不可运行。尝试复制/粘贴我的答案,看看会发生什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多