標籤:https python flask gunicorn
1、安裝pyOpenSSL模組
pip install pyOpenSSL
如果flask是在python3環境下安裝的,記得切換到python3的虛擬環境
2、上傳認證檔案到項目根目錄,我這裡使用的是公網認證檔案,也可以自己手動生產自我簽署憑證,網上有很多樣本,就不列舉了。
3、配置https訪問,可以通過三種方法實現
3.1、直接使用flask架構內建的伺服器,修改代碼實現Https訪問
from flask import Flaskapp = Flask(__name__)@app.route(‘/‘)def index(): return ‘hello world‘if __name__ == ‘__main__‘: app.run(‘0.0.0.0‘,port=8100,ssl_context=(‘./server.pem‘,‘./server.key‘))
啟動flask
python myapp.py * Running on https://0.0.0.0:8100/ (Press CTRL+C to quit)
3.2、使用gunicorn實現Https訪問,代碼中就可以不用添加認證檔案配置了
from flask import Flaskapp = Flask(__name__)@app.route(‘/‘)def index(): return ‘hello world‘if __name__ == ‘__main__‘: app.run()
使用gunicorn啟動服務,添加指定認證檔案參數
gunicorn -w4 -b0.0.0.0:8000 --certfile=server.pem --keyfile=server.key myapp:app[2017-08-22 10:47:34 +0800] [23118] [INFO] Starting gunicorn 19.7.1[2017-08-22 10:47:34 +0800] [23118] [INFO] Listening at: https://0.0.0.0:8000 (23118)[2017-08-22 10:47:34 +0800] [23118] [INFO] Using worker: sync[2017-08-22 10:47:34 +0800] [23121] [INFO] Booting worker with pid: 23121[2017-08-22 10:47:34 +0800] [23122] [INFO] Booting worker with pid: 23122[2017-08-22 10:47:34 +0800] [23123] [INFO] Booting worker with pid: 23123[2017-08-22 10:47:34 +0800] [23124] [INFO] Booting worker with pid: 23124
服務啟動後,通過https就可以訪問到了
3.3、通過nginx代理,在Proxy 伺服器上添加認證檔案
server{ listen 443; server_name abc.abc.com; ssl on; ssl_certificate server.pem; ssl_certificate_key server.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!RC4:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!EXP:+MEDIUM; ssl_prefer_server_ciphers on; location / { proxy_connect_timeout 3; proxy_send_timeout 30; proxy_read_timeout 30; proxy_pass http://*.*.*.*:5000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
這是我實現的三種方式,其他小夥伴還有另外的方法,請指教,謝謝!
知行辦公,專業隨處工作平台 https://zx.naton.cn/
【總監】十二春秋之,[email protected];
【Master】zelo,[email protected];
【運營】狼行天下,[email protected];
【產品設計】流浪貓,[email protected];
【體驗設計】兜兜,[email protected];
【iOS】淘碼小工,[email protected];iMcG33K,[email protected];
【Android】人猿居士,[email protected];思路的頓悟,[email protected];
【java】首席工程師MR_W,[email protected];
【測試】土鏡問道,[email protected];
【資料】喜樂多,[email protected];
【安全】保密,你懂的。
本文出自 “踐行者” 部落格,請務必保留此出處http://bluemooder.blog.51cto.com/12822812/1958267
python https實現方法