tg.decorators – Decorators

Decorators use by the TurboGears controllers.

Not all of these decorators are traditional wrappers. They are much simplified from the TurboGears 1 decorators, because all they do is register attributes on the functions they wrap, and then the DecoratedController provides the hooks needed to support these decorators.

class tg.decorators.after_render(hook_func)

A list of callables to be run after the template is rendered.

Will be run before it is returned returned up the WSGI stack.

class tg.decorators.before_call(hook_func)

A list of callables to be run before the controller method is called.

class tg.decorators.before_render(hook_func)

A list of callables to be run before the template is rendered.

class tg.decorators.before_validate(hook_func)

A list of callables to be run before validation is performed.

class tg.decorators.cached(key=<class ''>, expire='never', type=None, query_args=None, cache_headers=('content-type', 'content-length'), invalidate_on_startup=False, cache_response=True, **b_kwargs)

Decorator to cache the controller.

The namespace and cache key used to cache the controller are available as request.caching.namespace and request.caching.key. This only caches the controller, not the template, validation or the hooks associated to the controller. If you also want to cache template remember to return tg_cache option with the same cache key from the controller.

The following parameters are accepted:

key - Specifies the controller parameters used to generate the cache key.

NoDefault - Uses function name and parameters (excluding args) as the key (default)

None - No variable key, uses only function name as key

string - Use function name and only “key” parameter

list - Use function name and all parameters listed

Time in seconds before cache expires, or the string “never”. Defaults to “never”
Type of cache to use: dbm, memory, file, memcached, or None for Beaker’s default
A tuple of header names indicating response headers that will also be cached.
If True, the cache will be invalidated each time the application starts or is restarted.

Determines whether the response at the time the cache is used should be cached or not, defaults to True.


When cache_response is set to False, the cache_headers argument is ignored as none of the response is cached.

class tg.decorators.decode_params(format='json')

Decorator that enables parsing parameters from request body.

By default the arguments are parsed in JSON format (which is currently the only supported format).

class tg.decorators.expose(template='', content_type=None, exclude_names=None, custom_format=None, render_params=None, inherit=False)

Register attributes on the decorated function.


Assign a template, you could use the syntax ‘genshi:template’ to use different templates. The default template engine is genshi.


Assign content type. The default content type is ‘text/html’.


Assign exclude names


Registers as a custom format which can later be activated calling use_custom_format


Assign parameters that shall be passed to the rendering method.


Inherit all the decorations from the same method in the parent class. This will let the exposed method expose the same template as the overridden method template and keep the same hooks and validation that the parent method had.

The expose decorator registers a number of attributes on the decorated function, but does not actually wrap the function the way TurboGears 1.0 style expose decorators did.

This means that we don’t have to play any kind of special tricks to maintain the signature of the exposed function.

The exclude_names parameter is new, and it takes a list of keys that ought to be scrubbed from the dictionary before passing it on to the rendering engine. This is particularly useful for JSON.

The render_parameters is also new. It takes a dictionary of arguments that ought to be sent to the rendering engine, like this:

render_params={'method': 'xml', 'doctype': None}

Expose decorator can be stacked like this:

@expose('json', exclude_names='d')
        content_type='text/xml', custom_format='special_xml')
def my_exposed_method(self):
    return dict(a=1, b=2, d="username")

The expose(‘json’) syntax is a special case. json is a rendering engine, but unlike others it does not require a template, and expose assumes that it matches content_type=’application/json’

If you want to declare a desired content_type in a url, you can use the mime-type style dotted notation:

"/mypage.json" ==> for json
"/mypage.html" ==> for text/html
"/mypage.xml" ==> for xml.

If you’re doing an http post, you can also declare the desired content type in the accept headers, with standard content type strings.

By default expose assumes that the template is for html. All other content_types must be explicitly matched to a template and engine.

The last expose decorator example uses the custom_format parameter which takes an arbitrary value (in this case ‘special_xml’). You can then use the use_custom_format() function within the method to decide which of the ‘custom_format’ registered expose decorators to use to render the template.

tg.decorators.override_template(view, template)

Override the template to be used.

Use override_template in a controller method in order to change the template that will be used to render the response dictionary dynamically.

The view argument is the actual controller method for which you want to replace the template.

The template string passed in requires that you include the template engine name, even if you’re using the default.

So you have to pass in a template id string like:


future versions may make the genshi: optional if you want to use the default engine.

class tg.decorators.paginate(name, use_prefix=False, items_per_page=10, max_items_per_page=0)

Paginate a given collection.

This decorator is mainly exposing the functionality of webhelpers.paginate().


You use this decorator as follows:

class MyController(object):

    def sample(self, *args):
        collection = get_a_collection()
        return dict(collection=collection)

To render the actual pager, use:


It is possible to have several paginate()-decorators for one controller action to paginate several collections independently from each other. If this is desired, don’t forget to set the use_prefix-parameter to True.


the collection to be paginated.


the number of items to be rendered. Defaults to 10


the maximum number of items allowed to be set via parameter. Defaults to 0 (does not allow to change that value).


if True, the parameters the paginate decorator renders and reacts to are prefixed with “<name>_”. This allows for multi-pagination.

class tg.decorators.require(predicate, denial_handler=None, smart_denial=False)

Decorator that checks if the specified predicate it met, if it isn’t it calls the denial_handler to prevent access to the decorated method.

The default authorization denial handler of this protector will flash the message of the unmet predicate with warning or error as the flash status if the HTTP status code is 401 or 403, respectively.

  • predicate – An object with a check_authorization(environ) method which must raise a tg.predicates.NotAuthorizedError if not met.
  • denial_handler – The callable to be run if authorization is denied (overrides default_denial_handler if defined).
  • smart_denial – A list of response types for which to trigger the smart denial, which will act as an API providing a pass-through tg.controllers.util.abort(). If True, ('application/json', 'text/xml') will be used.

If called, denial_handler will be passed a positional argument which represents a message on why authorization was denied.

Use allow_only property of TGController for controller-wide authorization.


Authorization denial handler for protectors.

tg.decorators.use_custom_format(controller, custom_format)

Use use_custom_format in a controller in order to change the active @expose decorator when available.

class tg.decorators.validate(validators=None, error_handler=None, form=None, chain_validation=False)

Registers which validators ought to be applied.

If you want to validate the contents of your form, you can use the @validate() decorator to register the validators that ought to be called.

  • validators – A dictionary of FormEncode/TW2 validators, a tg.validation.Convert or any callable that might throw tg.validation.TGValidationError.
  • error_handler – Function or action that should be used to handle the errors.
  • form – A TW2 or ToscaWidgets form to validate ( to be provided instead of validators )
  • chain_validation – Whenever error_handler should perform validation too in case it’s a controller action or not. By default it’s disabled.

The first positional parameter can either be a dictonary of validators, a FormEncode schema validator, or a callable which acts like a FormEncode validator.

class tg.decorators.with_engine(engine_name=None, master_params=None)

Decorator to force usage of a specific database engine in TurboGears SQLAlchemy BalancedSession.

  • engine_name – ‘master’ or the name of one of the slaves, if is None it will not force any specific engine.
  • master_params – A dictionary or GET parameters that when present will force usage of the master node. The keys of the dictionary will be the name of the parameters to look for, while the values must be whenever to pop the parameter from the parameters passed to the controller (True/False). If master_params is a list then it is converted to a dictionary where the keys are the entries of the list and the value is always True.