Skip to content

Instantly share code, notes, and snippets.

@luliangce
Created March 3, 2021 10:37
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 luliangce/9f9ce635a62f4b60e3109177630b0a30 to your computer and use it in GitHub Desktop.
Save luliangce/9f9ce635a62f4b60e3109177630b0a30 to your computer and use it in GitHub Desktop.
在flask使用异步
import asyncio
import time
import httpx
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def hello_world():
start = time.time()
for i in range(10):
response = httpx.get('https://www.baidu.com')
print(response)
return jsonify(elp=str(time.time() - start)) # 0.75
async def fetch(url: str) -> str:
async def task_handler(url):
async with httpx.AsyncClient() as client:
response = await client.get(url)
print(response)
tasks = []
for i in range(10):
tasks.append(task_handler(url))
await asyncio.gather(*tasks)
@app.route('/async')
def async_hello():
start = time.time()
asyncio.run(fetch('https://www.baidu.com'))
return jsonify(elp=str(time.time() - start)) #0.18
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment