带有Python请求的异步请求 - python

我尝试了requests library文档中提供的python示例。

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

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

参考方案

注意

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

我已经留下了这个答案,以反映原始问题,该问题与使用请求<v0.13.0有关。

要使用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)
    

    Requests.get无法与&字符一起使用 - python

    我正在使用以下网址进行request.get调用:https://api.datasource.com/apps/ios/ranking?countries=NL&categories=Overall > Kids > 5 & Under&device=ios&ranks=1000 我收到"categor…

    Python-使用请求时发布请求失败 - python

    使用外壳程序时,我可以通过运行以下命令成功创建新用户curl --user administrator:pasword "Content-Type: application/json" https://localhost:8080/midpoint/ws/rest/users -d @user.json但是,当我尝试使用请求在python…

    在返回'Response'(Python)中传递多个参数 - python

    我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

    Python exchangelib在子文件夹中读取邮件 - python

    我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

    python JSON对象必须是str,bytes或bytearray,而不是'dict - python

    在Python 3中,要加载以前保存的json,如下所示:json.dumps(dictionary)输出是这样的{"('Hello',)": 6, "('Hi',)": 5}当我使用json.loads({"('Hello',)": 6,…