淺析Python 中的 WSGI 接口和 WSGI 服務的運行
HTTP格式HTTP GET請求的格式:
GET /path HTTP/1.1Header1: Value1Header2: Value2Header3: Value3
每個Header一行一個,換行符是rn。
HTTP POST請求的格式:
POST /path HTTP/1.1Header1: Value1Header2: Value2Header3: Value3body data goes here...
當遇到連續(xù)兩個rn時,Header部分結(jié)束,后面的數(shù)據(jù)全部是Body。
HTTP響應的格式:
200 OKHeader1: Value1Header2: Value2Header3: Value3body data goes here...
HTTP響應如果包含body,也是通過rnrn來分隔的。需注意,Body的數(shù)據(jù)類型由Content-Type頭來確定,如果是網(wǎng)頁,Body就是文本,如果是圖片,Body就是圖片的二進制數(shù)據(jù)。
當存在Content-Encoding時,Body數(shù)據(jù)是被壓縮的,最常見的壓縮方式是gzip。
WSGI接口WSGI:Web Server Gateway Interface。
WSGI接口定義非常簡單,只需要實現(xiàn)一個函數(shù),就可以響應HTTP請求。
# hello.pydef 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’)]
函數(shù)接收兩個參數(shù):
environ:一個包含所有HTTP請求信息的dict對象; start_response:一個發(fā)送HTTP響應的函數(shù)。運行WSGI服務Python內(nèi)置了一個WSGI服務器,這個模塊叫wsgiref,它是用純Python編寫的WSGI服務器的參考實現(xiàn)。
# server.pyfrom wsgiref.simple_server import make_serverfrom hello import application# 創(chuàng)建一個服務器,IP地址為空,端口是8000,處理函數(shù)是application:httpd = make_server(’’, 8000, application)print(’Serving HTTP on port 8000...’)# 開始監(jiān)聽HTTP請求:httpd.serve_forever()
在命令行輸入python server.py即可啟動WSGI服務器。
啟動成功后,打開瀏覽器,輸入http://localhost:8000/,即可看到結(jié)果。
按Ctrl+C可以終止服務器。
以上就是淺析Python 中的 WSGI 接口和 WSGI 服務的運行的詳細內(nèi)容,更多關于Python WSGI接口和WSGI服務的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
