Created
March 3, 2021 10:37
-
-
Save luliangce/9f9ce635a62f4b60e3109177630b0a30 to your computer and use it in GitHub Desktop.
在flask使用异步
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 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