当前位置:网站首页>Time to update your tech arsenal in 2020: Asgi vs Wsgi (FastAPI vs Flask)
Time to update your tech arsenal in 2020: Asgi vs Wsgi (FastAPI vs Flask)
2022-08-08 13:43:00 【User 9127725】
那么到底啥是Wsgi,什么又是Asgi,放心,不扯CGI,Do not talk about various abstract concepts,简单粗暴理解:
Wsgiis the synchronous communication service specification,Client requests a service,and wait for the service to finish,only when it receives the result of the service,It will continue to work.当然了,Can define a timeout,If the service is not completed within the stipulated time,the call fails,The caller continues to work.
WsgiSimple working principle diagram:
简单实现:
#WSGI example
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
return b'Hello, Wsgi\n'
Asgiis the asynchronous communication service specification.Client initiates service call,但不等待结果.The caller continues its work immediately,并不关心结果.If the caller is interested in the result,There are some mechanisms that allow it to be returned by the callback method at any time.
AsgiSimple working principle diagram:
简单实现:
#Asgi example
async def application(scope, receive, send):
event = await receive()
...
await send({"type": "websocket.send", ...})
简单总结一下:Asgi是异步的,Wsgi是同步的,而基于Wsgi的Flask是同步框架,基于Asgi的FastAPI是异步框架,就这么简单,So what is the difference between a synchronous framework and an asynchronous framework??为什么要把Flask换成FastAPI?
Don't rely on slaps on the forehead、nor hearsay、人云亦云.Those who play technology should speak with data,Arguments are always based on arguments,So let's simply test the performance of the two frameworks,First install the dependent libraries separately.
Flask:
pip install gunicorn
pip install gevent
pip install flask
FastAPI:
pip install fastapi
pip install uvicorn
The first thing we do is,看看Flask和FastAPIHow to deal with from multiple client requests.Especially when the code has efficiency issues(For example, a time-consuming task such as a long database query time),deliberately used heretime.sleep()来模拟耗时任务,为什么不用asyncio呢?因为众所周知的原因:time.sleep是阻塞的.
Flask:
from flask import Flask
from flask_restful import Resource, Api
from time import sleep
app = Flask(__name__)
api = Api(app)
class Root(Resource):
def get(self):
print('睡10秒')
sleep(10)
print('醒了')
return {'message': 'hello'}
api.add_resource(Root, '/')
if __name__ == "__main__":
app.run()
FastApi:
import uvicorn
from fastapi import FastAPI
from time import sleep
app = FastAPI()
@app.get('/')
async def root():
print('睡10秒')
sleep(10)
print('醒了')
return {'message': 'hello'}
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
分别启动服务
Flask:python3 manage.py
FastAPI:uvicorn manage:app --reload
at the same time,Open multiple browsers,Concurrently request the home page separately .
Flask:http://localhost:5000
FastAPI:http://localhost:8000
Observe the spooling result:
Flask:
FastAPI:
可以看到,the same four requests,Flaskblocked first40秒,然后依次返回结果,FastAPIIt is to return directly after the first block,这代表了在FastAPIAn event queue is blocked in,证明FastAPI是异步框架,而在Flask中,The request may be running in a new thread.将所有CPUBound tasks moved to separate processes,所以在FastAPI的例子中,just in the event loopsleep(So the asynchronous framework is best not to use heretime.sleep而是asyncio.sleep).在FastAPI中,异步运行IO绑定的任务.
Of course this doesn't mean too many problems,We continue to use the well-knownApacheBenchTest the two frameworks separately.
一共设置5000个请求,QPS是100(Please forgive my poor machine).
ab -n 5000 -c 100 http://127.0.0.1:5000/
ab -n 5000 -c 100 http://127.0.0.1:8000/
here to be fair,Flask配合Gunicorn服务器,开3个worker,FastAPI配合Uvicorn服务器,同样开3个worker.
Flask压测结果:
liuyue:mytornado liuyue$ ab -n 5000 -c 100 http://127.0.0.1:5000/
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking 127.0.0.1 (be patient)
Completed 500 requests
Completed 1000 requests
Completed 1500 requests
Completed 2000 requests
Completed 2500 requests
Completed 3000 requests
Completed 3500 requests
Completed 4000 requests
Completed 4500 requests
Completed 5000 requests
Finished 5000 requests
Server Software: gunicorn/20.0.4
Server Hostname: 127.0.0.1
Server Port: 5000
Document Path: /
Document Length: 28 bytes
Concurrency Level: 100
Time taken for tests: 4.681 seconds
Complete requests: 5000
Failed requests: 0
Total transferred: 1060000 bytes
HTML transferred: 140000 bytes
Requests per second: 1068.04 [#/sec] (mean)
Time per request: 93.629 [ms] (mean)
Time per request: 0.936 [ms] (mean, across all concurrent requests)
Transfer rate: 221.12 [Kbytes/sec] received
FastAPI压测结果:
liuyue:mytornado liuyue$ ab -n 5000 -c 100 http://127.0.0.1:8000/
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking 127.0.0.1 (be patient)
Completed 500 requests
Completed 1000 requests
Completed 1500 requests
Completed 2000 requests
Completed 2500 requests
Completed 3000 requests
Completed 3500 requests
Completed 4000 requests
Completed 4500 requests
Completed 5000 requests
Finished 5000 requests
Server Software: uvicorn
Server Hostname: 127.0.0.1
Server Port: 8000
Document Path: /
Document Length: 19 bytes
Concurrency Level: 100
Time taken for tests: 2.060 seconds
Complete requests: 5000
Failed requests: 0
Total transferred: 720000 bytes
HTML transferred: 95000 bytes
Requests per second: 2426.78 [#/sec] (mean)
Time per request: 41.207 [ms] (mean)
Time per request: 0.412 [ms] (mean, across all concurrent requests)
Transfer rate: 341.27 [Kbytes/sec] received
显而易见,5000个总请求,Flask花费4.681秒,每秒可以处理1068.04个请求,而FastAPI花费2.060秒,每秒可以处理2426.78个请求.
结语:曾几何时,当人们谈论Pythonframe performance,Do it automatically ,而现在,PythonAsynchronous ecology is undergoing earth-shattering changes,A new framework emerges(Sanic、FastAPI),The old framework is being refactored(Django3.0),Many libraries are also starting to support async(httpx、Sqlalchemy、Mortor).The history of software technology development shows that,Emergence and application of a new technology,often bring profound changes to the field,古语有云:察势者智,Homeopathy wins,驭势者独步天下.所以,Only embrace the future、拥抱新技术、It is right to adapt to the times、可持续发展的道路.
边栏推荐
- HackTheBox | Horizontall
- HackTheBox | Previse
- Implementation of FIR filter based on FPGA (1) - using fir1 function design
- textarea disable drag and drop
- 【C语言】自定义类型详解:结构体、枚举、联合
- qsort 函数的使用及其模拟实现
- 行业领先的界面开发组件DevExpress 8月发布新版——v22.1.4
- MySQL:索引(1)原理与底层结构
- R语言ggpubr包的ggsummarystats函数可视化分面箱图(通过ggfunc参数和facet.by参数设置)、添加描述性统计结果表格、palette参数配置不同水平可视化图像和统计值的颜色
- 基于FPGA的FIR滤波器的实现(1)—采用fir1函数设计
猜你喜欢
HackTheBox | Previse
sample function—R language
深入浅出对话系统——任务型对话系统技术框架
金融行业数智化供应链管理系统:多维度评估分析供应商,赋能智能金融变革
活动报名| StreamNative 受邀参与 ITPUB 在线技术沙龙
【软考 系统架构设计师】软件架构设计⑥ 软件产品线
【黑马早报】巴菲特罕见巨亏近3000亿;周鸿祎回应360不能卸载;三亚倡议酒店不变相提高房价;首个国产抗新冠口服药定价不超300元...
第十二届蓝桥杯《杨辉三角》-二分法
直接选择排序
Three classic topics in C language: three-step flip method, Young's matrix, and tossing and dividing method
随机推荐
HackTheBox | Horizontall
sample函数—R语言
2022-08-03
使用shardingjdbc实现读写分离配置
Photoshop插件-charIDToTypeID-PIStringTerminology.h-不同值的解释及参考-脚本开发-PS插件
基于FPGA的FIR滤波器的实现(1)—采用fir1函数设计
serialize serialize native method
Flink1.15 组件RPC通信过程概览图
Knowledge points and written test questions related to shift operations, bit operations, and logical operations
a += 1 += 1为什么是错的?
又一个千亿市场,冰淇淋也成了创新试验田
changes not staged for commit solution
删库不易,跑路更难
医药行业转型发展,探索数字化供应链升级之道
用 Antlr 重构脚本解释器
指针和数组笔试题解析
KD-SCFNet: More Accurate and Efficient Salient Object Detection Through Knowledge Distillation (ECCV2022)
Three classic topics in C language: three-step flip method, Young's matrix, and tossing and dividing method
论文理解:“Self-adaptive loss balanced Physics-informed neural networks“
php文件上传下载(存放文件二进制到数据库)