zoukankan      html  css  js  c++  java
  • Python学习---IO的异步[gevent+Grequests模块]

    安装gevent模块

    pip3 install gevent
    

    Gevent实例

    import gevent
    import requests
    from gevent import monkey
    # socket发送请求以后就会进入等待状态,gevent更改了这个机制
    # socket.setblocking(False)  -->发送请求后就不会等待服务器响应
    monkey.patch_all()  # 找到内置的socket并更改为gevent自己的东西
    
    def fetch_async(method, url, req_kwargs):
        print(method, url, req_kwargs)
        response = requests.request(method=method, url=url, **req_kwargs)
        print(response.url, response.content)
    
    # ##### 发送请求 #####
    gevent.joinall([
        # 这里spawn是3个任务[实际是3个协程],每个任务都会执行fetch_async函数
        gevent.spawn(fetch_async, method='get', url='https://www.python.org/', req_kwargs={}),
        gevent.spawn(fetch_async, method='get', url='https://www.yahoo.com/', req_kwargs={}),
        gevent.spawn(fetch_async, method='get', url='https://github.com/', req_kwargs={}),
    ])

    image

    Gevent也是支持协程池

    ##### 发送请求(协程池控制最大协程数量) #####
    # 也可以理解为先最大发送2个请求,2个请求结束后发送第三个请求
    from gevent.pool import Pool
    pool = Pool(2)  # 最多执行2个协程序,None表示不设置限制
    gevent.joinall([
        pool.spawn(fetch_async, method='get', url='https://www.python.org/', req_kwargs={}),
        pool.spawn(fetch_async, method='get', url='https://www.yahoo.com/', req_kwargs={}),
        pool.spawn(fetch_async, method='get', url='https://www.github.com/', req_kwargs={}),
    ])

    Grequests

    安装grequests

    pip3 install grequests
    

    grequests实际上就是封装了gevent里面的方法,然后配合requests实现异步的IO

    grequests = gevent + request

    grequests.map() 内部实现

    image

    Grequest实例

    import grequests  # 实际上就是requests + gevent
    request_list = [
        # 发送get请求
        grequests.get('https://www.baidu.com/', timeout=10.001),
        grequests.get('https://www.taobao.com/'),
        grequests.get('https://hao.360.cn/')
    ]
    # ##### 执行并获取响应列表 #####
    response_list = grequests.map(request_list)  # 实际上内部循环执行gevent内部的joinall()方法
    print(response_list)
    
    # ##### 执行并获取响应列表(处理异常) #####
    # def exception_handler(request, exception):
    # print(request,exception)
    #     print("Request failed")
    
    # response_list = grequests.map(request_list, exception_handler=exception_handler)
    # print(response_list)

    image

  • 相关阅读:
    对象实例化内存布局与访问定位
    方法区

    本地方法栈
    本地方法接口
    虚拟机栈
    程序计数器
    运行时数据区概述及线程
    自学》2.网页弹窗计算商品价格
    自学》1.用网站发邮件
  • 原文地址:https://www.cnblogs.com/ftl1012/p/9424822.html
Copyright © 2011-2022 走看看