1. 程式人生 > >Python 非同步 asyncio aiohttp和uvloop加速

Python 非同步 asyncio aiohttp和uvloop加速

服務端

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())