带有 Python 请求的异步请求

新手上路,请多包涵

我尝试了 python 请求库 文档中提供的示例。

使用 async.map(rs) ,我得到响应代码,但我想获取请求的每个页面的内容。例如,这不起作用:

 out = async.map(rs)
print out[0].content

原文由 trbck 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 865
2 个回答

笔记

以下答案 不适 用于请求 v0.13.0+。编写此问题后,异步功能已移至 grequests 。但是,您可以将 requests 替换为下面的 grequests ,它应该可以工作。

我留下这个答案是为了反映关于使用 requests < v0.13.0 的原始问题。


要使用 async.map 异步 执行多项任务,您必须:

  1. 为每个对象(您的任务)定义一个函数
  2. 在您的请求中将该函数添加为事件挂钩
  3. 在所有请求/操作的列表中调用 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)

原文由 Jeff 发布,翻译遵循 CC BY-SA 3.0 许可协议

async 现在是一个独立的模块: grequests

请参阅此处: https ://github.com/kennethreitz/grequests

还有: 通过 Python 发送多个 HTTP 请求的理想方法?

安装:

 $ pip install grequests

用法:

建立一个堆栈:

 import grequests

urls = [
    'http://www.heroku.com',
    'http://tablib.org',
    'http://httpbin.org',
    'http://python-requests.org',
    'http://kennethreitz.com'
]

rs = (grequests.get(u) for u in urls)

发送堆栈

grequests.map(rs)

结果看起来像

[<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]

grequests 似乎没有为并发请求设置限制,即当多个请求被发送到同一台服务器时。

原文由 outforawhile 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题