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.
Decorator to cache the controller, if you also want to cache template remember to return tg_cache option from the controller.
The following parameters are accepted:
NoDefault - Uses function name and all request parameters 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
Determines whether the response at the time the cache is used should be cached or not, defaults to True.
Note
When cache_response is set to False, the cache_headers argument is ignored as none of the response is cached.
Decorator that enables parsing parameters from request body.
By default the arguments are parsed in JSON format (which is currently the only supported format).
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 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:
"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: |
|
---|
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.
Parameters: |
|
---|
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.
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: |
|
---|
Works like python @property but the decorated function only gets executed once, successive accesses to the property will just return the value previously stored into the object.
The @cached_property decorator can be executed within a provided context, for example to make the cached property thread safe a Lock can be provided:
from threading import Lock
from tg.caching import cached_property
class MyClass(object):
@cached_property
def my_property(self):
return 'Value!'
my_property.context = Lock()
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.
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.
Parameters: |
|
---|
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.
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 middlewares
Those are all deprecated middlewares and will be removed in future TurboGears versions as they have been replaced by other tools.
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[‘tm.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 TurboGears controller wrapper.
Controller Wrappers are much like a decorator applied to every controller. They receive tg.configuration.AppConfig instance as an argument and the next handler in chain and are expected to return a new handler that performs whatever it requires and then calls the next handler.
A simple example for a controller wrapper is a simple logging wrapper:
def controller_wrapper(app_config, caller):
def call(*args, **kw):
try:
print 'Before handler!'
return caller(*args, **kw)
finally:
print 'After Handler!'
return call
base_config.register_controller_wrapper(controller_wrapper)
It is also possible to register wrappers for a specific controller:
base_config.register_controller_wrapper(controller_wrapper, controller=RootController.index)
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.
See tg.appwrappers.base.ApplicationWrapper for complete definition of application wrappers.
The after parameter defines their position into the wrappers chain. The default value None means they are executed in a middle point, so they run after the TurboGears wrappers like ErrorPageApplicationWrapper which can intercept their response and return an error page.
Builtin TurboGears wrappers are usually registered with after=True which means they run furthest away from the application itself and can intercept the response of any other wrapper.
Providing after=False means the wrapper will be registered near to the application itself (so wrappers registered at default position and with after=True will be able to see its response).
after parameter can also accept an application wrapper class. In such case the registered wrapper will be registered right after the specified wrapper and so will be a little further from the application then the specified one (can see the response of the specified one).
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
Support for flash messages stored in a plain cookie.
Supports both fetching flash messages on server side and on client side through Javascript.
When used from Python itself, the flash object provides a TGFlash.render() method that can be used from templates to render the flash message.
When used on Javascript, calling the TGFlash.render() provides a webflash javascript object which exposes .payload() and .render() methods that can be used to get current message and render it from javascript.
For a complete list of options supported by Flash objects see TGFlash.configure().
Flash messages can be configured through AppConfig (app_cfg.base_config) using the following options:
Get only current flash message, getting the flash message will delete the cookie.
Fetch current flash message, status and related information.
Fetching flash message deletes the associated cookie.
Render the flash message inside template or provide Javascript support for them.
container_id is the DIV where the messages will be displayed, while use_js switches between rendering the flash as HTML or for Javascript usage.
Get only current flash status, getting the flash status will delete the cookie.
Renders a specific template in current TurboGears context.
Permits to manually render any template like TurboGears would for expositions. It also guarantees that the before_render_call and after_render_call hooks are called in the process.
Parameters: |
|
---|
TurboGears injects some additional variables in the template context, those include:
- tg.config -> like tg.config in controllers
- tg.flash_obj -> the flash object, call render on it to display it.
- tg.quote_plus -> function to perform percentage escaping (%xx)
- tg.url -> like tg.url in controllers
- tg.identity -> like tg.request.identity in controllers
- tg.session -> like tg.session in controllers
- tg.locale -> Languages of the current request
- tg.errors -> Validation errors
- tg.inputs -> Values submitted for validation
- tg.request -> like tg.request in controllers
- tg.auth_stack_enabled -> if authentication is enabled or not
- tg.predicates -> like tg.predicates in controllers
- tmpl_context -> like tg.tmpl_context in controllers
- response -> like tg.response in controllers
- request -> like tg.request in controllers
- config -> like tg.config in controllers
- app_globals -> like tg.app_globals in controllers
- session -> like tg.session in controllers
- url -> like tg.url in controllers
- h -> Your application helpers
- translator -> The current gettext translator
- _ -> like tg.i18n.ugettext
Additional variables can be added to every template by a variable_provider function inside the application configuration. This function is expected to return a dict with any variable that should be added the default template variables. It can even replace existing variables.
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.
Factory that creates one or multiple rendering engines for TurboGears. Subclasses have to be registered with tg.configuration.AppConfig.register_rendering_engine() and must implement the create method accordingly.
Given the TurboGears configuration and application globals it must create a rendering engine for each one specified into the engines list.
It must return a dictionary in the form:
{'engine_name': rendering_engine_callable,
'other_engine': other_rendering_callable}
Rendering engine callables are callables in the form:
func(template_name, template_vars,
cache_key=None, cache_type=None, cache_expire=None,
**render_params)
render_params parameter will contain all the values provide through @expose(render_params={}).
Here specify the list of engines for which this factory will create a rendering engine and their options. They must be specified like:
engines = {'json': {'content_type': 'application/json'}}
Currently only supported option is content_type.
Here specify if turbogears variables have to be injected in the template context before using any of the declared engines. Usually True unless engines are protocols (ie JSON).
TurboGears custom JSONEncoder.
Provides support for encoding objects commonly used in TurboGears apps, like:
- SQLAlchemy queries
- Ming queries
- Dates
- Decimals
- Generators
Support for additional types is provided through the __json__ method that will be called on the object by the JSONEncoder when provided and through the ability to register custom encoder for specific types using JSONEncoder.register_custom_encoder().
JSON encoder can be configured through AppConfig (app_cfg.base_config) using the following options:
Register a custom encoder for the given type.
Instead of using standard behavior for encoding the given type to JSON, the encoder will used instead. encoder must be a callable that takes the object as argument and returns an object that can be encoded in JSON (usually a dict).
Return a JSON string representation of a Python object.
Encode object, yielding each string representation as available.
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.
Manages hooks registrations and notifications
Disconnect an hook.
The registered function is removed from the hook notification list.
Notifies a TurboGears hook.
Each function registered for the given hook will be executed, args and kwargs will be passed to the registered functions as arguments.
It permits to notify both application hooks:
tg.hooks.notify('custom_global_hook')
Or controller hooks:
tg.hooks.notify('before_render', args=(remainder, params, output),
controller=RootController.index)
Notifies a TurboGears hook which is expected to return a value.
hooks with values are expected to accept an input value an return a replacement for it. Each registered function will receive as input the value returned by the previous function in chain.
The resulting value will be returned by the notify_with_value call itself:
app = tg.hooks.notify_with_value('before_config', app)
Registers a TurboGears hook.
Given an hook name and a function it registers the provided function for that role. For a complete list of hooks provided by default have a look at Hooks and Wrappers.
It permits to register hooks both application wide or for specific controllers:
tg.hooks.register('before_render', hook_func, controller=RootController.index)
tg.hooks.register('startup', startup_function)
Basic interface of the TurboGears Application Wrappers.
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 can be registered using AppConfig.register_wrapper() which will inject them into the next TGApp created.
While they can be any callable, inheriting from this base class is strongly suggested as enables additional behaviours and third party code might depend on them.
Application Wrappers require a next_handler which is the next handler to call in the chain and config which is the current application configuration.
This is the actual wrapper implementation.
Wrappers are called for each request with the controller in charge of handling the request, the environ of the request and the TurboGears context of the request.
They should call the next_handler (which will accept the same parameters) and return a tg.request_local.Response instance which is the request response. Usually they will return the same response object provided by the next handler unless they want to replace it.
A simple logging wrapper might look like:
class LogAppWrapper(ApplicationWrapper):
def __init__(self, handler, config):
super(LogAppWrapper, self).__init__(handler, config)
def __call__(self, controller, environ, context):
print 'Going to run %s' % context.request.path
return self.next_handler(controller, environ, context)
Whenever the Application Wrapper should be injected.
By default all application wrappers are injected into the wrappers chain, you might want to make so that they are injected or not depending on configuration options.
The next handler in the chain
Tracks actions that need to be performed when a specific configuration point is reached and required options are correctly initialized
Marks the milestone as reached.
Runs the registered actions. Calling this method multiple times should lead to nothing.
Registers an action to be called on milestone completion.
If milestone is already passed action is immediately called
Set the current language(s) used for translations in current call and session.
languages should be a string or a list of strings. First lang will be used as main lang, others as fallbacks.
Return the current i18n languages used
returns None if no supported language is available (no translations are in place) or a list of languages.
In case all parameter is False only the languages for which the application is providing a translation are returned. Otherwise all the languages preferred by the user are returned.
Add a fallback language from which words not matched in other languages will be translated to.
This fallback will be associated with the currently selected language – that is, resetting the language via set_lang() resets the current fallbacks.
This function can be called multiple times to add multiple fallbacks.
Set the current request language(s) used for translations without touching the session language.
languages should be a string or a list of strings. First lang will be used as main lang, others as fallbacks.
Mark a string for translation. Returns the localized unicode string of value.
Mark a string to be localized as follows:
_('This should be in lots of languages')
Lazy-evaluated version of the ugettext function
string of value.
Mark a string to be localized as follows:
_('This should be in lots of languages')
Mark a string for translation. Returns the localized unicode string of the pluralized value.
This does a plural-forms lookup of a message id. singular is used as the message id for purposes of lookup in the catalog, while n is used to determine which plural form to use. The returned message is a Unicode string.
Mark a string to be localized as follows:
ungettext('There is %(num)d file here', 'There are %(num)d files here',
n) % {'num': n}
Lazy-evaluated version of the ungettext function
string of the pluralized value.
This does a plural-forms lookup of a message id. singular is used as the message id for purposes of lookup in the catalog, while n is used to determine which plural form to use. The returned message is a Unicode string.
Mark a string to be localized as follows:
ungettext('There is %(num)d file here', 'There are %(num)d files here',
n) % {'num': n}
Helper functions for controller operation.
URL definition and browser redirection are defined here.
Generate an absolute URL that’s specific to this application.
The URL function takes a string (base_url) and, appends the SCRIPT_NAME and adds parameters for all of the parameters passed into the params dict.
Like tg.url but is lazily evaluated.
This is useful when creating global variables as no request is in place.
As without a request it wouldn’t be possible to correctly calculate the url using the SCRIPT_NAME this demands the url resolution to when it is displayed for the first time.
Generate an HTTP redirect.
The function raises an exception internally, which is handled by the framework. The URL may be either absolute (e.g. http://example.com or /myfile.html) or relative. Relative URLs are automatically converted to absolute URLs. Parameters may be specified, which are appended to the URL. This causes an external redirect via the browser; if the request is POST, the browser will issue GET for the second request.
Use the HTTP Entity Tag cache for Browser side caching
If a “If-None-Match” header is found, and equivilant to key, then a 304 HTTP message will be returned with the ETag to tell the browser that it should use its current cache of the page.
Otherwise, the ETag header will be added to the response headers.
Aborts the request immediately by returning an HTTP exception
In the event that the status_code is a 300 series error, the detail attribute will be used as the Location header should one not be specified in the headers attribute.
When True instead of displaying the custom error document for errors or the authentication page for failed authorizations the response will just pass through as is.
Set to "json" to send out the response body in JSON format.
When True instead of immediately abort the request it will create a callable that can be used as @validate error_handler.
A common case is abort(404, error_handler=True) as error_handler for validation that retrieves objects from database:
from formencode.validators import Wrapper
@validate({'team': Wrapper(to_python=lambda value:
Group.query.find({'group_name': value}).one())},
error_handler=abort(404, error_handler=True))
def view_team(self, team):
return dict(team=team)
Forces user logout if authentication is enabled.
Forces user login if authentication is enabled.
As TurboGears identifies users by user_name the passed parameter should be anything your application declares being the user_name field in models.
Returns a Response object with validation errors.
The response will be created with a 412 Precondition Failed status code and errors are reported in JSON format as response body.
Typical usage is as error_handler for JSON based api:
@expose('json')
@validate({'display_name': validators.NotEmpty(),
'group_name': validators.NotEmpty()},
error_handler=validation_errors_response)
def post(self, **params):
group = Group(**params)
return dict(group=group)
Utilities
A dictionary that provides attribute-style access.
this class implements a cache system above the get_dotted_filename function and is designed to be stuffed inside the app_globals.
It exposes a method named get_dotted_filename with the exact same signature as the function of the same name in this module.
The reason is that is uses this function itself and just adds caching mechanism on top.
this helper function is designed to search a template or any other file by python module name.
Given a string containing the file/template name passed to the @expose decorator we will return a resource useable as a filename even if the file is in fact inside a zipped egg.
The actual implementation is a revamp of the Genshi buffet support plugin, but could be used with any kind a file inside a python package.
@param template_name: the string representation of the template name as it has been given by the user on his @expose decorator. Basically this will be a string in the form of: “genshi:myapp.templates.somename” @type template_name: string
@param template_extension: the extension we excpect the template to have, this MUST be the full extension as returned by the os.path.splitext function. This means it should contain the dot. ie: ‘.html’
This argument is optional and the default value if nothing is provided will be ‘.html’ @type template_extension: string
Convenience method that permits to quickly get a file by dotted notation.
Creates a DottedFileNameFinder and uses it to lookup the given file using dotted notation. As DottedFileNameFinder provides a lookup cache, using this method actually disables the cache as a new finder is created each time, for this reason if you have recurring lookups it’s better to actually create a dotted filename finder and reuse it.
Behaves like a string, but no instance is created until the string is actually used.
Takes a function which should be a string factory and a set of arguments to pass to the factory. Whenever the string is accessed or manipulated the factory is called to create the actual string. This is used mostly by lazy internationalization.
Decorator to return a lazy-evaluated version of the original
Applying decorator to a function it will create a LazyString with the decorated function as factory.
Decorator that suppresses warnings inside the decorated function
Defines a configurable TurboGears object with a global default instance.
GlobalConfigurable are objects which the user can create multiple instances to use in its own application or third party module, but for which TurboGears provides a default instance.
Common examples are tg.flash and the default JSON encoder for which TurboGears provides default instances of .TGFlash and .JSONEncoder classes but users can create their own.
While user created versions are configured calling the GlobalConfigurable.configure() method, global versions are configured by AppConfig which configures them when config_ready milestone is reached.
Expected to be implemented by each object to proceed with actualy configuration.
Configure method will receive all the options whose name starts with CONFIG_NAMESPACE (example json.isodates has json. namespace).
If CONFIG_OPTIONS is specified options values will be converted with coerce_config() passing CONFIG_OPTIONS as the converters dictionary.
Extracts a set of options with a common prefix and converts them.
To extract all options starting with trace_errors. from the conf dictionary and conver them:
trace_errors_config = coerce_config(conf, 'trace_errors.', {
'smtp_use_tls': asbool,
'dump_request_size': asint,
'dump_request': asbool,
'dump_local_frames': asbool,
'dump_local_frames_count': asint
})
Convert some configuration options to expected types.
To replace given options with the converted values in a dictionary you might do:
conf.update(coerce_options(conf, {
'debug': asbool,
'serve_static': asbool,
'auto_reload_templates': asbool
}))
Given a dictionary and a prefix, return a Bunch, with just items that start with prefix
The returned dictionary will have ‘prefix.’ stripped so:
get_partial_dict('prefix', {'prefix.xyz':1, 'prefix.zyx':2, 'xy':3})
would return:
{'xyz':1,'zyx':2}