001. Flask + Hypercorn 搭建 HTTP2 服務(wù)器
框架介紹
Flask 是一個(gè)輕量級的 Python Web 框架,Hypercorn 是一個(gè)使用 asyncio 的 Python WSGI 服務(wù)器??梢允褂眠@兩個(gè)工具來搭建一個(gè)支持 HTTP2 的 Web 服務(wù)器。
環(huán)境介紹
系統(tǒng):Windows 10
Python:3.10.0
瀏覽器:Microsoft Edge(版本 107.0.1418.35)
搭建步驟
首先,需要安裝 Flask 和 Hypercorn:
然后,你可以創(chuàng)建一個(gè) Flask 應(yīng)用來處理 HTTP 請求。例如,可以使用以下代碼創(chuàng)建一個(gè)簡單的 Flask 應(yīng)用:
接下來,你可以使用 Hypercorn 來啟動你的 Flask 應(yīng)用。例如,可以使用以下代碼啟動服務(wù)器:
此時(shí)通過瀏覽器訪問?
來訪問你的?Flask 應(yīng)用了,你將看到一個(gè) HelloWorld 界面。http://127.0.0.1:443
?

打開控制臺的網(wǎng)絡(luò)面板,勾選標(biāo)題選項(xiàng)的協(xié)議,查看當(dāng)前HTTP協(xié)議發(fā)現(xiàn)并未啟用HTTP2。

仍為HTTP1.1協(xié)議
這是因?yàn)?,你需要在服?wù)器上安裝 SSL 證書才能啟用 HTTP2。你可以使用 Let's Encrypt 或其他方式來獲取 SSL 證書(以后我會寫一篇文章專門講解)。然后,可以使用以下代碼來配置 Hypercorn:
這樣,你就可以通過瀏覽器訪問?
來訪問你的?Flask 應(yīng)用了,效果如下:https://127.0.0.1
?


已啟用HTTP2
附:SSL Error處理
使用Hypercorn時(shí),在與客戶端進(jìn)行 SSL 握手期間,可能會引發(fā) SSLError 。這些錯誤由 asyncio 的?Event Loop 處理,并通過 Loop 的異常處理程序報(bào)告(通常直接拋出)。要忽略(或處理)這些錯誤,需要配置 Event?Loop 的異常處理程序。
關(guān)于這個(gè)問題,Hypercorn 作者?pgjones 回答如下:
This is a Hypercorn issue - I don't think it causes any noticeable problems though? As I understand it Hypercorn tries to send information after the socket has closed and things then error and Hypercorn restarts on the next request. If it is problematic try using Uvicorn until this is fixed.

延伸閱讀
為什么使用HTTP2?:https://www.cnblogs.com/jesse131/p/11529931.html
asyncio 事件循環(huán)錯誤處理API:https://docs.python.org/zh-cn/3/library/asyncio-eventloop.html#error-handling-api
Hypercorn 文檔地址:https://hypercorn.readthedocs.io/en/latest/index.html
Hypercorn?Github 地址:https://github.com/pgjones/hypercorn