Aspen

A Python web framework that makes the most of the filesystem.
Simplates are the main attraction.

Response

The aspen.Response class has this constructor:

def __init__(self, code=200, body='', headers=None):
    """Takes an int, a string, and a dict (or list of tuples).

        - code        an HTTP response code, e.g., 404
        - body        the message body as a string
        - headers     a Headers instance

    Code is first because when you're raising your own Responses, they're
    usually error conditions. Body is second because one more often wants
    to specify a body without headers, than a header without a body.

    """

The Default Response Object

A Response object is automatically instantiated for all requests. This object is automatically available in the second page of your simplates, where it is named response.

One common thing to do with the response object is to set a header. The response.headers attribute is the same as on Request objects, so here’s how you would set a header in a simplate:

response.headers['X-My-Header'] = 'Greetings, program!'
[---]
Check your headers.

Raising Responses

You can also raise Response instances, because Response is a subclass of Python's built-in Exception class.

Make a simplate named fishing.html.spt with this content:

from aspen import Response
[---]
raise Response(200)
[---]
Let's go fishing!

Did you expect to see “Let's go fishing!” instead? The reason you don’t is that when you raise Response() from a simplate, the template page of the simplate is skipped. This is because the feature is really designed for exceptions, things like 404, etc.

So change the HTTP code in fishing.html.spt:

from aspen import Response
[---]
raise Response(404)
[---]
Let's go fishing!

You will get this:

Custom Response Objects

For advanced use cases, you can define your own Response class and instantiate it inside of your simplates. Whatever is named “response” at the end of page two of a simplate will be what Aspen uses to capture the template output and respond to the client. That is, the variable named “response” should be your Response instance. It will be used as a response, and—unless you raise it—its body attribute will be replaced with the output of the template page.

Home Virtual Paths