trac.web.api – Trac Web Request Handling

Primary interface for handling web requests.

Interfaces

The following interfaces allow components to interact at various stages of the web requests processing pipeline.

class trac.web.api.IRequestHandler

Bases: trac.core.Interface

Decide which trac.core.Component handles which Request, and how.

The boolean property is_valid_default_handler determines whether the IRequestFilter can be used as a default_handler and defaults to True. To be suitable as a default_handler, an IRequestFilter must return an HTML document and data dictionary for rendering the document, and must not require that match_request be called prior to process_request.

The boolean property jquery_noconflict determines whether jQuery’s noConflict mode will be activated by the handler, and defaults to False.

See also trac.web.api.IRequestHandler extension point

match_request(req)

Return whether the handler wants to process the given request.

process_request(req)

Process the request.

Return a (template_name, data) pair, where data is a dictionary of substitutions for the Jinja2 template (the template context, in Jinja2 terms).

Optionally, the return value can also be a (template_name, data, metadata) triple, where metadata is a dict with hints for the template engine or the web front-end.

Keys supported are:

  • 'content_type': the mimetype used for content delivery; “text/html” is assumed if the key is not present or the metadata was not specified
  • 'text': a boolean value indicating whether the Jinja2 auto-escaping feature should be deactivated (text=True) or not (text=False); defaults to False, suitable for generating HTML or XML content
  • 'fragment': a boolean value indicating whether the generated content will be used as part of another page (fragment=True) or as a stand-alone page (fragment=False), the default
  • 'domain': a string value indicating the translation domain to which the translated strings in the template belong to

Note that if template processing should not occur, this method can simply send the response itself (see Request methods) and not return anything, as the Request methods raise a RequestDone exception.

Since 1.0:Clearsilver templates are no longer supported.
Since 1.1.2:the rendering method (xml, xhtml or text) may be returned as a fourth parameter in the tuple, but if not specified it will be inferred from the content_type when rendering the template.
Since 1.3.2:returns a pair, or a tuple in which the third element is a dict instead of a string like in the old API. Note that the old API ((template, data, content_type) where content_type is a string or None) is still supported. When used, this means that template is a legacy Genshi template. This support for the old API will be removed in Trac 1.5.1, in which metadata will always be a dict or None when specified.

Note

The IRequestHandler.process_request method plays a major role during the compatibility period in which both the legacy Genshi templates and the new Jinja2 templates are supported by Trac.

The return type of (template_name, data, content_type) tuple is still supported, and when it is used, it is interpreted as an indication that the template is actually a legacy Genshi template, and not a Jinja2 template. For the same backward compatibility reasons, returning (template, data, None) is interpreted as specifying a content_type of None (i.e. ending up with the "text/html" default).

This support for legacy Genshi templates will be removed in Trac 1.5.1, where only the new API will be supported. At that point, if the third value in the returned tuple is None, this will have the same effect as returning only a (template, data) pair or (template, data, {}) triple (i.e. an empty metadata dict).

class trac.web.api.IRequestFilter

Bases: trac.core.Interface

Enable components to interfere with the processing done by the main handler, either before and/or after it enters in action.

See also trac.web.api.IRequestFilter extension point

post_process_request(req, template, data, metadata=None, method=None)

Do any post-processing the request might need

This typically means adding values to the template data dictionary, or changing the Jinja2 template.

data and metdata may be updated in place.

Always returns a tuple of (template, data) or (template, data, metadata), even if unchanged.

Be aware that returning a (template, data, None) triple will be interpreted as using the legacy API and will indicate that the template is a legacy Genshi template. The same will happen if the third value of the tuple is a string.

The method last parameter is deprecated and is now supposed to be passed as 'method' in the metadata dict. Even better, use directly the 'text' indication (True or False).

Note that template, data, content_type will be None if:
  • called when processing an error page
  • the default request handler did not return any result
Since 1.0:Clearsilver templates are no longer supported.
Since 1.1.2:the rendering method will be passed if it is returned by the request handler, otherwise method will be None. For backward compatibility, the parameter is optional in the implementation’s signature.
Since 1.3.2:Genshi templates are still supported, and if process_request used the old API ((template, data, content_type)), the metadata parameter passed to post_process_request will actually be the content_type value (String or None). This support for the old API will be removed in Trac 1.5.1, in which metadata will always be a dict or None.
pre_process_request(req, handler)

