python多进程gevent,Flask gevent multiprocess WSGI,Flask gevent 多进程WSGI,Flask多进程gevent。
题外话:Flask,Instagram据说扛住了上亿日活,以前是Django。其是一个非常优秀的web service 框架,简洁灵活,可以利用大量的第三方组件和模块来快速开发。
如今,Instagram 的总注册用户达到 30 亿,月活用户超过 7 亿 (作为对比,微信最新披露的月活跃用户为 9.38 亿)。而令人吃惊的是,这么高的访问量背后,竟完全是由以速度“慢”著称的 Python + Django 支撑。
时至今日,即使已经拥有超过 30 亿的注册用户。Instagram 仍然是 Python 和 Django 的重度使用者。Instagram 的工程师 Hui Ding 说到: 『一直到用户 ID 已经超过了 32bit int 的限额(约为 20 亿),Django 本身仍然没有成为我们的瓶颈所在。』
flask + gevent + multiprocess + wsgi简介
常常大家都是用gunicorn来解决flask后端部署并发的问题, 然而觉得自启多进程是为更优雅的高并发方式。这样就不需要gunicorn了。也没有额外的第三方部署工作,于是有了以下flask + gevent + multiprocess + wsgi的测试
flask + gevent + multiprocess + wsgi程序代码cppla.py
Python
# coding: utf-8
# code by https://cpp.la, 2020-04-20
# flask + gevent + multiprocess + wsgi
from gevent import monkey
from gevent.pywsgi import WSGIServer
monkey.patch_all()
import datetime
import os
from multiprocessing import cpu_count, Process
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/cppla", methods=['GET'])
def function_benchmark():
return jsonify(
{
"status": "ok",
"time": datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
"pid": os.getpid()
}
), 200
def run(MULTI_PROCESS):
if MULTI_PROCESS == False:
WSGIServer(('0.0.0.0', 8080), app).serve_forever()
else:
mulserver = WSGIServer(('0.0.0.0', 8080), app)
mulserver.start()
def server_forever():
mulserver.start_accepting()
mulserver._stop_event.wait()
for i in range(cpu_count()):
p = Process(target=server_forever)
p.start()
if __name__ == "__main__":
# 单进程 + 协程
run(False)
# 多进程 + 协程
# run(True)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40