1. 程式人生 > >[bigdata-053] flask開發和高併發部署

[bigdata-053] flask開發和高併發部署

Flask的web server,可以以python3 myflask.py的方式執行,但這種方式不能用於生產環境,不穩定,比如說,每隔十幾分鍾,有一定概率遇到連線超時無返回的情況。

有各種方式部署。比較簡單的方式,就是用gevent部署。

1. pip3 install gevent

2. myflask.py如下

#!/usr/bin/env python3
#! -*- coding:utf-8 -*-

from flask import Flask, jsonify
from gevent.wsgi import WSGIServer

app = Flask(__name__)

#這裡的json使用中文key
@app.route("/", methods=['GET', 'POST'])
def index():
    return jsonify({'ret':'hi'})

WSGIServer(('0.0.0.0', 8889), app).serve_forever()


3. 測試程式碼如下:

#!/usr/bin/env python3
#! -*- coding:utf-8 -*-

import urllib
import json
import time

url = 'http://localhost:6666/'

while True:
    t1 = time.time()
    print(t1)
    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)

4. 但是,這並不能保證每一次請求都能返回結果。必需設定timeout,失敗後要重試。web http服務不是100%就能得到結果的。