Pyramid Response 响应对象
创建于 2024-12-03 /
18
字体:
[默认]
[大]
[更大]
Response 类在 pyramid.response 模块中定义。 此类的对象由可调用视图返回。
from pyramid.response import Response def hell(request): return Response("Hello World")
响应对象包含状态代码(默认为 200 OK)、响应标头列表和响应主体。 大多数 HTTP 响应标头都可以作为属性使用。 以下属性可用于 Response 对象 −
response.content_type − 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。 这些类实际上是 Response 类的子类。 其中一个类是"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/')
0 人点赞过