Python Pyramid - Hello World



示例

要檢查 Pyramid 及其依賴項是否已正確安裝,請輸入以下程式碼並將其儲存為 hello.py,使用任何支援 Python 的編輯器。

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
   return Response('Hello World!')
   
if __name__ == '__main__':
   with Configurator() as config:
      config.add_route('hello', '/')
      config.add_view(hello_world, route_name='hello')
      app = config.make_wsgi_app()
   server = make_server('0.0.0.0', 6543, app)
   server.serve_forever()

Configurator 物件用於定義 URL 路由並將檢視函式繫結到它。從該配置物件獲得的 WSGI 應用物件是 make_server() 函式的引數,以及 localhost 的 IP 地址和埠。當呼叫 serve_forever() 方法時,伺服器物件進入監聽迴圈。

從命令終端執行此程式,如下所示:

Python hello.py

輸出

WSGI 伺服器開始執行。開啟瀏覽器並在位址列中輸入 http://loccalhost:6543/。當請求被接受時,hello_world() 檢視函式將被執行。它返回 Hello world 訊息。Hello world 訊息將顯示在瀏覽器視窗中。

Hello World

如前所述,wsgiref 模組中 make_server() 函式建立的開發伺服器不適合生產環境。相反,我們將使用 Waitress 伺服器。根據以下程式碼修改 hello.py:

from pyramid.config import Configurator
from pyramid.response import Response
from waitress import serve

def hello_world(request):
   return Response('Hello World!')
   
if __name__ == '__main__':
   with Configurator() as config:
      config.add_route('hello', '/')
      config.add_view(hello_world, route_name='hello')
      app = config.make_wsgi_app()
      serve(app, host='0.0.0.0', port=6543)

所有其他功能都相同,除了我們使用 waitress 模組的 serve() 函式啟動 WSGI 伺服器。在執行程式後訪問瀏覽器中的 '/' 路由,將像以前一樣顯示 Hello world 訊息。

除了函式之外,可呼叫類也可以用作檢視。可呼叫類是重寫了 __call__() 方法的類。

from pyramid.response import Response
class MyView(object):
   def __init__(self, request):
      self.request = request
   def __call__(self):
      return Response('hello world')
廣告