Table Of Contents

TurboGears Configuration

TurboGears is designed to get running with a minimum of trouble and very little external configuration. For many applications, the only thing that will need to change from the basic tg quickstart configuration is the location of the database.

Configuration Layout

A quickstarted application comes with five configuration files:

  • dev.cfg
  • sample-prod.cfg
  • test.cfg
  • <package_name>/config/app.cfg
  • <package_name>/config/log.cfg

The dev.cfg file is the deployment configuration used while you are developing your application.

The sample-prod.cfg contains appropriate settings for a “real” deployment. We recommend that you rename this file to prod.cfg and tweak the settings before deploying an application.

The test.cfg file is used when you run the test suite of your project. See Testing Your Application for more information about test suites.

Of these three files, only one will be used at a time, depending on how you start the server, that’s why they are located in the toplevel-directory (that also holds the setup.py file) and not in your application’s package.

The app.cfg holds options that are always the same regardless of the environment your program runs in. While dev.cfg and prod.cfg are mostly concerned with database config strings, ports, and auto-reloading, app.cfg contains encoding, output, and identity settings.

The log.cfg holds logging configuration that is independent of of the environment your program runs in, e.g. different log handlers and log formatting profiles. Environment-specific logging configuration should go into dev.cfg or prod.cfg.

Running the server using start-*appname*.py will use the dev.cfg config file by default, and if that does not exist, a file prod.cfg in the current directory. You can change this by passing the path to another config file as a command line parameter:

python start-*appname*.py /some/path/prod.cfg

