zoukankan      html  css  js  c++  java
  • Python-http请求

    # -*- coding: utf-8 -*-
    
    import time
    import requests
    import httpx
    import aiohttp
    import asyncio
    
    
    url = 'https://www.baidu.com/'
    
    
    # ##################################### 时间装饰器 ###################################################
    
    
    def wrapper(func):
        def inner(*args, **kwargs):
            start_time = time.time()
            res = func(*args, **kwargs)
            print(time.time() - start_time)
            return res
        return inner
    
    # ##################################### 同步请求 ###################################################
    
    
    @wrapper
    def requests_sync_test(count=100):
        session = requests.Session()
        for _ in range(count):
            res = session.get(url=url)
            print(res.json())
    
    
    @wrapper
    def http_x_sync_test(count=100):
        for _ in range(count):
            res = httpx.get(url=url)
            print(res.json())
    
    
    # ##################################### 异步请求 ###################################################
    
    
    async def request(client):
        resp = await client.get(url=url)
        result = resp.json()
        print(result)
    
    
    @wrapper
    async def http_x_async_test(count=100):
        async with httpx.AsyncClient() as client:
            task_list = []
            for _ in range(count):
                task = asyncio.create_task(
                    request(client=client)
                )
                task_list.append(task)
            await asyncio.gather(*task_list)
    
    
    @wrapper
    async def aio_http_async_text(count=100):
        """废弃|太慢"""
        async with aiohttp.ClientSession() as client:
            for _ in range(count):
                res = await client.get(url=url)
                res_json = await res.json()
                print(res_json)
    
    
    if __name__ == '__main__':
        requests_sync_test(count=10)
        # asyncio.run(http_x_async_test(10))
        # asyncio.run(aio_http_async_text(10))

    参考:https://www.pythonf.cn/read/36407

  • 相关阅读:
    如何实现抢红包,100元6个用户抢,每个人抢的红包金额至少为10?
    秒杀项目中核心功能的实现
    如何判断一个单链表有环?
    Redis入门
    拼车
    微服务架构SpringCloud的理解
    Linux:移动当前目录的前N个文件到目标文件夹下
    Linux统计文件目录下文件的数目命令
    Python-目标检测-将xml文件转换成.txt文件
    Linux的命令合集
  • 原文地址:https://www.cnblogs.com/52-qq/p/14143899.html
Copyright © 2011-2022 走看看