Python Pyramid - Response Object



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")

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 ''.

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

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/')
Advertisements