If you want to package your application as an egg to be installed on the production server, then the content of the toplevel-directory will not be part of the package, i.e. neither dev.cfg nor prod.cfg will be available after installation of that egg. So you will need to take care of copying prod.cfg somewhere to the production server. Another solution is to package a default config file along with the application. When no dev.cfg` or ``prod.cfg will be found, then TurboGears looks for configs/default.cfg in the application’s package. Note that this file will be not created by default, you need to copy it from dev.cfg or sample-prod.cfg, and you also need to enable packaging of that file in setup.py by removing the comment in front of the following line:

``data_files = [('config', ['default.cfg'])],``

Configuration Syntax and Sections

The syntax is an extended version of the standard INI/ConfigParser format. The main extensions are an increased importance of sections and the addition og some pre-defined variables for string interpolation, to reduce the number of hard coded file paths. If want to know more about this format, you can refer to the ConfigObj documentation.

The [global] section of the config file is intended for settings that apply server-wide and at start-up time. These settings are also copied to CherryPy’s site configuration.

You can also have path-based config sections used for tools and other settings that apply only to one part of your site. These settings are also copied to CherryPy’s application configuration. The example below will set tg.allow_json only for the /admin part of the site.

[/admin]
tg.allow_json = True

Like with the ConfigParser format, you can also use string interpolation, to refer to values of one configuration setting in the value of another setting within the config file. See the ConfigObj documentation on string interpolation for more information on this.

There are two pre-defined variables for string interpolation. The first is current_dir_uri, which is the absolute file system path to the current working directory. This is primarily used in the default sqlite’s dburi but can be used elsewhere:

sqlobject.dburi = "sqlite://%(current_dir_uri)s/devdata.sqlite"

The second is top_level_dir, the absolute file system path to your application’s package directory (the location of controllers.py in a quickstarted project). It is used primarily in app.cfg to get a working filepath to the static content when the project is moved to a different server.

In addition to the global and application settings, there is also the logging configuration which is done in the [logging] section.

Retrieving Config Variables From Your Application

Retrieving values is done using the turbogears.config.get('key'[,default]) function:

>>> from turbogears import config
>>> config.get('sqlobject.dburi','sqlite:///:memory:') #second value is optional default value
'sqlite:///:memory:'

Accessing Config Variables Within the Template

In your templates the turbogears.config.get function is available as tg-config, so you can do something like this:

${tg.config('myproject.mysetting', 'default')}

Alternatively, you can pass the config object as part of your template dictionary:

from turbogears import config

    #...
    def ...(self, ...)
        return dict(config=config)

Or, if you prefer, you can import config in your Genshi or Kid template:

<?python from turbogears import config ?>

In both cases, the syntax for retrieving configuration settings is the same as in your controller code.

CherryPy Configuration Reference

TurboGears uses its own config module, but copies the global settings and the application settings to CherryPy’s configuration system. This document doesn’t cover the CherryPy settings and conventions in detail, but here is a short list of the most common options.

engine.autoreload.onTrue
The Cherrypy’s autoreload functionality takes care of restarting the server if any of the modules that have been imported changes. This is very handy for development but could cause huge resources usage in production since it requires checking quite a few files and is not compatible with zipped eggs.
engine.autoreload_match.*
This is a regular expression pattern (default .*) that you can change to filter which files are monitored when the autoreload mechanism is on.
environment"development"
This is the only CherryPy setting without a namespace prefix. Can be "development" or "production". The "development" option enables a variety of error reporting tools while "production" turns them all off in the interest of performance.
log.error_file `` -- ``None
Path to the error log file. Use the TurboGears logging configuration instead.
log.screenFalse
Sends the server log to screen. Keep it off and use the TurboGears logging configuration instead.
server.socket_file - ""
For when you’re proxying CherryPy locally and want to listen on a named pipe. If you use this, you must also set server.socket_port to None, leaving server.socket_port unset will not work.
server.socket_host""

This setting binds CherryPy to a particular ip address. This isn’t usually necessary, as CherryPy will listen for any incoming connections by default.

The exception is when your application is running on a system which has both a IPv4 and IPv6 network stack. By default the CherryPy server will only listen on the IPv6 interfaces. To listen on all IPv4 interfaces, you should set server.socket_host = '0.0.0.0'. If this does not work, a workaround would be to set server.socket_host to a specific interface address and run your application behind a reverse proxy that listens on all interfaces and forwards requests to your application.

server.socket_port8080
CherryPy listens on this port for incoming HTTP connections.
server.webpath

Specifies the root of the site for use when generating URLs. Use this if your whole TurboGears instance is not at the root of your webserver. So if your application was located at /turbogears/my_app rather than /my_app, you would set server.webpath = "/turbogears/".

Note: Despite the name, this option is a TurboGears extension to CherryPy and is used with the turbogears.url() function.

For a more complete treatment of CherryPy options, we defer you to the CherryPy site, specifically section 1.3 an overview of the configuration system and section 1.3.2 reference of some configuration options.

TurboGears dev.cfg and prod.cfg Configuration Reference

catwalk.session_dir<yourpkg>/catwalk-session

This sets the CatWalk session directory, i.e. where CatWalk stores its state data. You may need to set this to something different from the default, e.g. if you deploy your application with mod_wsgi and you want to use CatWalk mounted in your own controllers. Example:

catwalk.session_dir = "/var/cache/myapp/catwalk-session"

The path may be absolute or relative to the current working directory of your server. The directory will be created if it does not exist, so make sure it either exists already or the server has write access in the parent directory. New in TurboGears 1.5

sqlalchemy.dburi

The SQLAlchemy URI that identifies the database to use for this application when using the SQLAlchemy database abstraction (the default).

The general form of the URI is databasetype://username:password@hostname:port/databasename.

If you put :doc:`/notrans` in front of the URI, the automatic database transactions will be turned off.

Note that for sqlite, the format is more like that of a file:// URL: sqlite:///absolute_path_to_file (since absolute_path_to_file will start with a forward slash as well on Unix-like systems, you will end up with four slashes after sqlite:!).

Also note that on Windows systems, sqlite used | instead of : As of Turbogears 0.9a6, it is smart enough to undestand both ways. For example: sqlite:///d|databases/foo.db and sqlite:///d:databases/foo.db are both valid points to D:\databases\foo.db.

Note to MySQL users: If you use a different socket than /tmp/mysql.sock, you may specify which socket to use by adding a unix_socket argument to the dburi. i.e., mysql://user:pass@host:port/db?unix_socket=/path/to/mysql.sock.

sqlobject.dburi
The SQLObject URI that identifies the database to use for this application when using teh SQLObject database abstraction.
tg.bonjour
This setting enables/disables Zeroconf (aka Bonjour) support for the server. You can set this to the name under which your application should appear in the Zeroconf service list or to a boolean false value (empty string, None, False, 0) to disable registering the TurboGears server with zeroconf on startup. If it is not set, the server will be registered with Zeroconf only if server.environment is set to "development" and the name will be your application’s top-level package name.
tg.fancy_exceptionFalse
When True, exceptions will present an extended traceback with both locals() and an eval() input provided for each level of the stack. This is disabled by default because it allows the person viewing the trace to remotely evaluate arbitrary code on your server. Enable with due care.
tg.strict_parametersFalse
When True, TurboGears raises an error when a controller is passed an unexpected parameter. This is useful because it helps you catch typos in your code. In a production environment, mistyping a url or passing a bad parameter in a query string returns a 404 or 200, respectively.
tg.url_domain

Sets the hostname part of the URL under which your application is reachable from the network. This may be different from server.socket_name, e.g. if the TurboGears server is running behind a reverse proxy. This may include the port number (again, this is the port on which your app is available from the network and may be different from server.socket_port, separated by a colon. This setting is used by the turbogears.absolute_url function to build an absolute URL, including URL scheme (see below) and hostname.

Examples:

tg.url_domain = 'www.server.com'
# absolute_url('/') --> 'http://www.server.com/'
tg.url_domain = 'www.server.com:1234'
# absolute_url('/') --> 'http://www.server.com:1234/'
tg.url_scheme'http'

Sets the scheme part of the URL under which your application is reachable from the network. This may be necessary e.g. if the TurboGears server is running behind a reverse proxy and the proxy talks HTTP to the TurboGears server but HTTPS to the web client. This setting is used by the turbogears.absolute_url function to build an absolute URL, including URL scheme and hostname (see above).

Example:

tg.url_domain = 'www.server.com'
tg.url_scheme = 'https'
# absolute_url('/') --> 'https://www.server.com/'

Turbogears app.cfg Configuration Reference

safempfilter.onFalse

If you set this to True, the SafeMultiPartFilter request filter will be enabled, which handles request from buggy clients, which do not transfer properly formated multipart MIME messages, e.g. the Adobe Flash FileReference class. You would usually enable this only for the URLs that actually handle requests from these clients. New in 1.5

Example:

[/upload]
safempfilter.on True
tg.allow_jsonFalse
When this is set to False, calling a function with ?tg_format=json will not work by it’s own. You need to set allow_json to True in the expose() decorator or set the default_format='json'.
tg.content_type"text/html"
This is the IETF mime-type of the template output. The most common reason to change this is to add an encoding, e.g. tg.content_type = "text/html; encoding=utf-8".
tg.defaultview"genshi"
Determines which template engine to use by default. If this is not set, Kid will be used to render the templates you specify in your controller. The template engine is identified by the file extension used.
tg.ignore_parameters[]
List of names of parameters which shall not be passed to the controllers when tg.strict_parameters is set (besides tg_random, tg_format which are never passed anyway). For instance, since the ext.js JavaScript library uses the parameter name _dc (“don’t care”) to avoid caching problems, similar to how tg_random is used, you could set this to ['_dc'].
tg.include_widgets[]

This option automatically includes the listed widgets in all pages on the site. This is primarily useful for javascript libraries that have been packaged as widgets, such as the tg.mochikit.

Note: This option has replaced the tg.mochikit_all option from older TurboGears releases. To achieve the same effect, you’ll want to set tg.include_widgets = ['turbogears.mochikit'].

tg.mochikit_suppressFalse
Setting this to True will prevent the inclusion of the MochiKit version 1.3.1, that comes shipped with TurboGears, in the (X)HTML template output. This allows to include your own custom mochikit versions.
tg.schedulerFalse
The TurboGears Scheduler thread/process will be started at server startup if this is set to True.
tg.sitetemplate
TurboGears applications that are intended to be reused should make sure that every page template ultimately extends sitetemplate. This config variable lets you set which template is used as the sitetemplate. The value should be of the form *packagename*.templates.templatename, including the quotes.

Genshi Template Engine

genshi.default_encoding"utf-8"
The default output encoding to use when serializing a template. By default, Genshi uses UTF-8. If you need to, you can choose a different charset by specifying this option, although that rarely makes sense.
genshi.default_format"html"
Determines the default serialization method Genshi should use. Valid options are: “xml”, “xhtml”, “html” and “text”. By default, TurboGears will tell Genshi to produce HTML files (option value "html", which is optimum for most web applications. If your application needs to output XHTML or XML, you can set that here. You can read more about the available Genshi output formats in the Genshi documentation.
genshi.default_doctype{"html": "html-strict", "xhtml": "xhtml-strict", "xml": None}
The default DOCTYPE declaration to use in generated markup. Valid values are: “html-strict” (or just “html”), “html-transitional” “xhtml-strict” (or just “xhtml”), “xhtml-transitional” and “html5”. You can also set this to None to not do any prepending/replacing of a DOCTYPE, but rather pass through those defined in the templates (if any). If this option is set, however, any DOCTYPE declarations in the templates are replaced by the specified document type. Note that with (X)HTML, the presence and choice of the DOCTYPE can have a more or less dramatic impact on how modern browsers render pages that use CSS style sheets. In particular, browsers may switch to quirks rendering mode for certain document types, or when the DOCTYPE declaration is missing completely. You can also set this to a dictionary mapping format names (see above) to one of the valid values listed above. The default value makes Genshi use the strict variant for HTML and XHTML and no doctype declaration for XML format.
genshi.lookup_errors"lenient"
The error handling style that Genshi will use in template expressions. Can be either “lenient” (the default) or “strict”.
genshi.max_cache_size"25"
The maximum number of templates that the template loader will cache in memory. The default value is 25. You may want to choose a higher value if your web site uses a larger number of templates, and you have enough memory to spare.
genshi.search_path""
A colon-separated list of file-system path names that the template loader should use to search for templates.
genshi.allow_exec"yes"
Whether the Python code blocks should be permitted in templates. Specify “yes” to allow code blocks (which is the default), or “no” otherwise. Please note that disallowing code blocks in templates does not turn Genshi into a sandboxable template engine; there are sufficient ways to do harm even using plain expressions.
genshi.auto_reload"yes"
Whether the template loader should check the last modification time of template files, and automatically reload them if they have been changed. Specify “yes” to enable this reloading (which is the default), or “no” to turn it off. You probably want to disable reloading in a production environment to improve performance of both templating loading and the processing of includes. But remember that you’ll then have to manually restart the server process anytime the templates are updated.
genshi.new_text_syntax"no"
Whether the new syntax for text templates should be used. Specify “yes” to enable the new syntax, or “no” to use the old syntax. In the current version of Genshi, the default is to use the old syntax for backwards-compatibility, but that will change in a future release.

Kid Template Engine

kid.assume_encoding"utf-8"
The input encoding used for reading templates. If your templates are saved with another encoding, e.g. ISO-8869-13, set this to the encoding name.
kid.encoding"utf-8"
Sets the output encoding for kid templates.
kid.i18n.run_template_filternot set
Enables the translation filter for kid templates. This defaults to True` if i18n.run_template_filter is enabled, but you can still turn off the translation filter for kid templates only, if you add this to your confifuration file and set it to False.
kid.i18n_filter– None
If i18n.run_template_filter and kid.i18n.run_template_filter are enabled, this is set to the turbogears.i18n.kidutils.i18n_filter function, but you can override this with your own template translation filter function if necessary.
kid.outputformat"html"
Sets the default output format used when rendering Kid templates. You can read more about the available Kid output methods in the Kid documentation.
kid.precompiledFalse
Always use precompiled templates, if they are present, even if the corresponding *.kid files are newer. You might want to enable this for production systems for a slight speed advantage.
kid.sitetemplate"turbogears.view.templates.sitetemplate"
See the tg.sitetemplate setting.

