trac.env – Trac Environment model and APIs

Interfaces

class trac.env.IEnvironmentSetupParticipant

Bases: trac.core.Interface

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()

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()

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

Bases: trac.core.Interface

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=[])

Bases: trac.core.Component, trac.core.ComponentManager

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

attachments_dir

Absolute path to the attachments directory.

Since:1.3.1
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.

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).

component_guard(*args, **kwds)

Traps any runtime exception raised when working with a component and logs the error.

Parameters:
  • component – the component responsible for any error that could happen inside the context
  • reraise – if True, an error is logged but not suppressed. By default, errors are suppressed.
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 acct_mgr.* = enabled }}}

The first option tells Trac to disable the [wiki:TracReports report module]. The second option instructs Trac to enable all components in the acct_mgr 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

conf_dir

Absolute path to the conf directory.

Since:1.0.11
config_file_path

Path of the trac.ini file.

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.

Raises:
  • TracError – if the base directory of path does not exist.
  • TracError – if path exists and is not empty.
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 as 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.

files_dir

Absolute path to the files directory.

Since:1.3.2
get_known_users(as_dict=False)

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

By default this function returns a iterator that yields one tuple for every user, of the form (username, name, email), ordered alpha-numerically by username. When as_dict is True the function returns a dictionary mapping username to a (name, email) tuple.

Since 1.2:the as_dict parameter is available.
get_systeminfo()

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

Since 1.3.1:deprecated and will be removed in 1.5.1. Use system_info property instead.
href

The application root path

htdocs_dir

Absolute path to the htdocs directory.

Since:1.0.11
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_dir

Absolute path to the log directory.

Since:1.0.11
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_file_path

Path to the log file.

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 [http://docs.python.org/library/logging.html Python logger library] 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

log_level

Level of verbosity in log.

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

log_type

Logging facility to use.

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

name

The environment name.

Since:1.2
needs_upgrade()

Return whether the environment needs to be upgraded.

plugins_dir

Absolute path to the plugins directory.

Since:1.0.11
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.

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.

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.

shutdown(tid=None)

Close the environment.

system_info

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

system_info_providers

List of components that implement ISystemInfoProvider

templates_dir

Absolute path to the templates directory.

Since:1.0.11
trac_version

Returns the version of Trac. :since: 1.2

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.

class trac.env.EnvironmentSetup

Bases: trac.core.Component

Manage automatic environment upgrades.

environment_created()

Insert default data into the database.

class trac.env.EnvironmentAdmin

Bases: trac.core.Component

trac-admin command provider for environment administration.

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 omitted, 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

Exceptions

exception trac.env.BackupError

Bases: trac.core.TracBaseError, exceptions.RuntimeError

Exception raised during an upgrade when the DB backup fails.