Table Of Contents

Previous topic

Preparing a Release of TurboGears

TurboGears Reference

This page provides a quick access reference to the classes and functions provided by TurboGears

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.Decoration(controller)

Simple class to support ‘simple registration’ type decorators

lookup_template_engine(tgl)

Return the template engine data.

Provides a convenience method to get the proper engine, content_type, template, and exclude_names for a particular tg_format (which is pulled off of the request headers).

register_custom_template_engine(custom_format, content_type, engine, template, exclude_names, render_params)

Registers a custom engine on the controller.

Multiple engines can be registered, but only one engine per custom_format.

The engine is registered when @expose is used with the custom_format parameter and controllers render using this engine when the use_custom_format() function is called with the corresponding custom_format.

exclude_names keeps track of a list of keys which will be removed from the controller’s dictionary before it is loaded into the template. This allows you to exclude some information from JSONification, and other ‘automatic’ engines which don’t require a template.

render_params registers extra parameters which will be sent to the rendering method. This allows you to influence things like the rendering method or the injected doctype.

register_template_engine(content_type, engine, template, exclude_names, render_params)

Registers an engine on the controller.

Multiple engines can be registered, but only one engine per content_type. If no content type is specified the engine is registered at / which is the default, and will be used whenever no content type is specified.

exclude_names keeps track of a list of keys which will be removed from the controller’s dictionary before it is loaded into the template. This allows you to exclude some information from JSONification, and other ‘automatic’ engines which don’t require a template.

render_params registers extra parameters which will be sent to the rendering method. This allows you to influence things like the rendering method or the injected doctype.

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.expose(template='', content_type=None, exclude_names=None, custom_format=None, render_params=None, inherit=False)

Register attributes on the decorated function.

Parameters:
template

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

content_type

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

exclude_names

Assign exclude names

custom_format

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

render_params

Assign parameters that shall be passed to the rendering method.

inherit

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')
@expose('kid:blogtutorial.templates.test_form',
        content_type='text/html')
@expose('kid:blogtutorial.templates.test_form_xml',
        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(controller, template)

Override the template to be used.

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

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:

"genshi:myproject.templates.index2"

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().

Usage:

You use this decorator as follows:

class MyController(object):

    @expose()
    @paginate("collection")
    def sample(self, *args):
        collection = get_a_collection()
        return dict(collection=collection)

To render the actual pager, use:

${tmpl_context.paginators.<name>.pager()}

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.

Parameters:
name

the collection to be paginated.

items_per_page

the number of items to be rendered. Defaults to 10

max_items_per_page

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

use_prefix

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)

TurboGears-specific action protector.

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.

See allow_only for controller-wide authorization.

default_denial_handler(reason)

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)

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.

Parameters:
validators

Pass in a dictionary of FormEncode validators. The keys should match the form field names.

error_handler

Pass in the controller method which shoudl be used to handle any form errors

form

Pass in a ToscaWidget based form with validators

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={})

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

Parameters:
  • 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 paramter 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.

Validation

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

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.

Parameters:
validators

Pass in a dictionary of FormEncode validators. The keys should match the form field names.

error_handler

Pass in the controller method which shoudl be used to handle any form errors

form

Pass in a ToscaWidget based form with validators

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

exception tg.validation.TGValidationError(msg, value=None, error_dict=None)

Invalid data was encountered during validation.

The constructor can be passed a short message with the reason of the failed validation.

Authorization

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

TurboGears-specific action protector.

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.

See allow_only for controller-wide authorization.

Built-in predicate checkers.

This is mostly took from repoze.what.precidates

This is module provides the predicate checkers that were present in the original “identity” framework of TurboGears 1, plus others.

class tg.predicates.CompoundPredicate(*predicates, **kwargs)

A predicate composed of other predicates.

class tg.predicates.All(*predicates, **kwargs)

Check that all of the specified predicates are met.

Parameters:predicates – All of the predicates that must be met.

Example:

# Grant access if the current month is July and the user belongs to
# the human resources group.
p = All(is_month(7), in_group('hr'))
evaluate(environ, credentials)

Evaluate all the predicates it contains.

Parameters:
  • environ – The WSGI environment.
  • credentials – The repoze.what credentials.
Raises NotAuthorizedError:
 

If one of the predicates is not met.

class tg.predicates.Any(*predicates, **kwargs)

Check that at least one of the specified predicates is met.