JSON Output

json.assume_encodingutf-8
All input strings are decoded to unicode using this encoding prior to being transformed into JSON notation.
json.check_circularTrue
If this is True then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError).
json.descent_basesTrue

Whether to check all base classes for their attributes when converting an an SQLObject model object to JSON.

For backward-compatibility turbojson.descent_bases is also recognized as a default for this setting, but using turbojson.descent_bases is deprecated.

json.encoding"utf-8"
Sets the encoding for JSON output.
json.ensure_asciiFalse
If this is True, the output is guaranteed to be str objects with all incoming unicode characters escaped. If it is false, the output will be a encoded according to the json.encoding setting.
json.sort_keysFalse
If this is True the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on consistently.

All other options prefixed with json. are passed as keyword arguments to the json.JSONEncoder constructor (simplejson is used instead of json for older Python versions). See the json documentation for all supported options.

Internationalization

i18n.default_locale"en"
The default locale to use when it can not be determined from the request or the session.
i18n.domain"messages"
The gettext domain to use for your application’s messages. It defaults to "messages" but you could set this to your project name if you want, which might be sensible, if your package can be incorporated into other applications.
i18n.get_localenot set
A custom function to determine the locale to use, which overrides the default locale function turbogears.i18n.utils._get_locale. If used, should be set to a callable which takes no arguments and returns a locale string, e.g. "de" or "en_US".
i18n.gettext"tg_gettext"

