【问题标题】:Are my Python threads tripping over each other with requests?我的 Python 线程是否因请求而相互绊倒?
【发布时间】:2017-12-14 17:12:29
【问题描述】:

我有一个程序需要从 API 访问数据。我需要从中获取一个列表,然后对于该列表中的每个项目,从 API 请求更多数据。当我得到一个清单时,我会分批 50 个,而这个清单上有大约 600 个项目。我认为我可以使用请求和线程来做到这一点。这是它的样子:

我基本上有一个辅助方法来调用 API:

call_api_method(method, token, params={}):
     params_to_send = params.copy()
     params_to_send['auth'] = token
     response = requests.get('{0}/rest{1}'.format(DOMAIN, method), params = params_to_send)
     return response.json()

然后我有一个递归线程函数来获取所有信息。我想我可以使用线程继续请求下一批信息,同时让线程请求每个项目的信息:

def import_item_info(auth_token, start = None):
     if start is None:
          start = 0
     threads = []
     result = call_api_method('get_list', auth_token, {'start': start})
     #the call returns next which is the index of the next batch
     if result['next']:
          thread = threading.Thread(target=import_item_info, args=(auth_token, result['next'])
          thread.start()
          threads.append(thread)
     for list_item in result['result']:
          thread = threading.Thread(target=get_item_info, args=(auth_token, item['ID'])
          thread.start()
          threads.append(thread)
     for thread in threads:
          thread.join()

这是get_item_info,它使用item的id调用api来获取item的具体细节:

 def get_item_info(auth_token, item_id):
     item = call_api_method('get_item', auth_token, {'id': item_id})
     print(item['key'])

我已经提取了很多信息,但实际上发生的情况是,有时 requests.get 返回的内容有些乱码,并且我收到 JSONDecodeError: Expecting value: line 1 column 1 (char 0)。

我高度怀疑这是一个线程问题,因为第一个请求通过就好了。我似乎找不到我做错了什么。

【问题讨论】:

  • 真正的网址是什么?你试过没有线程的get_item_info 吗?你有同样的问题吗?你打印response.textresponse.content 看看你得到了什么?也许你会得到一些有用的信息——也许 API 会向你发送一些警告,或者网络存在不同的问题。您是否打印了完整的 url 以直接在网络浏览器中进行测试?也许您创建的 url 在网络浏览器中也不起作用。
  • get_item_info 在没有线程的情况下工作得很好。没问题。我打印了物品和物品的钥匙就好了。完整的网址也可以正常工作。至于真正的url是什么:是我们公司的云CRM。

标签: python multithreading python-requests


【解决方案1】:

好的。抱歉...我以为我检查过了,但显然我达到了查询限制,这就是它开始做奇怪事情的原因。

【讨论】:

    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多