Responses and Presentation

After performing some kind of processing on input information, an application will then want to produce some kind of response to indicate what went on. Here are some examples of responses:

Generating Responses

The procedure involved in generating a response usually involves the following steps:

  1. Setting a response code to signal whether the application performed the requested operation successfully.
  2. Setting a content type and a character encoding.
  3. Producing content and sending it to the user.

The kind of code involved may well resemble the following:

from WebStack.Generic import ContentType

class MyResource:
    def respond(self, trans):
        [Perform the requested operations.]

        if [the operation was successful]:
            trans.set_response_code(200)
            trans.set_content_type(ContentType("text/html", encoding="utf-8"))
            out = trans.get_response_stream()
            out.write([some data either as a plain string suitably encoded or as Unicode])
        else:
            trans.set_response_code(500) # or some other code
            trans.set_content_type(ContentType("text/html", encoding="utf-8"))
            out = trans.get_response_stream()
            out.write([some other data either as a plain string suitably encoded or as Unicode])

As discussed in "Character Encodings", care must be taken generating the response so that it meets any expectations that browsers and other Web clients may have.

WebStack API - Response-Related Methods

Transaction objects have various methods that can be used in generating responses:

set_response_code
This accepts an integer value denoting the response condition as described in the HTTP specification. If this method is not used, WebStack sets a 200 status condition on the response, meaning that the request was processed successfully.
set_content_type
This accepts a content type object (typically WebStack.Generic.ContentType) which specifies both the media type and the character encoding (if relevant) of the data sent to the user. The media type describes the format of the data (eg. text/html - a Web page), whereas the character encoding describes how any character information on the page is encoded - see "Character Encodings" for more information.
get_response_stream
This returns the output stream through which data may be sent to the user.