Configuration Options

This section reports a reference of various configuration options available inside TurboGears app_cfg or .ini file.

For example if you want to enable isodates in your application JSON encoder you might want to add to your app_cfg.base_config the following:

base_config['json.isodates'] = True

Configuration options can usually be set both through the app_cfg.py or through your .ini file.

Authentication

class tg.configurator.components.auth.SimpleAuthenticationConfigurationComponent

Provide support for Simple Authentication.

Simple Authentication is the standard way to handle authentication and authorization in TurboGears. Where every request has an associated User object (which might be None) and each user can be part of one or more Groups each having a set of Permissions.

The simple auth is based on repoze.who and by default sets the required authenticators, identifiers and metadata providers for a form based login. The user, its groups and permissions are retrieved through the authmetadata object configured by the application.

For most cases instead of tweaking the simple authentication options you probably just want to change the behaviour of authmetadata object in your application configuration.

Provided options:

  • auth_backed: Which is the backend used to authenticate the provided credentials (username and password) against a store of credentials. Can be one of:

    • "authmetadata": Which means the authmetadata object of your application will be in charge of verifying the credentials through an authenticate method.
    • None: Which means to disable the primary authenticator (only authenticators explicitly provided in authenticators ooption will be used). Most of Turbogears will consider authentication as disabled.
    • "ming": Which means to veirfy the credntials against a MongoDB database ( deprecated ).
    • "sqlalchemy": Which means to veirfy the credntials against a SQLalchemy database ( deprecated )
  • skip_authentication: Disable authentication for tests, the user will always be authenticated through a REMOTE_USER environ key which will be considered the authenticated user id when set.

  • sa_auth.authmetadata: authmetadata instance to use as an authenticator. This is always applied unless auth_backend is None or the provided object lacks an authenticate method.

  • sa_auth.log_stream: Provide a custom logger fo authentication. by default the auth logger is used.

  • sa_auth.identifiers: The identifiers to use to recognise a logged user. By default ('default', None) leads to an authentication cookie being used to recognise logged users.

  • sa_auth.form_identifies: Whenever to add the form plugin to the identifiers. By default True. This allows the form plugin to intercept requests and identify the user credentisl from the data submitted by the login page. If this is disabled, the form will be able to act as a challenger and redirect the user to the login page, but it won’t be able to actually get the user_name/password from the submitted form and provide them to the authenticator.

  • sa_auth.cookie_secret: Secret to encode the auth_tkt cookie. This is only required when ('default', None) is listed in sa_auth.identifiers.

  • sa_auth.authenticators: List of authenticators used to authenticate user against the provided credentials. By default ('default', None) and cookie are the only enabled ones. This means that user will be authenticated against an user name and password using the configured auth_backend or will be authenticated through the presence of an authentication cookie.

  • sa_auth.cookie_name: Name of the cookie used to authenticate the user if the cookie identifer and authenticator are enabled (by default they are).

  • sa_auth.login_url: Url where the login form is displayed if sa_auth.form_plugin is enabled. By default "/login".

  • sa_auth.login_handler: Url that should handle form submitted authentication requests if sa_auth.form_plugin is enabled and it is allowed to identify. By default it’s "/login_handler".

  • sa_auth.logout_handler: Url that should handle logout requests if sa_auth.form_plugin is enabled and it is allowed to identify. By default it’s "/logout_handler"

  • sa_auth.post_login_url: Where to redirect user after a login. Only applied if sa_auth.form_plugin is enabled and allowed to identify.

  • sa_auth.post_logout_url Where to redirect user after a logout. Only applied if sa_auth.form_plugin is enabled and allowed to identify.

  • sa_auth.login_counter_name: Parameter used by form login to keep track of login attempts if sa_auth.form_plugin` is enabled. By default __logins.

  • sa_auth.form_plugin: Provide an alternative login/logout implement for form based authentication. This might make all form_plugin related options unusable.

  • sa_auth.mdproviders: Enable some metadata providers. This are used to inject additional user details into the current request. By default it’s disabled and tg.appwrappers.identity.IdentityApplicationWrapper is used instead.

  • sa_auth.authtkt.timeout: Timeout of the authtkt token.

  • sa_auth.authtkt.reissue_time: Frequency at which the authtkt token

    should be refreshed.

  • sa_auth.authtkt.secure: Make cookie HTTPS only and disable Javascript access.

  • sa_auth.authtkt.samesite: Enable a SameSite=X option on the cookie.

class tg.appwrappers.identity.IdentityApplicationWrapper(handler, config)

Provides user identity when authentication is enabled.

The repoze.who provided identity takes precedence over the identity provided by IdentityApplicationWrapper if available.

Supported options which can be provided by config are:
  • sa_auth.authmetadata: The TGAuthMetadata object that should be used to retrieve identity metadata.
  • identity.enabled: Enable the Identity Application Wrapper. By default enabled if authmetadata available.
  • identity.allow_missing_user: Whenever the identity should be discarded or not when the authmetadata is unable to find an user.

App Globals

class tg.configurator.components.app_globals.AppGlobalsConfigurationComponent

Enables the application global object.

tg.app_globals is a global object always available in TG and shared across all requests and threads of the application.

It’s meant to keep around any value or method that all other parts of the application might depend on. As it’s shared between all application threads and requests its content should be immutable or it will lead to race conditions.

By default an instance of .lib.app_globals.Globals from within your application package is used. If it’s not available an empty Bunch will be created instead.

Provided options:

  • app_globals -> Factory or Class that should be used to create application global object instead of getting it from the application package.

Caching

class tg.configurator.components.caching.CachingConfigurationComponent

Provide support for caching through Beaker.

Caching components adds support for setting up the cache manager used by all caching features of turbogears:

  • The tg.cache object.
  • Templates caching
  • function results caching by key
  • Controller actions caching.

Supported Options:

  • cache.enabled: Enabled/Disable caching, by default True.

Refer to CacheApplicationWrapper for additional options.

class tg.appwrappers.caching.CacheApplicationWrapper(handler, config)

Provides Caching Support.

The Cache Application Wrapper will make a CacheManager instance available every request under the environ['beaker.cache'] key and inside the TurboGears request context as cache.

Supported options which can be provided by config are:

Custom Error Pages

class tg.configurator.components.error_pages.ErrorPagesConfigurationComponent

Provides support for custom error pages.

This will enable the required parts to show a custom error page when a common HTTP error happens in the TurboGears application.

Refer to ErrorPageApplicationWrapper for supported options.

When simple authentication backend is set to None (auth disabled) status code 401 will always be handled by custom error pages even if not specified in errorpage.status_codes.

class tg.appwrappers.errorpage.ErrorPageApplicationWrapper(handler, config)

Given an Application it intercepts the response code and shows a custom page.

Supported options are:

  • errorpage.enabled: Whenever the custom error page is enabled or not.
  • errorpage.status_codes: List of HTTP errors that should be trapped. By default 403, 404, 500.
  • errorpage.content_types: List of Content-Types for which the custom error page should be displayed. IE: ["text/html"]. An empty list means all. An entry with value None means no content type provided. Default is ["text/html", None].
  • errorpage.handle_exceptions: Whenever exceptions should be trapped and treated as a 500 error or not. By default this is True when debug=false.
  • errorapge.path: Path of the controller should be displayed in case of errors. By default /error/document.

Debugging

class tg.configurator.components.debugger.DebuggerConfigurationComponent

Enabled Backlash interactive debugger support.

If debug is enabled, the TurboGears app will be wrapped in the BackLash debugger middleware which displays interactive debugging sessions when a traceback occurs.

Supported Options:

  • debug: Whenever to enable or not the interactive debugger.

Make sure that the interactive debugger is never enable on production, or it will be a major security issue as it will allow full remote code execution.

Dispatch

class tg.configurator.components.dispatch.DispatchConfigurationComponent

Provide support for controller wrappers and dispatching configuration.

This component allows to setup and configure dispatching options and controller wrappers.

The supported options are:

  • root_controller: A root controller instance to use instead of
    loading it from the application package.
  • disable_request_extensions: Whenever to disable detection of expected
    response type based on request path extension (like /index.html returns HTML while /index.json returns JSON).
  • dispatch_path_translator: A translation function to apply to request paths.
    Can be False to disable translation or True to apply default escaping. Refer to DispatchState for details.
  • ignore_parameters: Request parameters that should be ignored when dispatching
    requests. Refer to DispatchState for details.
  • enable_routing_args: Set routing args in dispatcher state during dispatch and
    call _setup_wsgiorg_routing_args on root controller to to allow trapping routing arguments.

Controller wrappers can be registered by using register_controller_wrapper():

configurator.get_component('dispatch').register_controller_wrapper(wrapper)
register_controller_wrapper(wrapper, controller=None)

Registers a TurboGears controller wrapper.

Controller Wrappers are much like a decorator applied to every controller. They receive 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(caller):
    def call(*args, **kw):
        try:
            print 'Before handler!'
            return caller(*args, **kw)
        finally:
            print 'After Handler!'
    return call

dispatch_component.register_controller_wrapper(controller_wrapper)

It is also possible to register wrappers for a specific controller:

dispatch_component.register_controller_wrapper(controller_wrapper, controller=RootController.index)

Error Reporting

class tg.configurator.components.error_reporting.ErrorReportingConfigurationComponent

Provides Error reporting through Backlash on TurboGears.

This is enabled/disabled through the debug configuration option. Currently EMail and Sentry backlash reporters can be enabled.

All the options available for error reporting are configured as trace_errors.* options in your app_cfg or .ini files.

The available options for EMail reporter are:

  • trace_errors.enable -> Enable or disable error reporting, by default is enabled if backlash is available and debug=false
  • trace_errors.smtp_server -> SMTP Server to connect to for sending emails
  • trace_errors.smtp_port -> SMTP port to connect to
  • trace_errors.from_address -> Address sending the error emails
  • trace_errors.error_email -> Address the error emails should be sent to.
  • trace_errors.smtp_username -> Username to authenticate on SMTP server.
  • trace_errors.smtp_password -> Password to authenticate on SMTP server.
  • trace_errors.smtp_use_tls -> Whenever to enable or not TLS for SMTP.
  • trace_errors.error_subject_prefix -> Prefix to append to error emails, by default WebApp Error: is prepended.
  • trace_errors.dump_request -> Whenever to attach a request dump to the email so that all request data is provided.
  • trace_errors.dump_request_size -> Do not dump request if it’s bigger than this value, useful for uploaded files. By default 50K.
  • trace_errors.dump_local_frames -> Enable dumping local variables in case of crashes.
  • trace_errors.dump_local_frames_count -> Dump up to X frames when dumping local variables. The default is 2
  • trace_errors.reporters -> Add custom reporters to error reporting middleware.

Available options for Sentry reporter are:

  • trace_errors.sentry_dsn -> Sentry instance where to send the errors.

Helpers

class tg.configurator.components.helpers.HelpersConfigurationComponent

Add support for helpers in templates.

Helpers are a bunch of help functions, usually involved in generating small HTML snippets or formatting data that are exposed in templates under the h object.

By default the helpers will be loaded from your application package as package.lib.helpers which is expected to be a module containing all helpers functions.

Supported options:

  • helpers: Set a different object as the template helpers.

Internationalization

class tg.configurator.components.i18n.I18NConfigurationComponent

Enable support for internationalization.

Supported Options:

  • i18n.lang: Default web app language if none was requested or
    detected from browser. This will always be listed as fallback language.
  • i18n.enabled: Enable support for translations.
    Disabling i18n will speedup requests and all pages will be served as they were in i18n.lang value.
  • i18n.native: Native languages templates are written into.
    No translation will occurr for those language. Provide space separated or as a list.
  • localedir: Where to find translation catalogs.
    By default it’s project root/i18n

Refer to I18NApplicationWrapper for additional options in supporting i18n.

class tg.appwrappers.i18n.I18NApplicationWrapper(handler, config)

Provides Language detection from request and session.

The session language(s) take priority over the request languages.

Supported options which can be provided by config are:
  • i18n.enabled: Whenever language detection is enabled or not.
  • i18n.lang: Fallback language for the application, works both when language detection is enabled or disabled. If this is set and language detection is dislabled, the application will consider that all gettext wrapped strings must be translated to this language.
  • i18n.lang_session_key: Session key from which to read the saved language (tg_lang by default).
  • i18n.no_session_touch: Avoid causing a session save when reading it to retrieve the favourite user language. This is False by default, setting it to False causes TurboGears to save and update the session for each request.

MimeTypes

class tg.configurator.components.mimetypes.MimeTypesConfigurationComponent

Configure known MimeTypes.

Mimetypes are used by turbogears to detect expected content types based on file extensions. For example it’s used by DispatchConfigurationComponent request extensions to serve the right content based on URL path extension.

Options:

  • mimetype_lookup: Additional mapping from extensions to
    mimetypes that should be configured.

Ming MongoDB Support

class tg.configurator.components.ming.MingConfigurationComponent

Support MongoDB through the Ming Object Document Mapper.

Configures the ming connection to MongoDB, the automatic session cleanup at the end of each request and support for the UnitOfWork flushing/discard based on request success or failures.

The configured Ming session is made available as tg.config['MingSession'].

Options:

  • ming.enabled: Enable Ming in your application
  • ming.url: MongoDB url to connect to.
  • ming.db: Database to use. Can also be specified in ming.url.
  • ming.autoflush: Automatically flush the unit of work as the end
    of each request, unless there was a failure.
  • ming.connection.*: Options provided to the ming engine to configure
    the datastore and the MongoClient. Refer to MongoClient for available options.

See MingApplicationWrapper for additional configuration options.

class tg.appwrappers.mingflush.MingApplicationWrapper(handler, config)

Automatically flushes the Ming ODMSession.

In case an exception raised during excution it won’t flush the session and it will instead close it throwing away any change.

Supported options which can be provided by config are:

  • ming.autoflush: Whenever to flush session at end of request if no exceptions happened.

Paths

class tg.configurator.components.paths.PathsConfigurationComponent

Configure application paths.

States where the application is contained, where to load controllers from, templates from, static files and which is the application Python package.

Options:

  • package: The python package containing the web application.

  • paths: A Dictionary of directories where templates, static files

    and controllers can be found:

    {
        'controllers': 'my/path/to/controlllers',
        'static_files': 'my/path/to/files',
        'templates': ['list/of/paths/to/templates']
    )
    
  • static_files: An alias to paths['static_files'] for convenience.

Request Local Registry

class tg.configurator.components.registry.RegistryConfigurationComponent

Configure the request local context registry.

This configures support for setting and restoring a clean turbogears context on each request. This makes so that tg.request, tg.response and so on always refer to the data for current request.

Options:

  • registry_streaming: Enable streaming responses, thus restoring
    the registry at the end of the stream instead of as soon as the controller action returned. This is enabled by default.
  • debug: Ensures that the registry is not discarded in case of an
    exception. So that after the exception is possible to inspect the state of the request that caused the exception.

Rendering Engines

class tg.configurator.components.rendering.TemplateRenderingConfigurationComponent

Provides support for rendering engines.

The available options are:

  • use_dotted_templatenames -> (True/False) Use template names as packages in @expose instead of file paths. This is usually the default unless TG is started in Minimal Mode.
  • auto_reload_templates -> (True/False) Automatically reload template files if they change. Should usually be disabled on production for performance reasons.
  • tg.strict_tmpl_context -> (True/False) Should tg.tmpl_context be strict and complain about missing value or should it always just return empty values for missing ones?
  • renderers -> (list(str)) List of template engines that should be enabled.
  • default_renderer -> (str) The default template engine to use when not explicitly specified by @expose decorations.

Refer to each template engine renderer for specific configuration options.

register_engine(factory)

Registers a rendering engine factory.

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

Genshi

class tg.renderers.genshi.GenshiRenderer(loader, config)

Configuration Options available as templating.genshi.*:

  • templating.genshi.name_constant_patch -> Enable/Disable patch for Python3.4 compatibility.
  • templating.genshi.max_cache_size -> Maximum number of templates to keep cached, by default 30.
  • templating.genshi.method -> Genshi rendering method (html or xhtml).

Supported render_params:

  • Caching options supported by cached_template()
  • doctype -> To override the global doctype
  • method -> To override the global rendering method

Kajiki

class tg.renderers.kajiki.KajikiRenderer(loader)

Configuration Options available as templating.kajiki.*:

  • templating.kajiki.force_mode -> Kajiki Rendering Mode (html, html5, xml). Default html5.
  • templating.kajiki.template_extension -> Kajiki Templates extension, default .xhtml
  • templating.kajiki.xml_autoblocks -> List of tags that should be automatically converted to blocks.
  • templating.kajiki.cdata_scripts -> Automatically wrap scripts in CDATA.
  • templating.kajiki.html_optional_tags -> Allow unclosed html, head and body tags.
  • templating.kajiki.strip_text -> Strip leading/trailing spaces from text nodes.

Supported render_params:

  • Caching options supported by cached_template()
  • All arguments supported by kajiki.xml_template.XMLTemplate()

Jinja2

class tg.renderers.jinja.JinjaRenderer(jinja2_env)

Currently Jinja2 support uses a bunch of options from tg.config and doesn’t provide its own namespace.

Mako

class tg.renderers.mako.MakoRenderer(use_dotted_templatenames, template_extension, dotted_loader, normal_loader)

Configuration Options available as templating.mako.*:

  • templating.mako.template_extension -> Mako Templates extension, default .mak
  • templating.mako.compiled_templates_dir -> Where to store mako precompiled templates. By default templates are only stored in memory and not on disk.

JSON

class tg.renderers.json.JSONRenderer

JSON rendering can be configured using options supported by JSONEncoder.configure()

Supported render_params:

  • All supported by JSONEncoder.configure()
  • key -> Render a single key of the dictionary returned by controller instead of rendering the dictionary itself.
  • callback_param -> Name of the callback to call in rendered JS for jsonp

Seekable Request

class tg.configurator.components.seekable_request.SeekableRequestConfigurationComponent

Support for making the request body seekable.

This allows to make the request body seekable, so that it can be read multiple times and it’s possible to go back and forth in request submitted data. Note that this has a cost in terms of consumed memory.

Options:

  • make_body_seekable: Enable seekable request body.
    By default this is disabled.

Sessions

class tg.configurator.components.session.SessionConfigurationComponent

Provide support for sessions through Beaker.

Session components adds support for setting up the session manager used by tg.sessions.

Options:

  • session.enabled: Add support for sessions in the application.
    By default sesions are enabled.
  • session.data_dir: Where to store session files, by default
    the $cache_dir/sessions is used.

Refer to SessionApplicationWrapper for all the supported options.

class tg.appwrappers.session.SessionApplicationWrapper(handler, config)

Provides the Session Support

The Session Application Wrapper will make a lazy session instance available every request under the environ['beaker.session'] key and inside TurboGears context as session.

Supported options which can be provided by config are:

Slow Requests Reporting

class tg.configurator.components.slow_requests.SlowRequestsConfigurationComponent

Provides slow requests reporting for TurboGears through BackLash.

This is enabled through the trace_slowreqs.enable option and is only enabled when debug=false.

All the options available for error reporting are configured as trace_slowreqs.* options in your app_cfg or .ini files:

  • trace_slowreqs.enable -> Enable/Disable slow requests reporting, by default it’s disabled.
  • trace_slowreqs.interval -> Report requests slower than this value (default: 25s)
  • trace_slowreqs.exclude -> List of urls that should be excluded

Slow requests are reported using EMail or Sentry, the same options available in ErrorReportingConfigurationComponent apply with trace_slowreqs. instead of trace_errors..

SQLAlchemy

class tg.configurator.components.sqlalchemy.SQLAlchemyConfigurationComponent

Support Relational Databases through SQLAlchemy.

Configures SQLAlchemy connection to the database, the automatic session cleanup at the end of each request and support for master/slave databases.

Support for transaction commit/rollback on request state is provided by TransactionManagerConfigurationComponent.

The configured SQLAlchemy engine is made available as tg.app_globals.sa_engine. While the configured SQLAlchemy session is made available as tg.config['SQLASession'].

Options:

  • use_sqlalchemy: Enable SQLAlchemy in your application.
  • model: Configure where models could be found, by default
    they are expected in model Python module within your application package.
  • sqlalchemy.*: Options provided to SQLAlchemy connection
    as expected by engine_from_config().
  • sqlalchemy.master.* Enable Master/Slave replication support
    and configure the master connection.
  • sqlalchemy.slaves.slavename.*: Configure slavename slave in
    Master/Slave support and setup its connection. Multiple entries with different slavename values can be provided.

Static Files

class tg.configurator.components.statics.StaticsConfigurationComponent

Provide support for serving Static Files.

In production, use Apache or another web server to serve static files.

  • serve_static: Enable / Disable serving static files. Can be set from .ini file
  • paths.static_files: Directory where the static files should be served from.
    Refer to PathsConfigurationComponent for configuration.

ToscaWidgets2

class tg.configurator.components.toscawidgets2.ToscaWidgets2ConfigurationComponent

Support for ToscaWidgets2 based Widgets, Forms and Resources.

Options:

  • tw2.enabled: Enable ToscaWidgets2 support.
    For backward compatibility also prefer_toscawidgets2 and use_toscawidgets2 options are supported.
  • custom_tw2_config: Additional TW2 Middleware options to provide.
    This should be a dictionary of options.

Some options from other components influence TW2 behaviour too:

  • auto_reload_templates: Enable autoreloading of Widgets templates.
  • debug: Enable debug mode for TW2 (also injects debug resources).
  • default_renderer: Rendering Engine used to render Widgets templates.
  • renderers: Rendering engines that can be used to render Widgets templates.

Transaction Manager

class tg.configurator.components.transactions.TransactionManagerConfigurationComponent

Support for transaction manager.

The transaction manager will automatically handle transactions bound to it according to the request state.

Whenever a request succeeds the transaction manger will commit all transactions, while in case of a failure it will rollback the transactions.

Refer to TransactionApplicationWrapper for list of supported options.

class tg.appwrappers.transaction_manager.TransactionApplicationWrapper(handler, config)

Wraps the whole application in zope.transaction transaction manager and rollbacks transaction in case of crashes.

Supported options which can be provided by config are:

  • tm.enabled: Whenever the transaction manager is enabled or not.
  • tm.attempts: Number of times the transaction should be retried if it fails (no retry by default)
  • tm.commit_veto: A function that will be called for every transaction to check if it should abort transaction or let it go. Function signature should be: function(environ, status_code, headers) -> bool.

JSON Encoding

JSONEncoder.configure(isodates=False, custom_encoders=None, allow_lists=False, **kwargs)

JSON encoder can be configured through ApplicationConfigurator (app_cfg.base_config) using the following options:

  • json.isodates -> encode dates using ISO8601 format
  • json.custom_encoders -> List of tuples (type, encode_func) to register custom encoders for specific types.
  • json.allow_lists -> Allows lists to be encoded, this is usually disabled for security reasons due to JSON hijacking. See http://stackoverflow.com/questions/16289894 for additional details.

Flash Messages

TGFlash.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 ApplicationConfigurator using the following options:

  • flash.cookie_name -> Name of the cookie used to store flash messages
  • flash.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.