Table Of Contents

Previous topic

trac.db.utils – Trac DB utilities

Next topic

trac.mimeview.api – Trac content transformation APIs

This Page

trac.env – Trac Environment model and APIs

Interfaces

class trac.env.IEnvironmentSetupParticipant

Extension point interface for components that need to participate in the creation and upgrading of Trac environments, for example to create additional database tables.

Please note that IEnvironmentSetupParticipant instances are called in arbitrary order. If your upgrades must be ordered consistently, please implement the ordering in a single IEnvironmentSetupParticipant. See the database upgrade infrastructure in Trac core for an example.

See also trac.env.IEnvironmentSetupParticipant extension point

environment_created()

Called when a new Trac environment is created.

environment_needs_upgrade(db)

Called when Trac checks whether the environment needs to be upgraded.

Should return True if this participant needs an upgrade to be performed, False otherwise.

upgrade_environment(db)

Actually perform an environment upgrade.

Implementations of this method don’t need to commit any database transactions. This is done implicitly for each participant if the upgrade succeeds without an error being raised.

However, if the upgrade_environment consists of small, restartable, steps of upgrade, it can decide to commit on its own after each successful step.

class trac.env.ISystemInfoProvider

Provider of system information, displayed in the “About Trac” page and in internal error reports.

See also trac.env.ISystemInfoProvider extension point

get_system_info()

Yield a sequence of (name, version) tuples describing the name and version information of external packages used by a component.

Components

The Environment is special in the sense it is not only a Component, but also a trac.core.ComponentManager.

class trac.env.Environment(path, create=False, options=[])

Trac environment manager.

Trac stores project information in a Trac environment. It consists of a directory structure containing among other things:

  • a configuration file,
  • project-specific templates and plugins,
  • the wiki and ticket attachments files,
  • the SQLite database file (stores tickets, wiki pages...) in case the database backend is sqlite

Initialize the Trac environment.

Parameters:
  • path – the absolute path to the Trac environment
  • create – if True, the environment is created and populated with default data; otherwise, the environment is expected to already exist.
  • options – A list of (section, name, value) tuples that define configuration options
abs_href

The application URL

backup(dest=None)

Create a backup of the database.

Parameters:dest – Destination file; if not specified, the backup is stored in a file called db_name.trac_version.bak
base_url

Reference URL for the Trac deployment.

This is the base URL that will be used when producing documents that will be used outside of the web browsing context, like for example when inserting URLs pointing to Trac resources in notification e-mails.

base_url_for_redirect

Optionally use [trac] base_url for redirects.

In some configurations, usually involving running Trac behind a HTTP proxy, Trac can’t automatically reconstruct the URL that is used to access it. You may need to use this option to force Trac to use the base_url setting also for redirects. This introduces the obvious limitation that this environment will only be usable when accessible from that URL, as redirects are frequently used. ‘’(since 0.10.5)’‘

component_activated(component)

Initialize additional member variables for components.

Every component activated through the Environment object gets three member variables: env (the environment object), config (the environment configuration) and log (a logger object).

components_section

This section is used to enable or disable components provided by plugins, as well as by Trac itself. The component to enable/disable is specified via the name of the option. Whether its enabled is determined by the option value; setting the value to enabled or on will enable the component, any other value (typically disabled or off) will disable the component.

The option name is either the fully qualified name of the components or the module/package prefix of the component. The former enables/disables a specific component, while the latter enables/disables any component in the specified package/module.

Consider the following configuration snippet: {{{ [components] trac.ticket.report.ReportModule = disabled webadmin.* = enabled }}}

The first option tells Trac to disable the [wiki:TracReports report module]. The second option instructs Trac to enable all components in the webadmin package. Note that the trailing wildcard is required for module/package matching.

To view the list of active components, go to the ‘’Plugins’’ page on ‘’About Trac’’ (requires CONFIG_VIEW [wiki:TracPermissions permissions]).

See also: TracPlugins

create(options=[])