The translation function to use for message translation. Possible values are "tg_gettext", "so_gettext" and "sa_gettext". If this is not set, "tg_gettext" will be used, which refers to the turbogears.i18n.tg_gettext.tg_gettext function.

so_gettext and sa_gettext are alternative translation functions, which use specific storage backends, namely a database and the SQLObject or the SQLAlchemy driver. They are defined in turbogears.i18n.sogettext and turbogears.i18n.sagettext respectively.

i18n.locale_dir"locales"
The path of the directory where your gettext message catatalogs are stored. Defaults to the locales directory below your project directory.
i18n.run_template_filter - False
Enables the translation filter for kid and Genshi templates. See the i18n documentation for more information.
i18n.session_key"locale"
The name of the key in the session dict which the default get_locale function uses to look up the locale name in the session.

Visit and Identity Configuration Reference

Answering “yes” to the identity prompt during tg-admin quickstart will fill in your model with a number of tables and will add the following options to your app.cfg:

Visit

visit.cookie.domainNone

Domain name to specify when setting the cookie (must begin with a . (dot) according to RFC 2109). This is useful when your computer is at spam.eggs.foo.com and you want to set a cookie for your whole foo.com domain for use in other applications.

The default (None) should work for most cases and will default to the machine to which the request was made. Note: localhost is NEVER a valid value and will NOT work.

visit.cookie.name"tg-visit"
The name of the cookie with the visit key to transmit to the visitor’s browser.
visit.cookie.path"/"
Specific path for the cookie, the default puts your cookie in scope for the entire site.
visit.cookie.permanentFalse
Set to true if the visit cookie shall be a permanent cookie with a max-age attribute calculated from visit.timeout. Otherwise, max-age will not be set, resulting in a session cookie that will be discarded when the browser is closed.
visit.form.nametg_visit
The name of the request parameter from which the visit key may be retrieved when visit.source includes 'form'). The name MUST NOT contain dashes or dots or it will break the request parameters decoding by the NestedVariablesFilter. New in 1.0.6.
visit.manager"sqlobject"
The name of the VisitManager plugin to use for visitor tracking.
visit.onTrue
Enables visit tracking. This means that each visit to your application will be assigned a unique visit ID tracked via a cookie sent to the visitor’s browser.
visit.soprovider.model"*appname*.model.Visit"
Database class to use for visit tracking
visit.sourcecookie

Where to look for the key of an existing visit in the request.

This should be a comma-separated list of the possible values: 'cookie', 'form'. The given methods will be tried one-after-another in the given order until a valid visit key is found or the list is exhausted. By default only use the visit key found in a session cookie. New in 1.0.6.

visit.timeout20
Number of minutes a visit may be idle before it expires.
visit.interval30
Interval in seconds for updating the visit entries in the database. This is done by the visit manager in a separate thread.

Identity

identity.failure_url"/login"
URL to which CherryPy will internally redirect when an access control check fails. If Identity management is turned on, a value for this option must be specified. The value for this setting normally is a string with a URL but it can also be set to a callable which should accept one positional argument (a list of identity errors) and return the URL to redirect to as a string. See the identity recipes page for more information on using this feature.
identity.force_external_redirectFalse
If this is set to True, the identity framework will do an external redirect, when an IdentityFailure exception occurs, instead of an internal one, i.e. it will redirect the browser to the URL given by identity.failure_url. This is useful if the failure URL is set to an https:// URL (for example to handle logins over an HTTPS connection, but keep the rest of the site on plain HTTP), since an internal redirect would not work in this case.
identity.form.user_name"user_name"
See below.
identity.form.password"password"
See below.
identity.form.submit"login"
The names of the fields on the login form containing the visitor’s user name and password (as recorded in the applications’ data model object set by the identity.*provider.model.user setting explained below under Provider). In addition, the name of the submit button is specified simply so its value may be stripped out from the request data prior to passing it to the target controller method.
identity.onTrue
Enables usage of the turbogears.identity module.
identity.source"form,http_auth,visit"

Comma-separated list of sources the identity should provider consider when determining the identity associated with a request. The given methods will be tried one-after-another in the given order until a valid identity is found or the list is exhausted.

Available options:

  • form - Inspect the form variables passed in the request data to pull out identity information. The request data must have fields for user_name, password, and a login submit button.
  • http_auth - Tries to get the identity information from the HTTP Authorization header. Only Basic Auth is handled at the moment.
  • visit - Loads the identity from the visit records.
identity.custom_encryptionNone

When identity.*provider.encryption_algorithm (see below under Provider) is set to "custom" you can provide a custom password encryption function through this setting. The value should be the full name of the callable (including the module (and possibly class) name) in dotted-path notation. The callable should accept the password to be encrypted as a string (utf-8 encoded) and return a unicode string with the encrypted password.

Example:

identity.custom_encryption = 'mypkg.utils.encrypt_password'

Provider

These options are only applicable when using one of the default identity provider plugins. TurboGears supplies both a SQLObject and a SQLAlchemy identity provider, they are named soprovider and saprovider respectively and take the same options.

identity.*provider.encryption_algorithmNone

The password encryption algorithm used when comparing passwords against what’s stored in the database. Valid values are md5 or sha1 or custom.

If you do not specify an encryption algorithm, passwords are expected to be clear text. If the value is custom you must also set the the identity.custom.encryption setting (see above under Identity) to the name of an appropriate callable in dotted-path notation.

If this is set to a valid encryption algorithm the TurboGears identity provider will encrypt passwords supplied as part of your login form. If you set the password through the password property, like my_user.password = 'secret' the password will be saved in encrypted form in the database, provided identity is up and running, or you have loaded the configuration specifying what encryption to use (the latter may be necessary in situations where identity may not yet be running, like tests).

identity.*provider.model.group"*appname*.model.Group"
Database class for the provider’s group model
identity.*provider.model.permission"*appname*.model.Permission"
Database class for the provider’s permission model
identity.*provider.model.user"*appname*.model.User"
Database class for the provider’s user model