Parameters:predicates – Any of the predicates that must be met.

Example:

# Grant access if the currest user is Richard Stallman or Linus
# Torvalds.
p = Any(is_user('rms'), is_user('linus'))
evaluate(environ, credentials)

Evaluate all the predicates it contains.

Parameters:
  • environ – The WSGI environment.
  • credentials – The repoze.what credentials.
Raises NotAuthorizedError:
 

If none of the predicates is met.

class tg.predicates.has_all_permissions(*permissions, **kwargs)

Check that the current user has been granted all of the specified permissions.

Parameters:permissions – The names of all the permissions that must be granted to the user.

Example:

p = has_all_permissions('view-users', 'edit-users')
class tg.predicates.has_any_permission(*permissions, **kwargs)

Check that the user has at least one of the specified permissions.

Parameters:permissions – The names of any of the permissions that have to be granted to the user.

Example:

p = has_any_permission('manage-users', 'edit-users')
class tg.predicates.has_permission(permission_name, **kwargs)

Check that the current user has the specified permission.

Parameters:permission_name – The name of the permission that must be granted to the user.

Example:

p = has_permission('hire')
class tg.predicates.in_all_groups(*groups, **kwargs)

Check that the user belongs to all of the specified groups.

Parameters:groups – The name of all the groups the user must belong to.

Example:

p = in_all_groups('developers', 'designers')
class tg.predicates.in_any_group(*groups, **kwargs)

Check that the user belongs to at least one of the specified groups.

Parameters:groups – The name of any of the groups the user may belong to.

Example:

p = in_any_group('directors', 'hr')
class tg.predicates.in_group(group_name, **kwargs)

Check that the user belongs to the specified group.

Parameters:group_name (str) – The name of the group to which the user must belong.

Example:

p = in_group('customers')
class tg.predicates.is_user(user_name, **kwargs)

Check that the authenticated user’s username is the specified one.

Parameters:user_name (str) – The required user name.

Example:

p = is_user('linus')
class tg.predicates.is_anonymous(msg=None)

Check that the current user is anonymous.

Example:

# The user must be anonymous!
p = is_anonymous()

New in version 1.0.7.

class tg.predicates.not_anonymous(msg=None)

Check that the current user has been authenticated.

Example:

# The user must have been authenticated!
p = not_anonymous()

Configuration

class tg.configuration.AppConfig(minimal=False, root_controller=None)

Class to store application configuration.

This class should have configuration/setup information that is necessary for proper application function. Deployment specific configuration information should go in the config files (e.g. development.ini or deployment.ini).

AppConfig instances have a number of methods that are meant to be overridden by users who wish to have finer grained control over the setup of the WSGI environment in which their application is run.

This is the place to configure custom routes, transaction handling, error handling, etc.

add_auth_middleware(app, skip_authentication)

Configure authentication and authorization.

Parameters:
  • app – The TG2 application.
  • skip_authentication (bool) – Should authentication be skipped if explicitly requested? (used by repoze.who-testutil)
add_core_middleware(app)

Add support for routes dispatch, sessions, and caching. This is where you would want to override if you wanted to provide your own routing, session, or caching middleware. Your app_cfg.py might look something like this:

from tg.configuration import AppConfig
from routes.middleware import RoutesMiddleware
from beaker.middleware import CacheMiddleware
from mysessionier.middleware import SessionMiddleware

class MyAppConfig(AppConfig):
    def add_core_middleware(self, app):
        app = RoutesMiddleware(app, config['routes.map'])
        app = SessionMiddleware(app, config)
        app = CacheMiddleware(app, config)
        return app
base_config = MyAppConfig()
add_error_middleware(global_conf, app)

Add middleware which handles errors and exceptions.

add_ming_middleware(app)

Set up the ming middleware for the unit of work

add_sqlalchemy_middleware(app)

Set up middleware that cleans up the sqlalchemy session.

The default behavior of TG 2 is to clean up the session on every request. Only override this method if you know what you are doing!

add_tm_middleware(app)

Set up the transaction management middleware.

To abort a transaction inside a TG2 app:

import transaction
transaction.doom()

By default http error responses also roll back transactions, but this behavior can be overridden by overriding base_config.commit_veto.

add_tosca2_middleware(app)

Configure the ToscaWidgets2 middleware.

If you would like to override the way the TW2 middleware works, you might do change your app_cfg.py to add something like:

