如何多线程处理从 API 调用返回数据的函数



我正在尝试从各种API请求数据。服务器必须同时调用,我知道我需要使用多线程,但我无法弄清楚如何以我想要的方式返回数据,这里有一个例子。

import requests
import time
import threading
t = time.strftime('%m/%d/%Y %H:%M:%S')
def getBitstamp():
    data = requests.get('https://www.bitstamp.net/api/ticker/')
    data = data.json()
    ask  = round(float(data['ask']),2)
    bid  = round(float(data['bid']),2)
    print 'bitstamp', time.strftime('%m/%d/%Y %H:%M:%S')
    return ask, bid
def getBitfinex():
    data = requests.get('https://api.bitfinex.com/v1/pubticker/btcusd')
    data = data.json()
    ask  = round(float(data['ask']),2)
    bid  = round(float(data['bid']),2)
    print 'finex', time.strftime('%m/%d/%Y %H:%M:%S')
    return ask, bid 
while True: 
    bitstampBid, bitstampAsk rate = thread.start_new_thread(getBitstamp)
    bitfinexAsk, bitfinexBid = thread.start_new_thread(getBitfinex)
    #code to save data to a csv
    time.sleep(1)

但是,似乎线程不喜欢返回多个(甚至任何值(,我认为我误解了库的工作方式。

编辑删除了变量rate错误

您需要

决定是要使用高级Threading模块还是低级thread。如果以后使用import thread而不是import threading

接下来,您还需要传递一个带有参数的元组以在 thread 内运行函数。如果没有,可以按如下方式传递空元组。

bitstampBid, bitstampAsk, rate = thread.start_new_thread(getBitstamp,())
bitfinexAsk, bitfinexBid = thread.start_new_thread(getBitfinex,())

程序现在执行,如何遇到您可能需要调试的单独错误。
这是我注意到的几个错误。
getBitstamp(( 返回 rate ,但是,rate 没有在 getBitstamp(( 中定义。程序错误。

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Traceback (most recent call last):
  File "C:amPythonmultiThreading1.py", line 28, in <module>
    bitstampBid, bitstampAsk = thread.start_new_thread(getBitstamp,())
TypeError: 'int' object is not iterable
>>> bitstamp 03/18/2017 00:41:33

这篇 SO 帖子讨论了一些关于多线程的想法,可能对您有用。

最新更新