Called after initial handler selection, and can be used to change the selected handler or redirect request.

Always returns the request handler, even if unchanged.

For how the main content itself can be generated, see trac.web.chrome.

class trac.web.api.ITemplateStreamFilter

Bases: trac.core.Interface

Transform the generated content by filtering the Genshi event stream generated by the template, prior to its serialization.

Deprecated:the Genshi template filtering concept doesn’t apply anymore to Jinja2 templates, please consider converting your plugins to perform browser-side modifications of the rendered page using JavaScript. This interface will be removed in Trac 1.5.1.

See TracDev/PortingFromGenshiToJinja#ReplacingITemplateStreamFilter for details.

See also trac.web.api.ITemplateStreamFilter extension point

filter_stream(req, method, filename, stream, data)

Return a filtered Genshi event stream, or the original unfiltered stream if no match.

req is the current request object, method is the Genshi render method (xml, xhtml or text), filename is the filename of the template to be rendered, stream is the event stream and data is the data for the current template.

See the Genshi documentation for more information.

class trac.web.api.IAuthenticator

Bases: trac.core.Interface

Extension point interface for components that can provide the name of the remote user.

See also trac.web.api.IAuthenticator extension point

authenticate(req)

Return the name of the remote user, or None if the identity of the user is unknown.

Classes

class trac.web.api.Request(environ, start_response)

Bases: object

Represents a HTTP request/response pair.

This class provides a convenience API over WSGI.

Create the request wrapper.

Parameters:
  • environ – The WSGI environment dict
  • start_response – The WSGI callback for starting the response
  • callbacks – A dictionary of functions that are used to lazily evaluate attribute lookups
authname

The name associated with the user after authentification or 'anonymous' if no authentification took place.

This corresponds to the remote_user when the request is targeted to an area requiring authentication, otherwise the authname is retrieved from the trac_auth cookie.

href

An Href instance for generating relative URLs pointing to resources within the current Trac environment.

abs_href

An Href instance for generating absolute URLs pointing to resources within the current Trac environment.

add_redirect_listener(listener)

Add a callable to be called prior to executing a redirect.

The callable is passed the arguments to the redirect() call.

base_path

The root path of the application

check_modified(datetime, extra='')

Check the request “If-None-Match” header against an entity tag.

The entity tag is generated from the specified last modified time (datetime), optionally appending an extra string to indicate variants of the requested resource.

That extra parameter can also be a list, in which case the MD5 sum of the list content will be used.

If the generated tag matches the “If-None-Match” header of the request, this method sends a “304 Not Modified” response to the client. Otherwise, it adds the entity tag as an “ETag” header to the response so that consecutive requests can be cached.

end_headers()

Must be called after all headers have been sent and before the actual content is written.

get_header(name)

Return the value of the specified HTTP header, or None if there’s no such header in the request.

is_authenticated

Returns True if authname is not anonymous.

Since:1.3.2
is_xhr

Returns True if the request is an XMLHttpRequest.

Since:1.1.6
method

The HTTP method of the request

path_info

Path inside the application

query_string

Query part of the request

read(size=None)

Read the specified number of bytes from the request body.

redirect(url, permanent=False)

Send a redirect to the client, forwarding to the specified URL.

The url may be relative or absolute, relative URLs will be translated appropriately.

remote_addr

IP address of the remote user

remote_user

Name of the remote user.

Will be None if the user has not logged in using HTTP authentication.

scheme

The scheme of the request URL

send_file(path, mimetype=None)

Send a local file to the browser.

This method includes the “Last-Modified”, “Content-Type” and “Content-Length” headers in the response, corresponding to the file attributes. It also checks the last modification time of the local file against the “If-Modified-Since” provided by the user agent, and sends a “304 Not Modified” response if it matches.

send_header(name, value)

Send the response header with the specified name and value.

value must either be an unicode string or can be converted to one (e.g. numbers, ...)

send_response(code=200)

Set the status code of the response.

server_name

Name of the server

server_port