from tg.configuration import AppConfig
from tw2.core.middleware import TwMiddleware

class MyAppConfig(AppConfig):

    def add_tosca2_middleware(self, app):

        app = TwMiddleware(app,
            default_engine=self.default_renderer,
            translator=ugettext,
            auto_reload_templates = False
            )

        return app
base_config = MyAppConfig()

The above example would always set the template auto reloading off. (This is normally an option that is set within your application’s ini file.)

add_tosca_middleware(app)

Configure the ToscaWidgets middleware.

If you would like to override the way the TW middleware works, you might do something like:

from tg.configuration import AppConfig
from tw.api import make_middleware as tw_middleware

class MyAppConfig(AppConfig):

    def add_tosca2_middleware(self, app):

        app = tw_middleware(app, {
            'toscawidgets.framework.default_view': self.default_renderer,
            'toscawidgets.framework.translator': ugettext,
            'toscawidgets.middleware.inject_resources': False,
            })
        return app

base_config = MyAppConfig()

The above example would disable resource injection.

There is more information about the settings you can change in the ToscaWidgets middleware. <http://toscawidgets.org/documentation/ToscaWidgets/modules/middleware.html>

after_init_config()

Override this method to set up configuration variables at the application level. This method will be called after your configuration object has been initialized on startup. Here is how you would use it to override the default setting of tg.strict_tmpl_context

from tg.configuration import AppConfig
from tg import config

class MyAppConfig(AppConfig):
    def after_init_config(self):
        config['tg.strict_tmpl_context'] = False

base_config = MyAppConfig()
make_load_environment()

Return a load_environment function.

The returned load_environment function can be called to configure the TurboGears runtime environment for this particular application. You can do this dynamically with multiple nested TG applications if necessary.

register_rendering_engine(factory)

Registers a rendering engine factory.

Rendering engine factories are tg.renderers.base.RendererFactory subclasses in charge of creating a rendering engine.

register_wrapper(wrapper, after=None)

Registers a TurboGears application wrapper.

Application wrappers are like WSGI middlewares but are executed in the context of TurboGears and work with abstractions like Request and Respone objects.

Application wrappers are callables built by passing the next handler in chain and the current TurboGears configuration.

Every wrapper, when called, is expected to accept the WSGI environment and a TurboGears context as parameters and are expected to return a tg.request_local.Response instance:

class AppWrapper(object):
    def __init__(self, handler, config):
        self.handler = handler

    def __call__(self, environ, context):
        print 'Going to run %s' % context.request.path
        return self.handler(environ, context)
setup_auth()

Override this method to define how you would like the authentication options to be setup for your application.

setup_helpers_and_globals()

Add helpers and globals objects to the config.

Override this method to customize the way that app_globals and helpers are setup.

setup_ming()

Setup MongoDB database engine using Ming

setup_persistence()

Override this method to define how your application configures it’s persistence model. the default is to setup sqlalchemy from the cofiguration file, but you might choose to set up a persistence system other than sqlalchemy, or add an additional persistence layer. Here is how you would go about setting up a ming (mongo) persistence layer:

class MingAppConfig(AppConfig):
    def setup_persistence(self):
        self.ming_ds = DataStore(config['mongo.url'])
        session = Session.by_name('main')
        session.bind = self.ming_ds
setup_routes()

Setup the default TG2 routes

Override this and setup your own routes maps if you want to use custom routes.

It is recommended that you keep the existing application routing in tact, and just add new connections to the mapper above the routes_placeholder connection. Lets say you want to add a tg controller SamplesController, inside the controllers/samples.py file of your application. You would augment the app_cfg.py in the following way:

from routes import Mapper
from tg.configuration import AppConfig

class MyAppConfig(AppConfig):
    def setup_routes(self):
        map = Mapper(directory=config['paths']['controllers'],
                    always_scan=config['debug'])

        # Add a Samples route
        map.connect('/samples/', controller='samples', action=index)

        # Setup a default route for the root of object dispatch
        map.connect('*url', controller='root', action='routes_placeholder')

        config['routes.map'] = map


base_config = MyAppConfig()
setup_sqlalchemy()

Setup SQLAlchemy database engine.

The most common reason for modifying this method is to add multiple database support. To do this you might modify your app_cfg.py file in the following manner:

from tg.configuration import AppConfig, config
from myapp.model import init_model

