This page provides a quick access reference to the classes and functions provided by TurboGears
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.
Simple class to support ‘simple registration’ type decorators
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).
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.
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.
A list of callables to be run after the template is rendered.
Will be run before it is returned returned up the WSGI stack.
A list of callables to be run before the controller method is called.
A list of callables to be run before the template is rendered.
A list of callables to be run before validation is performed.
Register attributes on the decorated function.
Parameters: |
|
---|
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.
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.
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: |
|
---|
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.
Authorization denial handler for protectors.
Use use_custom_format in a controller in order to change the active @expose decorator when available.
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: |
|
---|
The first positional parameter can either be a dictonary of validators, a FormEncode schema validator, or a callable which acts like a FormEncode validator.
Decorator to force usage of a specific database engine in TurboGears SQLAlchemy BalancedSession.
Parameters: |
|
---|
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: |
|
---|
The first positional parameter can either be a dictonary of validators, a FormEncode schema validator, or a callable which acts like a FormEncode validator.
Invalid data was encountered during validation.
The constructor can be passed a short message with the reason of the failed validation.
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.
A predicate composed of other predicates.
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 all the predicates it contains.
Parameters: |
|
---|---|
Raises NotAuthorizedError: | |
If one of the predicates is not met. |
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 all the predicates it contains.
Parameters: |
|
---|---|
Raises NotAuthorizedError: | |
If none of the predicates is met. |
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')
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')
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')
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')
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')
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')
Check that the authenticated user’s username is the specified one.
Parameters: | user_name (str) – The required user name. |
---|
Example:
p = is_user('linus')
Check that the current user is anonymous.
Example:
# The user must be anonymous!
p = is_anonymous()
New in version 1.0.7.
Check that the current user has been authenticated.
Example:
# The user must have been authenticated!
p = not_anonymous()
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: |
|
---|
TurboGears Pagination support for @paginate decorator. It is based on a striped down version of the WebHelpers pagination class This represents a page inside a collection of items
Return string with links to other pages (e.g. “1 2 [3] 4 5 6 7”).
Format string that defines how the pager is rendered. The string can contain the following $-tokens that are substituted by the string.Template module:
To render a range of pages the token ‘~3~’ can be used. The number sets the radius of pages around the current page. Example for a range with radius 3:
‘1 .. 5 6 7 [8] 9 10 11 .. 500’
Default: ‘~2~’
String to be displayed as the text for the %(link_first)s link above.
Default: ‘<<’
String to be displayed as the text for the %(link_last)s link above.
Default: ‘>>’
String to be displayed as the text for the %(link_previous)s link above.
Default: ‘<’
String to be displayed as the text for the %(link_next)s link above.
Default: ‘>’
String that is used to separate page links/numbers in the above range of pages.
Default: ‘ ‘
When using AJAX/AJAH to do partial updates of the page area the application has to know whether a partial update (only the area to be replaced) or a full update (reloading the whole page) is required. So this parameter is the name of the URL parameter that gets set to 1 if the ‘onclick’ parameter is used. So if the user requests a new page through a Javascript action (onclick) then this parameter gets set and the application is supposed to return a partial content. And without Javascript this parameter is not set. The application thus has to check for the existence of this parameter to determine whether only a partial or a full page needs to be returned. See also the examples in this modules docstring.
Default: ‘partial’
Note: If you set this argument and are using a URL generator callback, the callback must accept this name as an argument instead of ‘partial’.
if True the navigator will be shown even if there is only one page
Default: False
A dictionary of attributes that get added to A-HREF links pointing to other pages. Can be used to define a CSS style or class to customize the look of links.
Example: { ‘style’:’border: 1px solid green’ }
Default: { ‘class’:’pager_link’ }
A dictionary of attributes that get added to the current page number in the pager (which is obviously not a link). If this dictionary is not empty then the elements will be wrapped in a SPAN tag with the given attributes.
Example: { ‘style’:’border: 3px solid blue’ }
Default: { ‘class’:’pager_curpage’ }
A dictionary of attributes that get added to the ‘..’ string in the pager (which is obviously not a link). If this dictionary is not empty then the elements will be wrapped in a SPAN tag with the given attributes.
Example: { ‘style’:’color: #808080’ }
Default: { ‘class’:’pager_dotdot’ }
A string with the template used to render page links
Default: ‘<a%s>%s</a>’
A string with the template used to render current page, and dots in pagination.
Default: ‘<span%s>%s</span>’
This paramter is a string containing optional Javascript code that will be used as the ‘onclick’ action of each pager link. It can be used to enhance your pager with AJAX actions loading another page into a DOM object.
In this string the variable ‘$partial_url’ will be replaced by the URL linking to the desired page with an added ‘partial=1’ parameter (or whatever you set ‘partial_param’ to). In addition the ‘$page’ variable gets replaced by the respective page number.
Note that the URL to the destination page contains a ‘partial_param’ parameter so that you can distinguish between AJAX requests (just refreshing the paginated area of your page) and full requests (loading the whole new page).
[Backward compatibility: you can use ‘%s’ instead of ‘$partial_url’]
Additional keyword arguments are used as arguments in the links.
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.
Configure authentication and authorization.
Parameters: |
|
---|
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 middleware which handles errors and exceptions.
Set up the ming middleware for the unit of work
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!
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.
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.)
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>
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()
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.
Registers a rendering engine factory.
Rendering engine factories are tg.renderers.base.RendererFactory subclasses in charge of creating a rendering engine.
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)
Override this method to define how you would like the authentication options to be setup for your application.
Add helpers and globals objects to the config.
Override this method to customize the way that app_globals and helpers are setup.
Setup MongoDB database engine using Ming
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 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 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.
Create a base TG app, with all the standard middleware.
Dispatches to a controller, the controller itself is expected to implement the routing system.
Override this to change how requests are dispatched to controllers.
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.
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 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.
Updates environ to be backward compatible with Pylons
Flash messaging system for sending info to the user in a non-obtrusive way
Flash Message Creator
Get the message previously set by calling flash().
Additionally removes the old flash message.
Get the status of the last flash message.
Additionally removes the old flash message status.
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
Caching options (uses Beaker caching middleware)
The minimum key required to trigger caching is cache_expire='never' which will cache the template forever seconds with no key.
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.
WebOb Response subclass
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.