Python Pyramid 简明教程
Python Pyramid - Response Object
Response
类定义在 pyramid.response
模块中。此类的对象由视图可调用项返回。
The Response class is defined in pyramid.response module. An object of this class is returned by the view callable.
from pyramid.response import Response
def hell(request):
return Response("Hello World")
响应对象包含一个状态代码(默认为 200 OK),一个响应标头列表和响应正文。大多数 HTTP 响应标头可用作属性。Response
对象可用的属性如下 −
The response object contains a status code (default is 200 OK), a list of response headers and the response body. Most HTTP response headers are available as properties. Following attributes are available for the Response object −
-
response.content_type − The content type is a string such as – response.content_type = 'text/html'.
-
response.charset − It also informs encoding in response.text.
-
response.set_cookie − This attribute is used to set a cookie. The arguments needed to be given are name, value, and max_age.
-
response.delete_cookie − Delete a cookie from the client. Effectively it sets max_age to 0 and the cookie value to ''.
pyramid.httpexceptions 模块定义了处理错误响应(例如 404 Not Found)的类。这些类实际上是 Response 类的子类。其中一个这样的类是 "pyramid.httpexceptions.HTTPNotFound"。它的典型用法如下 −
The pyramid.httpexceptions module defines classes to handle error responses such as 404 Not Found. These classes are in fact subclasses of the Response class. One such class is "pyramid.httpexceptions.HTTPNotFound". Its typical use is as follows −
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
属性将客户端重定向到另一个路由。例如 −
We can use location property of Response class to redirect the client to another route. For example −
view_config(route_name='add', request_method='POST')
def add(request):
#add a new object
return HTTPFound(location='http://localhost:6543/')