Python 协程池,异步IO非阻塞式,http 请求

先写个 Flask demo

import time
from flask import Flask
app = Flask(__name__)

@app.route('/<id>')
def hello(id):
    time.sleep(2)
    return 'Hello, World!: %s' % id

if __name__ == '__main__':
    app.run()

协程请求


import asyncio
import timeit
from concurrent.futures import ThreadPoolExecutor


def async_pool(pool_size):
    def async_func(func):
        async def wrapper(*args, **kwargs):
            loop = asyncio.get_running_loop()
            with ThreadPoolExecutor(max_workers=pool_size) as executor:
                result = await loop.run_in_executor(executor, func, *args, **kwargs)
            return result

        return wrapper

    return async_func


import requests


@async_pool(5)
def get(url):
    response = requests.get(url)
    return response.text


async def main():
    urls = [
        'http://127.0.0.1:5000/1',
        'http://127.0.0.1:5000/2',
        'http://127.0.0.1:5000/3',
        'http://127.0.0.1:5000/4',
    ]
    tasks = [asyncio.create_task(get(url)) for url in urls]
    results = await asyncio.gather(*tasks)
    return results



if __name__ == '__main__':
    rsp = asyncio.run(main())
    print(rsp)
    print("运行时间为: ", timeit.timeit(lambda: asyncio.run(main()), number=1), "秒")

终端输出

['Hello, World!: 1', 'Hello, World!: 2', 'Hello, World!: 3', 'Hello, World!: 4']
运行时间为:  2.0162846040000004 秒

posted @ 2023-06-09 10:24  kitai  阅读(35)  评论(0)    收藏  举报