Skip to content

Instantly share code, notes, and snippets.

@linnil1
Created June 25, 2023 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linnil1/55a4f5798592ad44aab73d3c6520fdcc to your computer and use it in GitHub Desktop.
Save linnil1/55a4f5798592ad44aab73d3c6520fdcc to your computer and use it in GitHub Desktop.
httpx is easier to use than aiohttp
import time
import uuid
import asyncio
import httpx
import aiohttp
url = "http://localhost:8080/"
async def query(client, user_id, text):
r = await client.post(url + user_id, json={"text": text})
data = r.json()
if asyncio.iscoroutine(data):
return await data
else:
return data
async def main(method, num=100):
users = [str(uuid.uuid4()) for _ in range(num)]
if method == "httpx":
client = httpx.AsyncClient(timeout=None)
elif method == "aiohttp":
connector = aiohttp.TCPConnector(limit=None)
client = aiohttp.ClientSession(connector=connector)
async with client:
data = await asyncio.gather(*[query(client, u, "test") for u in users])
# print(data)
async def mmain(method):
await asyncio.gather(*[main(method, num=100) for _ in range(10)])
now = time.time()
# asyncio.run(main("httpx"))
asyncio.run(mmain("httpx"))
now, old = time.time(), now
print(now - old)
# asyncio.run(main("aiohttp"))
asyncio.run(mmain("aiohttp"))
now, old = time.time(), now
print(now - old)
# aiohttp.client_exceptions.ClientOSError: [Errno 104] Connection reset by peer
# python3 test.py
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/<user_id>", methods=["POST"])
async def callback(user_id):
return jsonify({"name": user_id, "data": request.json})
# gunicorn --workers=1 -b 0.0.0.0:8080 --worker-connections 8192 test_web:app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment