HTTP API Reference


HTTP-related publisher interfaces.

interface zope.publisher.interfaces.http.IVirtualHostRequest[source]

The support for virtual hosts in Zope is very important.

In order to make virtual hosts working, we need to support several methods in our Request object. This interface defines the required methods.


Marks the currently traversed object as the root of a virtual host.

Any path elements traversed up to that

Set the names which compose the application path. These are the path elements that appear in the beginning of the generated URLs.

Should be called during traversal.


Returns the object which is the virtual host root for this request

Return None if setVirtualHostRoot hasn’t been called.

setApplicationServer(host, proto='http', port=None)

Override the host, protocol and port parts of generated URLs.

This affects automatically inserted <base> tags and URL getters in the request, but not things like @@absolute_url views.


Add the name being traversed to the application name

This is only allowed in the case where the name is the first name.

A Value error is raised if the shift can’t be performed.

interface zope.publisher.interfaces.http.IHTTPApplicationRequest[source]

Extends: zope.publisher.interfaces.IApplicationRequest, zope.publisher.interfaces.http.IVirtualHostRequest

HTTP request data.

This object provides access to request data. This includes, the input headers, server data, and cookies.

Request objects are created by the object publisher and will be passed to published objects through the argument name, REQUEST.

The request object is a mapping object that represents a collection of variable to value mappings. In addition, variables are divided into four categories:

The request object may be used as a mapping object, in which case values will be looked up in the order: environment variables, other variables, cookies, and special.


Return HTTP request data

Request data sre retrieved from one of:

Cookies are searched before environmental data.


Return the cookie data

Data are returned as a mapping object, mapping cookie name to value.


Request cookie data

This is a read-only mapping from variable name to value.

getHeader(name, default=None, literal=False)

Get a header value

Return the named HTTP header, or an optional default argument or None if the header is not found. Note that both original and CGI-ified header names are recognized, e.g. ‘Content-Type’, ‘CONTENT_TYPE’ and ‘HTTP_CONTENT_TYPE’ should all return the Content-Type header, if available.

If the literal argument is passed, the header is searched ‘as is’, eg: only if the case matches.


Request header data

This is a read-only mapping from variable name to value. It does not support iteration.


Request URL data

When converted to a string, this gives the effective published URL.

This object can also be used as a mapping object. The key must be an integer or a string that can be converted to an integer. A non-negative integer returns a URL n steps from the URL of the top-level application objects. A negative integer gives a URL that is -n steps back from the effective URL.

For example, ‘request.URL[-2]’ is equivalent to the Zope 2 ‘request[“URL2”]’. The notion is that this would be used in path expressions, like ‘request/URL/-2’.

getURL(level=0, path_only=False)

Return the published URL with level names removed from the end.

If path_only is true, then only a path will be returned.

getApplicationURL(depth=0, path_only=False)

Return the application URL plus depth steps

If path_only is true, then only a path will be returned.

interface zope.publisher.interfaces.http.IHTTPPublisher[source]

Extends: zope.publisher.interfaces.IPublishTraverse

HTTP Publisher

interface zope.publisher.interfaces.http.IHTTPView[source]

Extends: zope.browser.interfaces.IView


interface zope.publisher.interfaces.http.IHTTPApplicationResponse[source]

HTTP Response

redirect(location, status=302, trusted=False)

Causes a redirection without raising an error.

By default redirects are untrusted which restricts target URLs to the same host that the request was sent to.

If the trusted flag is set, redirects are allowed for any target URL.

interface zope.publisher.interfaces.http.IHeaderOutput[source]

Interface for setting HTTP response headers.

This allows the HTTP server and the application to both set response headers.

zope.publisher.http.HTTPResponse is optionally passed an object which implements this interface in order to intermingle its headers with the HTTP server’s response headers, and for the purpose of better logging.

setResponseStatus(status, reason)

Sets the status code and the accompanying message.


Sets headers. The headers must be Correctly-Cased.


Sets headers that can potentially repeat.

Takes a list of strings.


Returns a flag indicating whether the response

header has already been sent.


Sets the name of the authenticated user so the name can be logged.

interface zope.publisher.interfaces.http.IResult[source]

An iterable that provides the body data of the response.

For simplicity, an adapter to this interface may in fact return any iterable, without needing to strictly have the iterable provide IResult.

IMPORTANT: The result object may be held indefinitely by a server and may be accessed by arbitrary threads. For that reason the result should not hold on to any application resources (i.e., should not have a connection to the database) and should be prepared to be invoked from any thread.

This iterable should generally be appropriate for WSGI iteration.

Each element of the iteration should generally be much larger than a character or line; concrete advice on chunk size is hard to come by, but a single chunk of even 100 or 200 K is probably fine.

If the IResult is a string, then, the default iteration of per-character is wildly too small. Because this is such a common case, if a string is used as an IResult then this is special-cased to simply convert to a tuple of one value, the string.

Adaptation to this interface provides the opportunity for efficient file delivery, pipelining hooks, and more.


iterate over the values that should be returned as the result.

See IHTTPResponse.setResult.

interface zope.publisher.interfaces.http.IHTTPResponse[source]

Extends: zope.publisher.interfaces.IResponse

An object representation of an HTTP response.

The Response type encapsulates all possible responses to HTTP requests. Responses are normally created by the object publisher. A published object may recieve the response object as an argument named ‘RESPONSE’. A published object may also create its own response object. Normally, published objects use response objects to:

  • Provide specific control over output headers,
  • Set cookies, or
  • Provide stream-oriented output.

If stream oriented output is used, then the response object passed into the object must be used.


The authenticated user message.


Returns the current HTTP status code as an integer.

setStatus(status, reason=None)

Sets the HTTP status code of the response

The status parameter must be either an integer (preferred), a value that can be converted to an integer using the int() function, or one of the standard status messages listed in the status_codes dict of the zope.publisher.http module (including “OK”, “NotFound”, and so on). If the parameter is some other value, the status will be set to 500.

The reason parameter is a short message to be sent with the status code to the client. If reason is not provided, a standard reason will be supplied, falling back to “Unknown” for unregistered status codes.


Return the status followed by the reason.

setHeader(name, value, literal=False)

Sets an HTTP return header “name” with value “value”

The previous value is cleared. If the literal flag is true, the case of the header name is preserved, otherwise word-capitalization will be performed on the header name on output.

addHeader(name, value)

Add an HTTP Header

Sets a new HTTP return header with the given value, while retaining any previously set headers with the same name.

getHeader(name, default=None)

Gets a header value

Returns the value associated with a HTTP return header, or ‘default’ if no such header has been set in the response yet.


Returns a list of header name, value tuples.

appendToCookie(name, value)

Append text to a cookie value

If a value for the cookie has previously been set, the new value is appended to the old one separated by a colon.

expireCookie(name, **kw)

Causes an HTTP cookie to be removed from the browser

The response will include an HTTP header that will remove the cookie corresponding to “name” on the client, if one exists. This is accomplished by sending a new cookie with an expiration date that has already passed. Note that some clients require a path to be specified - this path must exactly match the path given when creating the cookie. The path can be specified as a keyword argument. If the value of a keyword argument is None, it will be ignored.

setCookie(name, value, **kw)

Sets an HTTP cookie on the browser

The response will include an HTTP header that sets a cookie on cookie-enabled browsers with a key “name” and value “value”. This overwrites any previously set value for the cookie in the Response object. If the value of a keyword argument is None, it will be ignored.

getCookie(name, default=None)

Gets HTTP cookie data as a dict

Returns the dict of values associated with an HTTP cookie set in the response, or ‘default’ if no such cookie has been set in the response yet.


Sets response result value based on input.

Input is usually a unicode string, a string, None, or an object that can be adapted to IResult with the request. The end result is an iterable such as WSGI prefers, determined by following the process described below.

Try to adapt the given input, with the request, to IResult (found above in this file). If this fails, and the original value was a string, use the string as the result; or if was None, use an empty string as the result; and if it was anything else, raise a TypeError.

If the result of the above (the adaptation or the default handling of string and None) is unicode, encode it (to the preferred encoding found by adapting the request to zope.i18n.interfaces.IUserPreferredCharsets, usually implemented by looking at the HTTP Accept-Charset header in the request, and defaulting to utf-8) and set the proper encoding information on the Content-Type header, if present. Otherwise (the end result was not unicode) application is responsible for setting Content-Type header encoding value as necessary.

If the result of the above is a string, set the Content-Length header, and make the string be the single member of an iterable such as a tuple (to send large chunks over the wire; see discussion in the IResult interface). Otherwise (the end result was not a string) application is responsible for setting Content-Length header as necessary.

Set the result of all of the above as the response’s result. If the status has not been set, set it to 200 (OK).


Returns the response body as a string.

Note that this function can be only requested once, since it is constructed from the result.


Returns the response body as an iterable.