Port number the server is bound to

write(data)

Write the given data to the response body.

data must be a str string or an iterable instance which iterates str strings, encoded with the charset which has been specified in the 'Content-Type' header or UTF-8 otherwise.

Note that when the 'Content-Length' header is specified, its value either corresponds to the length of data, or, if there are multiple calls to write, to the cumulative length of the data arguments.

class trac.web.api.RequestDone(iterable=None)

Bases: trac.core.TracBaseError

Marker exception that indicates whether request processing has completed and a response was sent.

Helper Functions

trac.web.api.arg_list_to_args(arg_list)

Convert a list of (name, value) tuples into into a _RequestArgs.

trac.web.api.parse_arg_list(query_string)

Parse a query string into a list of (name, value) tuples.

Since 1.1.2:a leading ? is stripped from query_string.
trac.web.api.is_valid_default_handler(handler)

Returns True if the handler is a valid default handler, as described in the IRequestHandler interface documentation.

Exceptions

exception trac.web.api.TracNotImplementedError(message, title=None, show_traceback=False)

Bases: trac.core.TracError, exceptions.NotImplementedError

Raised when a NotImplementedError is trapped.

This exception is for internal use and should not be raised by plugins. Plugins should raise NotImplementedError.

Since:1.0.11

If message is an Element object, everything up to the first <p> will be displayed in the red box, and everything after will be displayed below the red box. If title is given, it will be displayed as the large header above the error message.

exception trac.web.api.HTTPBadGateway(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 502 Bad Gateway

Factory for HTTPException classes.

exception trac.web.api.HTTPBadRequest(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 400 Bad Request

Factory for HTTPException classes.

exception trac.web.api.HTTPConflict(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 409 Conflict

Factory for HTTPException classes.

exception trac.web.api.HTTPExpectationFailed(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 417 Expectation Failed

Factory for HTTPException classes.

exception trac.web.api.HTTPForbidden(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 403 Forbidden

Factory for HTTPException classes.

exception trac.web.api.HTTPGatewayTimeout(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 504 Gateway Timeout

Factory for HTTPException classes.

exception trac.web.api.HTTPGone(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 410 Gone

Factory for HTTPException classes.

exception trac.web.api.HTTPLengthRequired(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 411 Length Required

Factory for HTTPException classes.

exception trac.web.api.HTTPMethodNotAllowed(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 405 Method Not Allowed

Factory for HTTPException classes.

exception trac.web.api.HTTPNotAcceptable(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 406 Not Acceptable

Factory for HTTPException classes.

exception trac.web.api.HTTPNotFound(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 404 Not Found

Factory for HTTPException classes.

exception trac.web.api.HTTPNotImplemented(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 501 Not Implemented

Factory for HTTPException classes.

exception trac.web.api.HTTPPaymentRequired(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 402 Payment Required

Factory for HTTPException classes.

exception trac.web.api.HTTPPreconditionFailed(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 412 Precondition Failed

Factory for HTTPException classes.

exception trac.web.api.HTTPProxyAuthenticationRequired(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 407 Proxy Authentication Required

Factory for HTTPException classes.

exception trac.web.api.HTTPRequestEntityTooLarge(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 413 Request Entity Too Large

Factory for HTTPException classes.

exception trac.web.api.HTTPRequestTimeout(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 408 Request Timeout

Factory for HTTPException classes.

exception trac.web.api.HTTPRequestUriTooLong(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 414 Request-Uri Too Long

Factory for HTTPException classes.

exception trac.web.api.HTTPRequestedRangeNotSatisfiable(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 416 Requested Range Not Satisfiable

Factory for HTTPException classes.

exception trac.web.api.HTTPServiceUnavailable(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 503 Service Unavailable

Factory for HTTPException classes.

exception trac.web.api.HTTPUnauthorized(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 401 Unauthorized

Factory for HTTPException classes.

exception trac.web.api.HTTPUnsupportedMediaType(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 415 Unsupported Media Type

Factory for HTTPException classes.

exception trac.web.api.HTTPVersionNotSupported(detail, *args)

Bases: trac.web.api.HTTPException

Exception for HTTP 505 Http Version Not Supported

Factory for HTTPException classes.