Skip to content

Instantly share code, notes, and snippets.

@florimondmanca
Forked from imbolc/httpx_aiohttp.py
Last active August 22, 2024 15:05
Show Gist options
  • Save florimondmanca/fbc85b58e9ce61e74b73df1e42829838 to your computer and use it in GitHub Desktop.
Save florimondmanca/fbc85b58e9ce61e74b73df1e42829838 to your computer and use it in GitHub Desktop.
HTTPX vs aiohttp (over HTTPS)

Usage

  • Generate TLS certificates for localhost:
pip install trustme-cli
trustme-cli
  • Run wrk on each endpoint, eg:
wrk https://localhost:8000/aiohttp/single

Results

aiohttp httpx aiohttp/httpx
single (req/s) 121 48 2.5
client (req/s) 284 221 1.2
client/single 2.3 4.6 0.5
import ssl
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.responses import PlainTextResponse
import httpx
import aiohttp
URL = "https://localhost:8000"
ssl_context = ssl.create_default_context(cafile="client.pem")
session = aiohttp.ClientSession()
client = httpx.AsyncClient(verify="client.pem")
async def index(request):
return PlainTextResponse("world")
async def aiohttp_single(request):
async with aiohttp.ClientSession() as session:
async with session.get(URL, ssl=ssl_context) as r:
return _response(await r.text())
async def aiohttp_session(request):
async with session.get(URL, ssl=ssl_context) as r:
return _response(await r.text())
async def httpx_single(request):
async with httpx.AsyncClient() as client:
r = await client.get(URL)
return _response(r.text)
async def httpx_client(request):
r = await client.get(URL)
return _response(r.text)
def _response(name):
return PlainTextResponse("Hello, " + name)
routes = [
Route("/", endpoint=index),
Route("/aiohttp/single", endpoint=aiohttp_single),
Route("/aiohttp/session", endpoint=aiohttp_session),
Route("/httpx/single", endpoint=httpx_single),
Route("/httpx/client", endpoint=httpx_client),
]
app = Starlette(routes=routes)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
app,
host="localhost",
port=8000,
ssl_keyfile="server.key",
ssl_certfile="server.pem",
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment