Python Flask 高併發部署(簡易)

一、安裝gevent

pip install gevent

二、修改 flask

#! -*- coding:utf-8 -*-
 
from flask import Flask, jsonify
from gevent.pywsgi import WSGIServer #關鍵這個
 
app = Flask(__name__)
 
#這裏的json使用中文key
@app.route("/", methods=['GET', 'POST'])
def index():
    return jsonify({'ret':'hi'})
 
WSGIServer(('127.0.0.1', 5000), app).serve_forever()

三、測試

#! -*- coding:utf-8 -*-
 
import urllib
import json
import time
 
url = 'http://127.0.0.1:5000/'
 
while True:
    t1 = time.time()
    print(t1)

    #並不能保證每一次請求都能返回結果。必需設置timeout
    res = json.loads(urllib.request.urlopen(url, timeout=10).read().decode('utf-8'))
    
    dt = time.time() - t1
    print("耗時"+"%.2f秒" % dt)
    print(res)
    time.sleep(0.01)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章