tornado.wsgi
— 與其他 Python 框架和伺服器的互操作性¶
Tornado Web 框架的 WSGI 支援。
WSGI 是 Python 的 Web 伺服器標準,允許 Tornado 與其他 Python Web 框架和伺服器之間的互操作性。
此模組透過 WSGIContainer
類別提供 WSGI 支援,這使得在 Tornado HTTP 伺服器上使用其他 WSGI 框架執行應用程式成為可能。反之則不支援;Tornado Application
和 RequestHandler
類別設計用於 Tornado HTTPServer
,且不能在通用的 WSGI 容器中使用。
- class tornado.wsgi.WSGIContainer(wsgi_application: WSGIAppType, executor: Optional[Executor] = None)[原始碼]¶
使 WSGI 相容的應用程式可在 Tornado 的 HTTP 伺服器上執行。
警告
WSGI 是一個同步介面,而 Tornado 的並行模型基於單執行緒的非同步執行。Tornado 的許多獨特功能在 WSGI 模式下不可用,包括高效的長輪詢和 WebSocket。
WSGIContainer
的主要目的是在單一程序中同時支援 WSGI 應用程式和原生 TornadoRequestHandlers
。僅限 WSGI 的應用程式最好使用專用的 WSGI 伺服器,例如gunicorn
或uwsgi
。將 WSGI 應用程式包裝在
WSGIContainer
中,使其實現 TornadoHTTPServer
request_callback
介面。WSGIContainer
物件接著可以傳遞至tornado.routing
模組中的類別、tornado.web.FallbackHandler
或直接傳遞至HTTPServer
。此類別旨在讓其他框架(Django、Flask 等)在 Tornado HTTP 伺服器和 I/O 迴圈上執行。
實際使用情況會更複雜,但最簡單的範例是使用手寫的 WSGI 應用程式與
HTTPServer
def simple_app(environ, start_response): status = "200 OK" response_headers = [("Content-type", "text/plain")] start_response(status, response_headers) return [b"Hello world!\n"] async def main(): container = tornado.wsgi.WSGIContainer(simple_app) http_server = tornado.httpserver.HTTPServer(container) http_server.listen(8888) await asyncio.Event().wait() asyncio.run(main())
建議的模式是使用
tornado.routing
模組,在您的 WSGI 應用程式和通常的tornado.web.Application
之間設定路由規則。或者,tornado.web.Application
可以用作頂層路由器,而tornado.web.FallbackHandler
可以在其中嵌入WSGIContainer
。如果提供
executor
引數,WSGI 應用程式將在該執行器上執行。這必須是concurrent.futures.Executor
的實例,通常是ThreadPoolExecutor
(不支援ProcessPoolExecutor
)。如果未提供executor
,則應用程式將在 Tornado 6.3 的事件迴圈執行緒上執行;這將在 Tornado 7.0 中更改為預設使用內部執行緒池。警告
預設情況下,WSGI 應用程式在事件迴圈的執行緒上執行。這將伺服器限制為一次處理一個請求(每個程序),使其擴充性不如大多數其他 WSGI 伺服器。因此,強烈建議在建構
WSGIContainer
時傳遞ThreadPoolExecutor
,並驗證您的應用程式是執行緒安全的。預設值將在 Tornado 7.0 中更改為使用ThreadPoolExecutor
。6.3 版新增:
executor
參數。自 6.3 版起已棄用: 在事件迴圈執行緒上執行 WSGI 應用程式的預設行為已棄用,將在 Tornado 7.0 中變更為預設使用執行緒池。
- environ(request: HTTPServerRequest) Dict[str, Any] [原始碼]¶
將
tornado.httputil.HTTPServerRequest
轉換為 WSGI 環境。在 6.3 版中變更: 不再是靜態方法。