• Python 中的异步请求



    今天我们来学习一下异步请求; 这个讨论将引出代码示例,看看我们如何在 Python 中编写异步请求。


    Python 中的异步请求

    异步请求是我们系统的核心。 我们可以这样想:

    当用户加载我们的网站(网站或网络应用程序)时,用户立即开始看到内容。 但它还没有完全准备好。 因此,当用户继续与页面交互时,我们在后台异步加载内容。

    这些请求在等待响应时不会阻止后续代码的执行。 这意味着在处理请求时其他代码可以继续运行。

    在处理可能需要一些时间才能响应的外部资源(例如 API 调用)时,它会很有帮助。 它还可以使您的代码响应更快,因为 UI 可以在处理请求时继续更新。


    在 Python 中使用异步请求的重要性

    异步请求是提高 Python 应用程序性能的好方法。 当发出请求时,Python解释器可以在处理请求的同时继续执行其他代码。

    它可以显着提高速度,特别是对于发出大量请求的应用程序。 但是,以下是使用异步请求时需要记住的一些要点。

    1. 首先,我们必须避免同时提出太多请求。 如果我们提出太多请求,口译员可能会不知所措并放慢速度。
    2. 其次,我们需要做好处理错误的准备。 如果请求失败,解释器将无法继续执行代码。

    总的来说,异步请求是提高 Python 应用程序性能的一个很好的工具。 但是,小心使用它; 它们可以帮助我们的应用程序运行得更快、更流畅。


    用 Python 编写异步请求的最简单方法

    使用 asyncio 模块可以轻松地发出异步请求。 此外,python的asyncio库提供了编写异步代码的工具。 例如,我们可以使用 asyncio.sleep() 暂停协程,使用 asyncio.wait() 等待协程完成。

    要编写异步请求,我们需要首先创建一个协程。 我们可以使用 asyncio.ensure_future() 函数来做到这一点。 一旦我们有了协程,我们就可以使用 asyncio.sleep() 函数来暂停它,并使用 asyncio.wait() 函数来等待它完成。


    在 Python 中处理异步请求

    首先,如果我们想在Python中运行异步请求,那么您应该使用以下命令安装aiohttp的python库。

    pip install aiohttp
    
    • 1

    我们可以使用异步请求来提高 Python 应用程序的性能。 通过并行发出请求,我们可以大大加快这个过程。

    在 Python 中有一些不同的方法来处理异步请求。 最流行的是 asyncio 库。 这个库提供了处理异步请求的强大工具。

    另一个流行的选择是 grequests 库。 这个库比 asyncio 使用起来更简单一些,但它可以同样有效。

    我们选择哪个选项将取决于我们的具体需求。 但无论我们选择哪种方式,我们都可以通过异步请求看到显着的性能提升。

    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    异步请求所需的 Python 库

    我们可以使用大量 Python 库来发出异步请求。 最受欢迎的是 aiohttp 和 asyncio。

    用于异步请求的 aiohttp 库

    aiohttp 是一个使我们能够发出异步 HTTP 请求的库。 它建立在 asyncio 之上,并提供了一个简单的接口来发出 HTTP 请求。

    用于异步请求的 asyncio 库

    asyncio 是一个支持 Python 异步编程的库。 它使我们能够编写异步代码,并使使用支持 asyncio 的库变得容易。

    aiohttp 和 asyncio 都可以在 PyPI 上使用,并且可以使用 pip 安装。

    import asyncio
    import aiohttp
    import json
    
    from text_api_config import apikey
    
    • 1
    • 2
    • 3
    • 4
    • 5

    异步请求与常规请求

    我们可以向服务器发出两种类型的请求:异步请求和常规请求。 当用户仍然与页面交互时,异步请求是在后台发出的。 典型的请求是在页面加载时发出的。

    异步请求通常比常规请求更快、更高效,因为它们不会阻止页面加载。 然而,它们的实现可能更加复杂,并且并非所有浏览器都始终支持它们。

    代码示例:

    import requests
    import time
    
    start_time = time.time()
    
    for number in range(1, 151):
        url = f'https://pokeapi.co/api/v2/pokemon/{number}'
        resp = requests.get(url)
        pokemon = resp.json()
        print(pokemon['name'])
    
    print("--- %s seconds ---" % (time.time() - start_time))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    输出:

    bulbasaur
    ivysaur
    venusaur
    ....
    dragonair
    dragonite
    mewtwo
    --- 68.17992424964905 seconds
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Python 中的 asyncio 模块

    asyncio 是 Python 中用于并发编程的模块。 它提供了一个用于管理并发线程、任务和事件的框架。 asyncio 用于编写可以同时执行多个任务的程序。

    asyncio 基于协程的概念。 协程是一个可以暂停执行并将控制权交还给调用者的函数。 它允许多个协程同时运行。

    asyncio 提供了用于管理协程的工具,包括事件循环、任务调度程序和并发数据结构。

    asyncio 是编写并发程序的有效方式。 它易于使用并且可以扩展到大型程序。 asyncio 是需要同时执行多个任务的程序的绝佳选择。

    代码示例:

    import asyncio
    import aiohttp
    import json
    from text_api_config import apikey
    
    async def gather_with_concurrency(n, *tasks):
        semaphore = asyncio.Semaphore(n)
        async def sem_task(task):
            async with semaphore:
                return await task
       
        return await asyncio.gather(*(sem_task(task) for task in tasks))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    Python 中的 aiohttp 模块

    aiohttp 模块是 Python 的异步 HTTP 客户端/服务器。 它基于 asyncio 构建,并提供了一个用于处理 HTTP 的简单 API。

    aiohttp 模块使得在 Python 中使用 HTTP 变得很容易。 它提供了一个简单的 API,可以轻松发送和接收 HTTP 请求和响应。

    aiohttp 模块还提供了一种运行异步 HTTP 服务器的方法。

    import asyncio
    import aiohttp
    import json
    from text_api_config import apikey
    
    async def main():
        conn = aiohttp.TCPConnector(limit=None, ttl_dns_cache=300)
        session = aiohttp.ClientSession(connector=conn)
        urls = [summarize_url, ner_url, mcp_url]
        conc_req = 3
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Python 中的异步请求

    代码示例:

    import queue
    def task1(name, s_queue):
        if s_queue.empty():
            print(f'Task {name} has nothing to do')
        else:
            while not s_queue.empty():
                cnt = s_queue.get()
                total = 0
                for x in range(cnt):
                    print(f'Task {name} is working now.')
                    total += 1
                print(f'Task {name} is working with a total of: {total}')
    def s_async():
        s_queue = queue.Queue()
        for work in [2, 5, 10, 15, 20]:
            s_queue.put(work)
        tasks = [
            (task1, 'Async1', s_queue),
            (task1, 'Async2', s_queue),
            (task1, 'Async3', s_queue)
        ]
        for t, n, q in tasks:
            t(n, q)
    if __name__ == '__main__':
        s_async()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    输出:

    Task Async1 is running now.
    Task Async1 is running with a total of: 2
    Task Async1 is running now
    ...
    Task Async1 is running now.
    Task Async1 is running with a total of: 5
    Task Async1 is running now
    ...
    Task Async1 is running now.
    Task Async1 is running with a total of: 10
    Task Async1 is running now
    ...
    Task Async1 is running now.
    Task Async1 is running with a total of: 15
    Task Async1 is running now
    ...
    Task Async1 is running now.
    Task Async1 is running with a total of: 20
    Task Async3 has nothing to do
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
  • 相关阅读:
    Spring使用(二)
    SpringDataJpa(三)
    数据结构-堆排序Java实现
    GO语言-栈的应用-表达式求值
    java之你真正了解抽象类和接口嘛?
    红黑树及其相关操作(一遍包会)
    基于java的学生信息管理系统
    洛谷P4345 超能粒子炮·改
    PHP 生成 PDF文件
    freeipa server副本同步中断,两主节点数据不一致
  • 原文地址:https://blog.csdn.net/fengqianlang/article/details/133378045