天天看點

Python程式設計:WSGI伺服器的參考實作wsgiref子產品

WSGI的全稱是Web Server Gateway Interface,Web伺服器網關接口

具體的來說,WSGI是一個規範,定義了Web伺服器如何與Python應用程式進行互動

WSGI 相當于是Web伺服器和Python應用程式之間的橋梁

Python程式設計:WSGI伺服器的參考實作wsgiref子產品

使用python内置的子產品實作一個伺服器

python3下示例

# WSGI伺服器的參考實作

# 【應用程式】
# 處理函數
def application(environ, start_response):
    start_response("200 OK", [('Content-Type', 'text/html')])
    body = "<h1>hello world %s<h1>"% (environ["PATH_INFO"][1:] or "web")
    return [ body.encode()]


# 【伺服器】
from wsgiref.simple_server import make_server

# 建立一個伺服器,是application
server = make_server("localhost", 9999, application)

print("服務啟動,按Ctrl+C終止... http://localhost:9999/")

# 開始監聽HTTP請求
server.serve_forever()

      

參考

  1. WSGI接口- 廖雪峰部落格
  2. WGSI簡易教程