Note that this function can be only requested once, since it is constructed from the result.

interface zope.publisher.interfaces.http.IHTTPVirtualHostChangedEvent[source]

The host, port and/or the application path have changed.

The request referred to in this event implements at least the IHTTPAppliationRequest interface.


The application request whose virtual host info has been altered

interface zope.publisher.interfaces.http.IHTTPException[source]

Marker interface for http exceptions views

interface zope.publisher.interfaces.http.IMethodNotAllowed[source]

Extends: zope.interface.common.interfaces.IException

An exception that signals the 405 Method Not Allowed HTTP error


The object on which the error occurred


The request in which the error occurred

exception zope.publisher.interfaces.http.MethodNotAllowed(object, request)[source]

Bases: exceptions.Exception

An exception that signals the 405 Method Not Allowed HTTP error


HTTP Publisher


Split port number off the hostname.

>>> splitport('')
('', '80')
>>> splitport('localhost')
('localhost', None)
>>> splitport('[::1]')
('[::1]', None)
>>> splitport('[::1]:443')
('[::1]', '443')
>>> splitport('localhost:')
('localhost', None)
class zope.publisher.http.HTTPInputStream(stream, environment)[source]

Bases: object

Special stream that supports caching the read data.

This is important, so that we can retry requests.

class zope.publisher.http.HTTPRequest(body_instream, environ, response=None)[source]

Bases: zope.publisher.base.BaseRequest

Model HTTP request data.

This object provides access to request data. This includes, the input headers, form data, server data, and cookies.

Request objects are created by the object publisher and will be passed to published objects through the argument name, REQUEST.

The request object is a mapping object that represents a collection of variable to value mappings. In addition, variables are divided into four categories:

  • Environment variables

    These variables include input headers, server data, and other request-related data. The variable names are as <a href=””>specified</a> in the <a href=””>CGI specification</a>

  • Form data

    These are data extracted from either a URL-encoded query string or body, if present.

  • Cookies

    These are the cookie data, if present.

  • Other

    Data that may be set by an application object.

The form attribute of a request is actually a Field Storage object. When file uploads are used, this provides a richer and more complex interface than is provided by accessing form data as items of the request. See the FieldStorage class documentation for more details.

The request object may be used as a mapping object, in which case values will be looked up in the order: environment variables, other variables, form data, and then cookies.


See IPublisherRequest


See IPublisherRequest


See IPublisherRequest

getHeader(name, default=None, literal=False)[source]

See IHTTPRequest


See IHTTPApplicationRequest


See IHTTPRequest


See IHTTPCredentials


See IPublicationRequest

getApplicationURL(depth=0, path_only=False)[source]

See IHTTPApplicationRequest


Add the name being traversed to the application name

This is only allowed in the case where the name is the first name.

A Value error is raise if the shift can’t be performed.

get(key, default=None)[source]

See Interface.Common.Mapping.IReadMapping


See Interface.Common.Mapping.IEnumerableMapping

class zope.publisher.http.HTTPResponse[source]

Bases: zope.publisher.base.BaseResponse


See IResponse

setStatus(status, reason=None)[source]

See IHTTPResponse


See IHTTPResponse


See IHTTPResponse

setHeader(name, value, literal=False)[source]

See IHTTPResponse

addHeader(name, value)[source]

See IHTTPResponse

getHeader(name, default=None, literal=False)[source]

See IHTTPResponse


See IHTTPResponse

appendToCookie(name, value)[source]

See IHTTPResponse

expireCookie(name, **kw)[source]

See IHTTPResponse

setCookie(name, value, **kw)[source]

See IHTTPResponse

getCookie(name, default=None)[source]

See IHTTPResponse


See IHTTPResponse


See IHTTPResponse


See IHTTPResponse


Calls self.setBody() with an error response.


See IPublisherResponse


Returns a response object to be used in a retry attempt

redirect(location, status=None, trusted=False)[source]

Causes a redirection without raising an error


See IHTTPResponse

class zope.publisher.http.DirectResult(body)[source]

Bases: object

A generic result object.

The result’s body can be any iterable. It is the responsibility of the application to specify all headers related to the content, such as the content type and length.

Creating HTTP Results

This document describes the state of creating HTTP results for Zope 3.4. This is different than it was in the past.

Traditionally in Zope, HTTP results are created by simply returning strings. Strings are inspected to deduce their content type, which is usually HTML. Applications can override this by setting a response headers (calling request.response.setHeader).

