響應(yīng)類(lèi)定義在pyramid.response模塊中。該類(lèi)的一個(gè)對(duì)象由視圖的可調(diào)用性返回。
from pyramid.response import Response
def hell(request):
return Response("Hello World")
響應(yīng)對(duì)象包含一個(gè)狀態(tài)代碼(默認(rèn)是200 OK),一個(gè)響應(yīng)頭的列表和響應(yīng)體。大多數(shù)HTTP響應(yīng)頭都可以作為屬性使用。以下屬性對(duì)響應(yīng)對(duì)象是可用的
pyramid.httpexceptions 模塊定義了處理錯(cuò)誤響應(yīng)的類(lèi),如404 Not Found。這些類(lèi)實(shí)際上是 響應(yīng) 類(lèi)的子類(lèi)。一個(gè)這樣的類(lèi)是 “pyramid.httpexceptions.HTTPNotFound”。它的典型用途如下
from pyramid.httpexceptions import HTTPNotFound
from pyramid.config import view_config
@view_config(route='Hello')
def hello(request):
response = HTTPNotFound("There is no such route defined")
return response
我們可以使用Response類(lèi)的location屬性來(lái)將客戶端重定向到另一個(gè)路由。例如 –
view_config(route_name='add', request_method='POST')
def add(request):
#add a new object
return HTTPFound(location='http://localhost:6543/')
更多建議: