wsgi全稱是"Web Server Gateway Interfacfe",web服務器網關接口,wsgi在python2.5中加入,是
web服務器和web應用的標准接口,任何實現了該接口的web服務器和web應用都能無縫協作。來看一個形象點的圖:
如上圖所示(圖片來自
這里),wsgi一端連接web服務器(http服務器),另一端連接應用。目前已經有很多的web框架,如flask、webpy,用戶只要簡單配置一些路由信息,就能開發出一個web應用。后文中的web框架就等同於應用(application)
那么這個接口是什么樣子的呢,pep333是這么描述的:
(1)App提供一個接受兩個參數的callable對象。第一個參數是一個dict類型,表示請求相關的環境變量;第二個參數是一個callable對象,app在代碼中調用該callable設置響應的消息頭。app需要返回一個可迭代的字符串序列,表示響應的消息內容
(2)web server在http請求到來之后,調用App提供的callable對象,傳入響應的參數。然后把App的返回值發送給http請求者(如瀏覽器)
首先,我們還是來看最基礎的例子,wsgi的Hello World!
1 def hello_world_app(environ, start_response): 2 status = '200 OK' # HTTP Status 3 headers = [('Content-type', 'text/plain')] # HTTP Headers 4 start_response(status, headers) 5 6 # The returned object is going to be printed 7 return ["Hello World"]
1 def hello_world_app(environ, start_response): 2 status = '200 OK' # HTTP Status 3 headers = [('Content-type', 'text/plain')] # HTTP Headers 4 start_response(status, headers) 5 6 # The returned object is going to be printed 7 return ["Hello World"] 8 9 def main(): 10 from wsgiref.simple_server import make_server 11 httpd = make_server('', 8000, hello_world_app) 12 print "Serving on port 8000..." 13 14 # Serve until process is killed 15 httpd.serve_forever() 16 17 if __name__ == '__main__': 18 main()
運行這段代碼,然后在瀏覽器輸入 127.0.0.1:8000,即可看到結果
常見的python web服務器包括,cherrypy、gevent-fastcgi、gunicorn、uwsgi、twisted、webpy、tornado等等,在實際應用中,這些web服務器可能需要配合其他http代理服務器使用,如Nginx。
常見的python web框架包括 Django, Flask, webpy,bottle,Cherrypy, tornado。一些web框架本身也自帶web服務器,如Cherrypy、tornado。tornado因為有異步網絡庫,作為web服務器性能也不錯。
最后,推薦一篇文章《
一起寫一個 Web 服務器》,是伯樂在線翻譯的,
原文在此。文章包括三部分:第一部分介紹http服務;第二部分實現了一個wsgi web服務器,並配合各種web框架進行使用和測試;第三部分對第二部分實現wsgi服務器進行並發優化。
reference:
