Python 异步 asyncio aiohttp和uvloop加速

版权声明:未经本人同意,禁止转载! https://blog.csdn.net/TianPingXian/article/details/82383323

服务端

from aiohttp import web


async def handle(request):
    name = request.match_info.get('name', 'Anonymous')
    text = 'Hello,{}'.format(name)
    print('service : {}'.format(name))
    return web.Response(text=text)

app = web.Application()
app.add_routes([
    web.get('/', handle),
    web.get('/{name}', handle)
])
web.run_app(app)

代理端

import aiohttp
import asyncio

import uvloop


async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()


async def main():
    async with aiohttp.ClientSession() as session:
        url = 'http://localhost:8080/{}'
        for i in range(10000):
            html = await  fetch(session, url.format(i))
            print(html)


asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

猜你喜欢

转载自blog.csdn.net/TianPingXian/article/details/82383323