# add this before base_config =
class MultiDBAppConfig(AppConfig):
    def setup_sqlalchemy(self):
        '''Setup SQLAlchemy database engine(s)'''
        from sqlalchemy import engine_from_config
        engine1 = engine_from_config(config, 'sqlalchemy.first.')
        engine2 = engine_from_config(config, 'sqlalchemy.second.')
        # engine1 should be assigned to sa_engine as well as your first engine's name
        config['tg.app_globals'].sa_engine = engine1
        config['tg.app_globals'].sa_engine_first = engine1
        config['tg.app_globals'].sa_engine_second = engine2
        # Pass the engines to init_model, to be able to introspect tables
        init_model(engine1, engine2)

#base_config = AppConfig()
base_config = MultiDBAppConfig()

This will pull the config settings from your .ini files to create the necessary engines for use within your application. Make sure you have a look at Using Multiple Databases In TurboGears for more information.

setup_tg_wsgi_app(load_environment=None)

Create a base TG app, with all the standard middleware.

load_environment
A required callable, which sets up the basic evironment needed for the application.
setup_vars
A dictionary with all special values necessary for setting up the base wsgi app.
class tg.wsgiapp.TGApp(config=None, **kwargs)
dispatch(controller, environ, context)

Dispatches to a controller, the controller itself is expected to implement the routing system.

Override this to change how requests are dispatched to controllers.

find_controller(controller)

Locates a controller by attempting to import it then grab the SomeController instance from the imported module.

Override this to change how the controller object is found once the URL has been resolved.

resolve(environ, context)

Uses dispatching information found in environ['wsgiorg.routing_args'] to retrieve a controller name and return the controller instance from the appropriate controller module.

Override this to change how the controller name is found and returned.

setup_app_env(environ)

Setup Request, Response and TurboGears context objects.

Is also in charge of pushing TurboGears context into the paste registry and detect test mode. Returns whenever the testmode is enabled or not and the TurboGears context.

setup_pylons_compatibility(environ, controller)

Updates environ to be backward compatible with Pylons

WebFlash

Flash messaging system for sending info to the user in a non-obtrusive way

class tg.flash.TGFlash(cookie_name='webflash', default_status='ok')

Flash Message Creator

tg.flash.get_flash()

Get the message previously set by calling flash().

Additionally removes the old flash message.

tg.flash.get_status()

Get the status of the last flash message.

Additionally removes the old flash message status.

Rendering

tg.render.cached_template(template_name, render_func, ns_options=(), cache_key=None, cache_type=None, cache_expire=None, **kwargs)

Cache and render a template, took from Pylons

Cache a template to the namespace template_name, along with a specific key if provided.

Basic Options

template_name
Name of the template, which is used as the template namespace.
render_func
Function used to generate the template should it no longer be valid or doesn’t exist in the cache.
ns_options
Tuple of strings, that should correspond to keys likely to be in the kwargs that should be used to construct the namespace used for the cache. For example, if the template language supports the ‘fragment’ option, the namespace should include it so that the cached copy for a template is not the same as the fragment version of it.

Caching options (uses Beaker caching middleware)

cache_key
Key to cache this copy of the template under.
cache_type
Valid options are dbm, file, memory, database, or memcached.
cache_expire
Time in seconds to cache this template with this cache_key for. Or use ‘never’ to designate that the cache should never expire.

The minimum key required to trigger caching is cache_expire='never' which will cache the template forever seconds with no key.

Request & Response

class tg.request_local.Request(environ, charset=None, unicode_errors=None, decode_param_names=None, **kw)

WebOb Request subclass

The WebOb webob.Request has no charset, or other defaults. This subclass adds defaults, along with several methods for backwards compatibility with paste.wsgiwrappers.WSGIRequest.

Extract a signed cookie of name from the request

The cookie is expected to have been created with Response.signed_cookie, and the secret should be the same as the one used to sign it.

Any failure in the signature of the data will result in None being returned.

class tg.request_local.Response(body=None, status=None, headerlist=None, app_iter=None, content_type=None, conditional_response=None, **kw)

WebOb Response subclass

content

The body of the response, as a str. This will read in the entire app_iter if necessary.

Save a signed cookie with secret signature

Saves a signed cookie of the pickled data. All other keyword arguments that WebOb.set_cookie accepts are usable and passed to the WebOb set_cookie method after creating the signed cookie value.