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.
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.
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.
tg.decorators.
before_call
(hook_func)¶A list of callables to be run before the controller method is called.
tg.decorators.
before_render
(hook_func)¶A list of callables to be run before the template is rendered.
tg.decorators.
before_validate
(hook_func)¶A list of callables to be run before validation is performed.
tg.decorators.
cached
(key=<class 'tg.support.NoDefault'>, expire='never', type=None, query_args=None, cache_headers=('content-type', 'content-length'), invalidate_on_startup=False, cache_response=True, **b_kwargs)¶Decorator to cache the controller.
The namespace and cache key used to cache the controller are available asrequest.caching.namespace
andrequest.caching.key
. This only caches the controller, not the template, validation or the hooks associated to the controller. If you also want to cache template remember to returntg_cache
option with the same cache key from the controller.
The following parameters are accepted:
key
- Specifies the controller parameters used to generate the cache key.NoDefault - Uses function name and parameters (excluding *args) as the key (default)
None - No variable key, uses only function name as key
string - Use function name and only “key” parameter
list - Use function name and all parameters listed
expire
type
cache_headers
invalidate_on_startup
cache_response
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.
tg.decorators.
decode_params
(format='json')¶Decorator that enables parsing parameters from request body.
By default the arguments are parsed in JSON format (which is currently the only supported format).
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: |
|
---|
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
(view, template)¶Override the template to be used.
Use override_template in a controller method in order to change the template that will be used to render the response dictionary dynamically.
The view
argument is the actual controller method for which you
want to replace the template.
The template
string passed in requires that
you include the template engine name, even if you’re using the default.
So you have to pass in a template id string like:
"genshi:myproject.templates.index2"
future versions may make the genshi: optional if you want to use the default engine.
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: |
|
---|
tg.decorators.
require
(predicate, denial_handler=None, smart_denial=False)¶Decorator that checks if the specified predicate it met, if it isn’t it calls the denial_handler to prevent access to the decorated method.
The default authorization denial handler of this protector will flash
the message of the unmet predicate with warning
or error
as the
flash status if the HTTP status code is 401 or 403, respectively.
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.
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.
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: |
|
---|
The first positional parameter can either be a dictonary of validators, a FormEncode schema validator, or a callable which acts like a FormEncode validator.
tg.decorators.
with_engine
(engine_name=None, master_params=None)¶Decorator to force usage of a specific database engine in TurboGears SQLAlchemy BalancedSession.
Parameters: |
|
---|
tg.caching.
cached_property
(func)¶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()
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: |
|
---|
The first positional parameter can either be a dictonary of validators, a FormEncode schema validator, or a callable which acts like a FormEncode validator.
tg.validation.
Convert
(func, msg=<tg.util.lazystring.LazyString object>, default=None)¶Applies a conversion function as a validator.
This is meant to implement simple validation mechanism.
Any callable can be used for func
as far as it accepts an argument and
returns the converted object. In case of exceptions the validation
is considered failed and the msg
parameter is displayed as
an error.
A default
value can be provided for values that are missing
(evaluate to false) which will be used in place of the missing value.
Example:
@expose()
@validate({
'num': Converter(int, 'Must be a number')
}, error_handler=insert_number)
def post_pow2(self, num):
return str(num*num)
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.
tg.decorators.
require
(predicate, denial_handler=None, smart_denial=False)Decorator that checks if the specified predicate it met, if it isn’t it calls the denial_handler to prevent access to the decorated method.
The default authorization denial handler of this protector will flash
the message of the unmet predicate with warning
or error
as the
flash status if the HTTP status code is 401 or 403, respectively.
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.
tg.predicates.
CompoundPredicate
(*predicates, **kwargs)¶A predicate composed of other predicates.
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: |
|
---|---|
Raises: | NotAuthorizedError – If one of the predicates is not met. |
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: |
|
---|---|
Raises: | NotAuthorizedError – If none of the predicates is met. |
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')
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')
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')
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')
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')
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')
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')
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.
tg.predicates.
not_anonymous
(msg=None)¶Check that the current user has been authenticated.
Example:
# The user must have been authenticated!
p = not_anonymous()
tg.predicates.
NotAuthorizedError
¶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: |
|
---|
tg.support.paginate.
Page
(collection, page=1, items_per_page=20)¶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
pager
(format='~2~', page_param='page', partial_param='partial', show_if_single_page=False, separator=' ', onclick=None, symbol_first='<<', symbol_last='>>', symbol_previous='<', symbol_next='>', link_attr=None, curpage_attr=None, dotdot_attr=None, page_link_template='<a%s>%s</a>', page_plain_template='<span%s>%s</span>', **kwargs)¶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.
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.
Configuration Options provided:
debug
-> Enables / Disables debug mode. Can be set from .ini file
serve_static
-> Enable / Disable serving static files. Can be set from .ini file
use_dotted_templatenames
-> Use template names as packages in @expose instead of file paths. This is usually the default unless TG is started in Minimal Mode. Can be set from .ini file
registry_streaming
-> Enable streaming of responses, this is enabled by default. Can be set from .ini file
paths
-> Dictionary of directories where templates, static files and controllers are found:{ 'controllers': 'my/path/to/controlllers', 'static_files': 'my/path/to/files', 'templates': ['list/of/paths/to/templates'] )
use_toscawidgets
-> Enable ToscaWidgets1, this is deprecated.
use_toscawidgets2
-> Enable ToscaWidgets2
prefer_toscawidgets2
-> When both TW2 and TW1 are enabled prefer TW2. Can be set from .ini file
custom_tw2_config
-> Dictionary of configuration options for TW2, refer totw2.core.middleware.Config
for available options.
auth_backend
-> Authentication Backend, can beNone
,sqlalchemy
orming
.
sa_auth
-> Simple Authentication configuration dictionary. This is a Dictionary that contains the configuration options forrepoze.who
, see Authentication in TurboGears 2 applications for available options. Basic options include:
cookie_secret
-> Secret phrase used to verify auth cookies.authmetadata
-> Authentication and User Metadata Provider for TurboGearspost_login_url
-> Redirect users here after loginpost_logout_url
-> Redirect users here when they logout
package
-> Application Package, this is used to configure paths as being inside a python
app_globals
-> Application Globals class, by default build frompackage.lib.app_globals
. package. Which enables serving templates, controllers, app globals and so on from the package itself.
helpers
-> Template Helpers, by defaultpackage.lib.helpers
is used.
model
-> The models module (or object) where all the models, DBSession and init_models method areavailable. By default
package.model
is used.
renderers
-> List of enabled renderers names.
default_renderer
-> When not specified, use this renderer for templates.
auto_reload_templates
-> Automatically reload templates when modified (disable this on production for a performance gain). Can be set from .ini file
use_ming
-> Enable/Disable Ming as Models storage.
ming.url
-> Url of the MongoDB database
ming.db
-> If Database is not provided inming.url
it can be specified here.
ming.connection.*
-> Options to configure the ming connection, refer toming.datastore.create_datastore()
for available options.
use_sqlalchemy
-> Enable/Disable Ming as Models storage.
sqlalchemy.url
-> Url of the SQLAlchemy database. Refer to SQLAlchemy Master Slave Load Balancing for configuring master-slave urls.
add_auth_middleware
(app, skip_authentication)¶Configure authentication and authorization.
Parameters: |
|
---|
add_core_middleware
(app)¶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_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[‘tm.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
(conf)¶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_controller_wrapper
(wrapper, controller=None)¶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)
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.
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).
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
setup_vars
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
Flash messaging system for sending info to the user in a non-obtrusive way
tg.flash.
TGFlash
(**options)¶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()
.
configure
(cookie_name='webflash', default_status='ok', template=<string.Template object>, js_call='webflash.render()', js_template=<string.Template object>, allow_html=False)¶Flash messages can be configured through AppConfig
(app_cfg.base_config
)
using the following options:
flash.cookie_name
-> Name of the cookie used to store flash messagesflash.default_status
-> Default message status if not specified (ok
by default)flash.template
-> string.Template
instance used as the flash template when
rendered from server side, will receive $container_id
, $message
and $status
variables.flash.allow_html
-> Turns on/off escaping in flash messages, by default HTML is not allowed.flash.js_call
-> javascript code which will be run when displaying the flash
from javascript. Default is webflash.render()
, you can use webflash.payload()
to retrieve the message and show it with your favourite library.flash.js_template
-> string.Template
instance used to replace full
javascript support for flash messages. When rendering flash message for javascript usage
the following code will be used instead of providing the standard webflash
object.
If you replace js_template
you must also ensure cookie parsing and delete it for
already displayed messages. The template will receive: $container_id
,
$cookie_name
, $js_call
variables.message
¶Get only current flash message, getting the flash message will delete the cookie.
pop_payload
()¶Fetch current flash message, status and related information.
Fetching flash message deletes the associated cookie.
render
(container_id, use_js=True)¶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.
status
¶Get only current flash status, getting the flash status will delete the cookie.
tg.
render_template
(template_vars, template_engine=None, template_name=None, **kwargs)¶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.
tg.render.
MissingRendererError
(template_engine)¶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
render_func
ns_options
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
cache_type
dbm
, file
, memory
, database
,
or memcached
.cache_expire
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.
tg.renderers.base.
RendererFactory
¶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.
create
(config, app_globals)¶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={})
.
options
= {}¶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
.
with_tg_vars
= True¶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).
tg.jsonify.
JSONEncoder
(**kwargs)¶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()
.
configure
(isodates=False, custom_encoders=None, **kwargs)¶JSON encoder can be configured through AppConfig
(app_cfg.base_config
)
using the following options:
json.isodates
-> encode dates using ISO8601 formatjson.custom_encoders
-> List of tuples (type, encode_func)
to register
custom encoders for specific types.default
(obj)¶Implement this method in a subclass such that it returns
a serializable object for o
, or calls the base implementation
(to raise a TypeError
).
For example, to support arbitrary iterators, you could implement default like this:
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
# Let the base class default method raise the TypeError
return JSONEncoder.default(self, o)
register_custom_encoder
(objtype, encoder)¶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).
tg.jsonify.
encode
(obj, encoder=None, iterencode=False)¶Return a JSON string representation of a Python object.
tg.jsonify.
encode_iter
(obj, encoder=None)¶Encode object, yielding each string representation as available.
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.
tg.request_local.
Response
(body=None, status=None, headerlist=None, app_iter=None, content_type=None, conditional_response=None, charset=<object object>, **kw)¶WebOb Response subclass
content
¶The body of the response, as a bytes
. 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.
tg.configuration.hooks.
HooksNamespace
¶Manages hooks registrations and notifications
disconnect
(hook_name, func, controller=None)¶Disconnect an hook.
The registered function is removed from the hook notification list.
notify
(hook_name, args=None, kwargs=None, controller=None, context_config=None, trap_exceptions=False)¶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)
notify_with_value
(hook_name, value, controller=None, context_config=None)¶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)
register
(hook_name, func, controller=None)¶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)
tg.appwrappers.base.
ApplicationWrapper
(next_handler, config)¶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.
__call__
(controller, environ, context)¶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)
__init__
(next_handler, config)¶x.__init__(…) initializes x; see help(type(x)) for signature
injected
¶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.
next_handler
¶The next handler in the chain
tg.configuration.milestones.
_ConfigMilestoneTracker
(name)¶Tracks actions that need to be performed when a specific configuration point is reached and required options are correctly initialized
reach
()¶Marks the milestone as reached.
Runs the registered actions. Calling this method multiple times should lead to nothing.
register
(action, persist_on_reset=False)¶Registers an action to be called on milestone completion.
If milestone is already passed action is immediately called
tg.i18n.
set_lang
(languages, **kwargs)¶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.
tg.i18n.
get_lang
(all=True)¶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.
tg.i18n.
add_fallback
(lang, **kwargs)¶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.
tg.i18n.
set_request_lang
(languages, tgl=None)¶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.
tg.i18n.
ugettext
(value)¶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')
tg.i18n.
lazy_ugettext
(*args, **kwargs)¶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')
tg.i18n.
ungettext
(singular, plural, n)¶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}
tg.i18n.
lazy_ungettext
(*args, **kwargs)¶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.
tg.controllers.util.
url
(base_url='/', params=None, qualified=False)¶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.
tg.controllers.util.
lurl
(base_url=None, params=None)¶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.
tg.controllers.util.
redirect
(base_url='/', params=None, redirect_with=<class 'tg.exceptions.HTTPFound'>, **kwargs)¶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.
tg.controllers.util.
etag_cache
(key=None)¶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.
tg.controllers.util.
abort
(status_code=None, detail='', headers=None, comment=None, passthrough=False, error_handler=False)¶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)
tg.controllers.util.
auth_force_logout
()¶Forces user logout if authentication is enabled.
tg.controllers.util.
auth_force_login
(user_name)¶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.
tg.controllers.util.
validation_errors_response
(*args, **kwargs)¶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)
tg.util.bunch.
Bunch
¶A dictionary that provides attribute-style access.
tg.util.dates.
get_fixed_timezone
(offset)¶Returns a tzinfo instance with a fixed offset from UTC.
offset
should be provided in minutes or as a timedelta
.
tg.util.dates.
parse_datetime
(value)¶Parses a string and return a datetime.datetime.
This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC.
Raises ValueError
if the input isn’t well formatted.
tg.util.dates.
utctz
= <UTC>¶UTC tzinfo instance
tg.util.decorators.
no_warn
(f, *args, **kwargs)¶Decorator that suppresses warnings inside the decorated function
tg.util.files.
DottedFileLocatorError
¶tg.util.files.
DottedFileNameFinder
¶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.
get_dotted_filename
(template_name, template_extension='.html')¶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
lookup
(name, extension='.html')¶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.
tg.util.files.
safe_filename
(filename)¶Escapes a filename to ensure is valid and secure.
Filename can then safely be stored on a regular file system and passed
to os.path.join()
. The filename returned is an ASCII only string
for maximum portability:
>>> safe_filename("My cool movie.mov")
'My_cool_movie.mov'
>>> safe_filename("../../../etc/passwd")
'etc_passwd'
>>> safe_filename(u'i contain cool ümläuts.txt')
'i_contain_cool_umlauts.txt'
The function might return an empty filename. .
tg.util.html.
script_json_encode
(obj, **kwargs)¶Works exactly like tg.jsonify.encode()
but is safe
for use in <script>
tags.
<
>
&
'
This makes it safe to embed such strings in any place in HTML with the notable exception of double quoted attributes. In that case single quote your attributes or HTML escape it in addition.
tg.util.lazystring.
LazyString
(func, *args, **kwargs)¶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.
tg.util.lazystring.
lazify
(func)¶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.
tg.util.webtest.
test_context
(app, url=None, environ=None)¶Given a WebTest application, performs a with
statement using /_test_vars
.
if app
is None
a new empty application is configured which responds ‘HELLO’
to every request.
Entering the context a request for /_test_vars
is performed such to setup the
test variables, everything inside the with statement has a TurboGears context available
which is then removed by a call to /
at the end of the with
block to reset
the test variables.
url
parameter is provided to simulate the context as being for that url and
environ
parameter is provided to allow changing WSGI environ entries for the
context.
tg.util.sqlalchemy.
dictify
(obj)¶Converts a SQLAlchemy model instance to a dictionary
tg.util.sqlalchemy.
is_saobject
(obj)¶Checks if the provided object is a SQLAlchemy model instance
tg.util.ming.
dictify
(obj)¶Converts a Ming model instance to a dictionary
tg.util.ming.
is_mingobject
(obj)¶Checks if the provided object is a Ming model instance
tg.configuration.utils.
GlobalConfigurable
¶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.
configure
(**options)¶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.
tg.configuration.utils.
TGConfigError
¶tg.configuration.utils.
coerce_config
(configuration, prefix, converters)¶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
})
tg.configuration.utils.
coerce_options
(options, converters)¶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
}))
tg.configuration.utils.
get_partial_dict
(prefix, dictionary, container_type=<type 'dict'>)¶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}