使用requests和concurrent.futures异步发送多个API post请求

时间:2014-01-23 07:09:38

标签: python twitter

除了请求之外,我一直在尝试使用concurrent.futures,以便从几个不同的用户发送几个不同的直接消息。我正在设计的应用程序的目的是尽可能快地发送这些直接消息,并且单独发送每个请求花费的时间太长。

下面的代码是我尝试过的,但我已经清楚地发现,期货不会读取存储在数组中的请求。

非常感谢任何关于如何做到这一点的建议。

from concurrent import futures
import requests
from requests_oauthlib import OAuth1
import json
from datetime import datetime

startTime = datetime.now()

URLS = ['https://api.twitter.com/1.1/direct_messages/new.json'] * 1

def get_oauth():
    oauth = OAuth1("xxxxxx",
                client_secret="zzzxxxx",
                resource_owner_key="xxxxxxxxxxxxxxxxxx",
                resource_owner_secret="xxxxxxxxxxxxxxxxxxxx")
    return oauth

oauth = get_oauth()

req = []


def load_url(url, timeout):
    req.append(requests.post(url, data={'screen_name':'vancephuoc','text':'hello pasdfasasdfdasdfasdffpls 1 2 3 4 5'}, auth=oauth, stream=True, timeout=timeout))
    req.append(requests.post(url, data={'screen_name':'vancephuoc','text':'hello this is tweetnumber2 1 2 3 4 5 7'}, auth=oauth, stream=True, timeout=timeout))



with futures.ThreadPoolExecutor(max_workers=100) as executor:
    future_to_url = dict((executor.submit(req, url, 60 ), url)
                         for url in URLS)
    for future in futures.as_completed(future_to_url):
        url = future_to_url[future]
        print ("DM SENT IN")
        print (datetime.now()-startTime)
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

1 个答案:

答案 0 :(得分:4)

考虑一些现有的库,试图简化与requests的并发使用可能是值得的。

来自:http://docs.python-requests.org/en/latest/user/advanced/#blocking-or-non-blocking

  

[..]有很多项目将Requests与Python的异步框架结合起来。两个很好的例子是grequestsrequests-futures

相关问题