Python 中的 WSGI 接口和 WSGI 服務

HTTP格式

HTTP GET請求的格式:html

GET /path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3

每一個Header一行一個,換行符是\r\npython

HTTP POST請求的格式:web

POST /path HTTP/1.1
Header1: Value1
Header2: Value2
Header3: Value3

body data goes here...

當遇到連續兩個\r\n時,Header部分結束,後面的數據所有是Body。瀏覽器

HTTP響應的格式:服務器

200 OK
Header1: Value1
Header2: Value2
Header3: Value3

body data goes here...

HTTP響應若是包含body,也是經過\r\n\r\n來分隔的。需注意,Body的數據類型由Content-Type頭來肯定,若是是網頁,Body就是文本,若是是圖片,Body就是圖片的二進制數據。app

當存在Content-Encoding時,Body數據是被壓縮的,最多見的壓縮方式是gzip。函數

WSGI接口

WSGI:Web Server Gateway Interface。命令行

WSGI接口定義很是簡單,只須要實現一個函數,就能夠響應HTTP請求。code

# hello.py

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    body = '<h1>Hello, %s!</h1>' % (environ['PATH_INFO'][1:] or 'web')
    return [body.encode('utf-8')]

函數接收兩個參數:server

  • environ:一個包含全部HTTP請求信息的dict對象;
  • start_response:一個發送HTTP響應的函數。

運行WSGI服務

Python內置了一個WSGI服務器,這個模塊叫wsgiref,它是用純Python編寫的WSGI服務器的參考實現。

# server.py

from wsgiref.simple_server import make_server
from hello import application

# 建立一個服務器,IP地址爲空,端口是8000,處理函數是application:
httpd = make_server('', 8000, application)
print('Serving HTTP on port 8000...')
# 開始監聽HTTP請求:
httpd.serve_forever()

在命令行輸入python server.py便可啓動WSGI服務器。

啓動成功後,打開瀏覽器,輸入http://localhost:8000/,便可看到結果。

Ctrl+C能夠終止服務器。

相關文章
相關標籤/搜索