Created
June 25, 2023 17:20
-
-
Save linnil1/55a4f5798592ad44aab73d3c6520fdcc to your computer and use it in GitHub Desktop.
httpx is easier to use than aiohttp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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