In Zope 2, applications could also call response.write. This allows both:

  • Effecient handling of large output
  • HTTP chucked output for streaming

Before release 3.1, Zope 3 has a response write method that did neither of these things. Developers coming from Zope 2 might use the write method, expecting it to have the same bahavior as it does in Zope 2. At least until we can satisfy those expectations, we have disabled the response write method for now. Maybe we’ll reinstate it in the future.

There is currently no support for streaming (at least while holding on to a database connection and transaction), but there is now support for returning large amounts of data.

Returning large amounts of data without storing the data in memory

To return a large result, you should write the result to a temporary file (tempfile.TemporaryFile) and return the temporary file. Alternatively, if the data you want to return is already in a (non-temporary) file, just open and return that file. The publisher (actually an adapter used by the publisher) will handle a returned file very efficiently.

The publisher will compute the response content length from the file automatically. It is up to applications to set the content type. It will also take care of positioning the file to it’s beginning, so applications don’t need to do this beforehand.

This is actually accomplished via, and happens if and only if that, or something like it, is registered as an adapter. The FileResult, however, does what needs to happen thanks to a special hook associated with the IResult interface, used by the http module in this package.


The interface for IResult describes the interface thoroughly. The IHTTPResponse.setHeader method that uses it also documents how it is used. Reading the IResult interface and the IHTTPResponse.setHeader description (in the same interface file) is highly recommended.

In addition to supporting sending large amoounts of data, IResult supports postprocessing of output. setResult tries to adapt everything to IResult. Postprocessing might include XSLT transforms, adding an O-wrap around the content, adding JavaScript and CSS header lines on the basis of elements added to a page, or pipelining somehow to do all of it sequentially. May the best approach win! This merely makes the different options possible.

To close, we’ll build a quick example so you can see it working.

(To make the code work in both python-2.x and python-3.x, define unicode name for python-3.x:

>>> import sys
>>> if sys.version_info[0] > 2:
...     unicode = str
>>> import zope.interface
>>> import zope.component
>>> from zope.publisher.browser import TestRequest
>>> from zope.publisher.interfaces.http import IResult, IHTTPRequest
>>> try:
...     from html import escape
... except ImportError:
...     from cgi import escape
>>> @zope.interface.implementer(IResult)
... @zope.component.adapter(unicode, IHTTPRequest)
... def do_something_silly_to_unicode_results(val, request):
...     request.response.setHeader('X-Silly', 'Yes')
...     return (unicode('<html>\n<head>\n<title>raw</title>\n</head>\n<body>\n') +
...             escape(val) + '\n</body>\n</html>')
>>> zope.component.provideAdapter(do_something_silly_to_unicode_results)

That’s returning a unicode string, which is special cased to (1) make an iterable that is chunked, (2) encode, and (3) set content-length.

>>> request = TestRequest()
>>> request.response.setHeader('content-type', 'text/html')
>>> request.response.setResult(unicode('<h1>Foo!</h1>'))
>>> request.response.getHeader('x-silly')
>>> request.response.getHeader('content-type')
>>> res = tuple(request.response.consumeBodyIter())
>>> res
>>> len(res[0]) == int(request.response.getHeader('content-length'))

You can also do everything yourself by returning any non-basestring iterable (for instance, a list or tuple).

>>> @zope.interface.implementer(IResult)
... @zope.component.adapter(int, IHTTPRequest)
... def do_something_silly_to_int_results(val, request):
...     return ['This', ' is an int: %i' % (val,),]
>>> zope.component.provideAdapter(do_something_silly_to_int_results)
>>> request = TestRequest()
>>> request.response.setHeader('content-type', 'text/plain')
>>> request.response.setResult(42)
>>> request.response.getHeader('content-type')
>>> res = tuple(request.response.consumeBodyIter())
>>> res
('This', ' is an int: 42')
>>> request.response.getHeader('content-length') is None

Again, READ THE INTERFACES. One important bit is that you can’t hold on to a database connection in one of these iterables.

You can bypass the adaptation by calling setResult with an object that provides IResult. The DirectResult class in the http module is the simplest way to do this, but any other IResult should work.

>>> from zope.publisher.http import DirectResult
>>> @zope.interface.implementer(IResult)
... @zope.component.adapter(DirectResult, IHTTPRequest)
... def dont_touch_this(val, request):
...     raise ValueError('boo!  hiss!') # we don't get here.
>>> request = TestRequest()
>>> request.response.setResult(DirectResult(('hi',)))
>>> tuple(request.response.consumeBodyIter())