Create the basic directory structure of the environment, initialize the database and populate the configuration file with default values.

If options contains (‘inherit’, ‘file’), default values will not be loaded; they are expected to be provided by that file or other options.

database_initial_version

Returns the version of the database at the time of creation.

In practice, for database created before 0.11, this will return False which is “older” than any db version number.

Since 1.0.2:
database_version

Returns the current version of the database.

Since 1.0.2:
db_exc

Return an object (typically a module) containing all the backend-specific exception types as attributes, named according to the Python Database API (http://www.python.org/dev/peps/pep-0249/).

To catch a database exception, use the following pattern:

try:
    with env.db_transaction as db:
        ...
except env.db_exc.IntegrityError, e:
    ...
db_query

Return a context manager (QueryContextManager) which can be used to obtain a read-only database connection.

Example:

with env.db_query as db:
    cursor = db.cursor()
    cursor.execute("SELECT ...")
    for row in cursor.fetchall():
        ...

Note that a connection retrieved this way can be “called” directly in order to execute a query:

with env.db_query as db:
    for row in db("SELECT ..."):
        ...
Warning:after a with env.db_query as db block, though the db variable is still defined, you shouldn’t use it as it might have been closed when exiting the context, if this context was the outermost context (db_query or db_transaction).

If you don’t need to manipulate the connection itself, this can even be simplified to:

for row in env.db_query("SELECT ..."):
    ...
db_transaction

Return a context manager (TransactionContextManager) which can be used to obtain a writable database connection.

Example:

with env.db_transaction as db:
    cursor = db.cursor()
    cursor.execute("UPDATE ...")

Upon successful exit of the context, the context manager will commit the transaction. In case of nested contexts, only the outermost context performs a commit. However, should an exception happen, any context manager will perform a rollback. You should not call commit() yourself within such block, as this will force a commit even if that transaction is part of a larger transaction.

Like for its read-only counterpart, you can directly execute a DML query on the db:

with env.db_transaction as db:
    db("UPDATE ...")
Warning:after a with env.db_transaction as db` block, though the db variable is still available, you shouldn’t use it as it might have been closed when exiting the context, if this context was the outermost context (db_query or db_transaction).

If you don’t need to manipulate the connection itself, this can also be simplified to:

env.db_transaction("UPDATE ...")
enable_component(cls)

Enable a component or module.

env

Property returning the Environment object, which is often required for functions and methods that take a Component instance.

get_db_cnx()

Return a database connection from the connection pool

Deprecated:Use db_transaction() or db_query() instead. Removed in Trac 1.1.2.

db_transaction for obtaining the db database connection which can be used for performing any query (SELECT/INSERT/UPDATE/DELETE):

with env.db_transaction as db:
    ...

Note that within the block, you don’t need to (and shouldn’t) call commit() yourself, the context manager will take care of it (if it’s the outermost such context manager on the stack).

db_query for obtaining a db database connection which can be used for performing SELECT queries only:

with env.db_query as db:
    ...
get_htdocs_dir()

Return absolute path to the htdocs directory.

get_known_users(cnx=None)

Generator that yields information about all known users, i.e. users that have logged in to this Trac environment and possibly set their name and email.

This function generates one tuple for every user, of the form (username, name, email) ordered alpha-numerically by username.

Parameters:cnx – the database connection; if ommitted, a new connection is retrieved
Since 1.0:deprecation warning: the cnx parameter is no longer used and will be removed in version 1.1.1
get_log_dir()

Return absolute path to the log directory.

get_read_db()

Return a database connection for read purposes.

See trac.db.api.get_read_db for detailed documentation.

Deprecated:Use db_query() instead. Will be removed in Trac 1.3.1.
get_repository(reponame=None, authname=None)

Return the version control repository with the given name, or the default repository if None.

The standard way of retrieving repositories is to use the methods of RepositoryManager. This method is retained here for backward compatibility.

Parameters:
  • reponame – the name of the repository
  • authname – the user name for authorization (not used anymore, left here for compatibility with 0.11)
get_systeminfo()

Return a list of (name, version) tuples describing the name and version information of external packages used by Trac and plugins.

get_templates_dir()

Return absolute path to the templates directory.

get_version(db=None, initial=False)

Return the current version of the database. If the optional argument initial is set to True, the version of the database used at the time of creation will be returned.

In practice, for database created before 0.11, this will return False which is “older” than any db version number.

Since:0.11
Since 1.0:deprecation warning: the db parameter is no longer used and will be removed in version 1.1.1
Since 1.0.2:The lazily-evaluated attributes database_version and database_initial_version should be used instead. This method will be renamed to a private method in release 1.3.1.
href

The application root path

invalidate_known_users_cache()

Clear the known_users cache.

is_component_enabled(cls)

Implemented to only allow activation of components that are not disabled in the configuration.

This is called by the ComponentManager base class when a component is about to be activated. If this method returns False, the component does not get activated. If it returns None, the component only gets activated if it is located in the plugins directory of the environment.

log_file

If log_type is file, this should be a path to the log-file. Relative paths are resolved relative to the log directory of the environment.

log_format

Custom logging format.

If nothing is set, the following will be used:

Trac[$(module)s] $(levelname)s: $(message)s

In addition to regular key names supported by the Python logger library (see http://docs.python.org/library/logging.html), one could use:

  • $(path)s the path for the current environment
  • $(basename)s the last path component of the current environment
  • $(project)s the project name

Note the usage of $(...)s instead of %(...)s as the latter form would be interpreted by the ConfigParser itself.

Example: ($(thread)d) Trac[$(basename)s:$(module)s] $(levelname)s: $(message)s

‘’(since 0.10.5)’‘

log_level

Level of verbosity in log.

Should be one of (CRITICAL, ERROR, WARN, INFO, DEBUG).

log_type

Logging facility to use.

Should be one of (none, file, stderr, syslog, winlog).

needs_upgrade()

Return whether the environment needs to be upgraded.

project_admin

E-Mail address of the project’s administrator.

project_admin_trac_url

Base URL of a Trac instance where errors in this Trac should be reported.

This can be an absolute or relative URL, or ‘.’ to reference this Trac instance. An empty value will disable the reporting buttons. (‘’since 0.11.3’‘)

project_description

Short description of the project.

Page footer text (right-aligned).

project_icon

URL of the icon of the project.

project_name

Name of the project.

project_url

URL of the main project web site, usually the website in which the base_url resides. This is used in notification e-mails.

secure_cookies

Restrict cookies to HTTPS connections.

When true, set the secure flag on all cookies so that they are only sent to the server on HTTPS connections. Use this if your Trac instance is only accessible through HTTPS. (‘’since 0.11.2’‘)

setup_config()

Load the configuration file.

setup_log()

Initialize the logging sub-system.

setup_participants

List of components that implement IEnvironmentSetupParticipant

shared_plugins_dir

Path to the //shared plugins directory//.

Plugins in that directory are loaded in addition to those in the directory of the environment plugins, with this one taking precedence.

(‘’since 0.11’‘)

shutdown(tid=None)

Close the environment.

system_info_providers

List of components that implement ISystemInfoProvider

upgrade(backup=False, backup_dest=None)

Upgrade database.

Parameters:
  • backup – whether or not to backup before upgrading
  • backup_dest – name of the backup file
Returns:

whether the upgrade was performed

verify()

Verify that the provided path points to a valid Trac environment directory.

with_transaction(db=None)

Decorator for transaction functions.

Deprecated:Use the query and transaction context managers instead. Will be removed in Trac 1.3.1.

Functions

trac.env.open_environment(env_path=None, use_cache=False)

Open an existing environment object, and verify that the database is up to date.

Parameters:
  • env_path – absolute path to the environment directory; if ommitted, the value of the TRAC_ENV environment variable is used
  • use_cache – whether the environment should be cached for subsequent invocations of this function
Returns:

the Environment object