Pyramid 响应对象

2023-03-30 17:39 更新

响应类定义在pyramid.response模块中。该类的一个对象由视图的可调用性返回。

from pyramid.response import Response
def hell(request):
   return Response("Hello World")

响应对象包含一个状态代码(默认是200 OK),一个响应头的列表和响应体。大多数HTTP响应头都可以作为属性使用。以下属性对响应对象是可用的

  • response.content_type – 内容类型是一个字符串,如 – response.content_type = ‘text/html’。
  • response.charset – 它也通知 response.text 中的编码 。
  • response.set_cookie – 这个属性用来设置一个cookie。需要给出的参数是name、value和max_age。
  • response.delete_cookie – 从客户端删除一个cookie。有效地,它将max_age设置为0,并将cookie的值设置为”。

pyramid.httpexceptions 模块定义了处理错误响应的类,如404 Not Found。这些类实际上是 响应 类的子类。一个这样的类是 “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类的location属性来将客户端重定向到另一个路由。例如 –

view_config(route_name='add', request_method='POST')
def add(request):
   #add a new object
   return HTTPFound(location='http://localhost:6543/')


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号