Pyramid Hello World

2023-04-03 13:53 更新

例子

要檢查Pyramid及其依賴項(xiàng)是否正確安裝,請(qǐng)輸入以下代碼并保存為 hello.py 

你可以使用任何支持Python的編輯器來(lái)完成它。

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 ?對(duì)象需要定義URL路由并將視圖函數(shù)綁定到它。從這個(gè)配置對(duì)象中獲得的WSGI應(yīng)用對(duì)象是 ?make_server()? 函數(shù)的一個(gè)參數(shù),同時(shí)還有l(wèi)ocalhost的IP地址和端口。當(dāng) ?serve_forever()? 方法被調(diào)用時(shí),?server ?對(duì)象進(jìn)入一個(gè)監(jiān)聽(tīng)循環(huán)。

從命令終端運(yùn)行這個(gè)程序?yàn)椤?/p>

Python hello.py

輸出

WSGI服務(wù)器開(kāi)始運(yùn)行。打開(kāi)瀏覽器,在地址欄中輸入?http://loccalhost:6543/?。當(dāng)請(qǐng)求被接受時(shí),? hello_world() ?視圖函數(shù)被執(zhí)行。它返回字符?Hello world!?。在瀏覽器窗口中會(huì)看到輸出Hello world。

PythonPyramid--Hello World

如前所述,由 wsgiref 模塊中的?make_server()?函數(shù)創(chuàng)建的開(kāi)發(fā)服務(wù)器不適合于生產(chǎn)環(huán)境。相反,我們將使用Waitress服務(wù)器。按照以下代碼修改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() ?函數(shù)來(lái)啟動(dòng)WSGI服務(wù)器,其他功能都是一樣的。在運(yùn)行程序后訪問(wèn)瀏覽器中的?'/'?路線時(shí),會(huì)像之前一樣顯示Hello world。

你可以重新寫一個(gè)可調(diào)用的類來(lái)處理一些流程。

注意,可調(diào)用類需要重寫__call__()? 方法

可調(diào)用類可以代替函數(shù),也可以作為視圖使用。

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


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)