d********g 发帖数: 7458 | 1 我们的网站后台遇到这么个问题,大概可以抽象成这样子:
import requests
for i in xrange(10):
response[i] = requests.post(API_URL,data={func(i)},timeout=30, verify=False);
# next step, processing response[]
API_URL是国内的API接口,因为连接速度比较慢,所以timeout设成了30来确保连通率。
目前的问题是10次循环下来,因为是阻塞式的,时间会拖得比较长。假设每次requests
平均需要15秒,一共就要150秒。
请问有什么异步的办法,能够同时并发这10次连接请求,然后等所有的response[i]全
收集齐了再做下一步? | c***d 发帖数: 996 | 2 pycurl curlmulti?
False);
率。
requests
【在 d********g 的大作中提到】 : 我们的网站后台遇到这么个问题,大概可以抽象成这样子: : import requests : for i in xrange(10): : response[i] = requests.post(API_URL,data={func(i)},timeout=30, verify=False); : # next step, processing response[] : API_URL是国内的API接口,因为连接速度比较慢,所以timeout设成了30来确保连通率。 : 目前的问题是10次循环下来,因为是阻塞式的,时间会拖得比较长。假设每次requests : 平均需要15秒,一共就要150秒。 : 请问有什么异步的办法,能够同时并发这10次连接请求,然后等所有的response[i]全 : 收集齐了再做下一步?
| d******e 发帖数: 2265 | 3 gevent
False);
率。
requests
【在 d********g 的大作中提到】 : 我们的网站后台遇到这么个问题,大概可以抽象成这样子: : import requests : for i in xrange(10): : response[i] = requests.post(API_URL,data={func(i)},timeout=30, verify=False); : # next step, processing response[] : API_URL是国内的API接口,因为连接速度比较慢,所以timeout设成了30来确保连通率。 : 目前的问题是10次循环下来,因为是阻塞式的,时间会拖得比较长。假设每次requests : 平均需要15秒,一共就要150秒。 : 请问有什么异步的办法,能够同时并发这10次连接请求,然后等所有的response[i]全 : 收集齐了再做下一步?
| k****0 发帖数: 7 | 4 use asyncio (python 3) or trollius (python 2)
call requests using loop.run_in_executor(None, requests.post, ....), which
returns a promise so it is not blocking.
Alternatively you can use grequest (basically requests+gevents), but gevents
will monkey patch all the network modules to make it non-blocking, which
sometimes breaks stuff. | s********k 发帖数: 6180 | 5 用twsited?或者直接自己写个unblock的coroutine?
False);
率。
requests
【在 d********g 的大作中提到】 : 我们的网站后台遇到这么个问题,大概可以抽象成这样子: : import requests : for i in xrange(10): : response[i] = requests.post(API_URL,data={func(i)},timeout=30, verify=False); : # next step, processing response[] : API_URL是国内的API接口,因为连接速度比较慢,所以timeout设成了30来确保连通率。 : 目前的问题是10次循环下来,因为是阻塞式的,时间会拖得比较长。假设每次requests : 平均需要15秒,一共就要150秒。 : 请问有什么异步的办法,能够同时并发这10次连接请求,然后等所有的response[i]全 : 收集齐了再做下一步?
| d********g 发帖数: 10550 | 6 gevent,或者简单点tornado:
http://www.tornadoweb.org/en/stable/gen.html
False);
率。
requests
【在 d********g 的大作中提到】 : 我们的网站后台遇到这么个问题,大概可以抽象成这样子: : import requests : for i in xrange(10): : response[i] = requests.post(API_URL,data={func(i)},timeout=30, verify=False); : # next step, processing response[] : API_URL是国内的API接口,因为连接速度比较慢,所以timeout设成了30来确保连通率。 : 目前的问题是10次循环下来,因为是阻塞式的,时间会拖得比较长。假设每次requests : 平均需要15秒,一共就要150秒。 : 请问有什么异步的办法,能够同时并发这10次连接请求,然后等所有的response[i]全 : 收集齐了再做下一步?
| d********g 发帖数: 10550 | 7 non-blocking的coroutine现成的tornado就有:
http://www.tornadoweb.org/en/stable/gen.html
【在 s********k 的大作中提到】 : 用twsited?或者直接自己写个unblock的coroutine? : : False); : 率。 : requests
|
|