- Python Falcon 教程
- Python Falcon - 首頁
- Python Falcon - 簡介
- Python Falcon - 環境搭建
- Python Falcon - WSGI vs ASGI
- Python Falcon - Hello World(WSGI)
- Python Falcon - Waitress
- Python Falcon - ASGI
- Python Falcon - Uvicorn
- Python Falcon - API 測試工具
- 請求 & 響應
- Python Falcon - 資源類
- Python Falcon - 應用類
- Python Falcon - 路由
- Falcon - 字尾響應器
- Python Falcon - Inspect 模組
- Python Falcon - Jinja2 模板
- Python Falcon - Cookies
- Python Falcon - 狀態碼
- Python Falcon - 錯誤處理
- Python Falcon - 鉤子
- Python Falcon - 中介軟體
- Python Falcon - CORS
- Python Falcon - Websocket
- Python Falcon - Sqlalchemy 模型
- Python Falcon - 測試
- Python Falcon - 部署
- Python Falcon 有用資源
- Python Falcon - 快速指南
- Python Falcon - 有用資源
- Python Falcon - 討論
Python Falcon - WSGI vs ASGI
Web 伺服器閘道器介面(WSGI)
一些最流行的 Python Web 框架實現了 WSGI(代表 **Web Server Gateway Interface**)。WSGI 本質上是一套關於 Web 伺服器和 Web 應用程式之間通用介面的規範,由 Web 伺服器軟體實現,用於處理來自基於 Python 的 Web 應用程式的請求。WSGI 規範於 2003 年首次引入 (PEP 333),並在 2010 年進行了更新 (PEP 3333)。
伺服器透過傳遞以下引數來呼叫 WSGI 應用程式物件:
**environ** - 一個 Python **dict** 物件,類似於 CGI 環境變數和一些 WSGI 特定的變數。
**start_response** - 一個回撥函式,應用程式可以使用它來返回其響應以及標頭和狀態碼。
此物件可以是 Python 中任何可呼叫的物件,例如函式、方法、類或具有 **__call__()** 方法的例項。此應用程式物件必須返回一個由單個位元組字串組成的迭代器。
def application (environ, start_response):
...
...
return [("Hello World!".encode("utf-8")]
但是,啟用 WSGI 的伺服器在操作上是同步的,因此應用程式效率不高。Python 透過在標準庫中引入 **asyncio** 模組,從 3.4 版本開始支援非同步程式設計。
**asyncio** 模組提供了在 Python 應用程式中整合併發程式設計風格的能力(通常稱為協作式多工)。在這種方法中,作業系統不會阻塞不同程序之間的上下文切換。相反,一個程序會定期讓出以適應其他程序,以便許多應用程式可以同時執行。
在 Python 3.5 版本中,添加了 **async** 和 **await** 這兩個關鍵字。使用 async 關鍵字定義的 Python 函式成為 **協程**,因此不能像普通函式一樣執行。相反,我們需要使用 **asyncio.run (coroutine)** 呼叫它。可以使用 await 關鍵字使協程的執行暫停,直到另一個協程完成。
import asyncio
async def main():
print('hello')
await asyncio.sleep(5)
print('world')
asyncio.run(main())
非同步伺服器閘道器介面(ASGI)
ASGI 代表 **Asynchronous Server Gateway Interface**(根據其官方文件,它是 WSGI 的精神繼任者),它為 Python Web 伺服器、應用程式和框架添加了非同步功能。
ASGI 應用程式是一個非同步可呼叫物件(使用者定義的函式或具有 **__call__()** 方法的類的物件)。它接受以下三個引數:
**Scope** - 包含特定連線詳細資訊的 **dict**
**Send** - 一個非同步可呼叫物件,應用程式可以使用它向客戶端傳送事件訊息。
**Receive** - 另一個非同步可呼叫物件。應用程式可以使用它從客戶端接收事件訊息。
以下是非同步函式表示的簡單 ASGI 應用程式的原型:
async def app(scope, receive, send):
assert scope['type'] == 'http'
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})
await send({
'type': 'http.response.body',
'body': b'Hello, world!',
})