python requests 异步调用_带有Python请求的异步请求
小編典典
注意
下面的答案是不適用于請求v0.13.0 +。編寫此問題后,異步功能已移至grequests。但是,你可以將其替換requests為grequests下面的內容,它應該可以工作。
我已經留下了這個答案,以反映原始問題,即有關使用請求
要async.map異步執行多個任務,你必須:
為每個對象定義一個函數(你的任務)
將該功能添加為請求中的事件掛鉤
調用async.map所有請求/操作的列表
例:
from requests import async
# If using requests > v0.13.0, use
# from grequests import async
urls = [
'http://python-requests.org',
'http://httpbin.org',
'http://python-guide.org',
'http://kennethreitz.com'
]
# A simple task to do to each response object
def do_something(response):
print response.url
# A list to hold our things to do via async
async_list = []
for u in urls:
# The "hooks = {..." part is where you define what you want to do
#
# Note the lack of parentheses following do_something, this is
# because the response will be used as the first argument automatically
action_item = async.get(u, hooks = {'response' : do_something})
# Add the task to our list of things to do via async
async_list.append(action_item)
# Do our list of things to do via async
async.map(async_list)
2020-02-17
總結
以上是生活随笔為你收集整理的python requests 异步调用_带有Python请求的异步请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python上机报告出现的问题和解决方法
- 下一篇: 数据结构哪本书比较好_东莞工厂电动伸缩门