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

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 otherwise, the environment is expected to already exist.
  • options – A list of (section, name, value) tuples that define configuration options
  • default_data – if True (the default), the environment is populated with default data when created.
system_info_providers

List of components that implement ISystemInfoProvider

setup_participants

List of components that implement IEnvironmentSetupParticipant

components_section

Enable or disable components provided by Trac and plugins. The component to enable/disable is specified by the option name. The enabled state 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 component 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: {{{#!ini [components] trac.ticket.report.ReportModule = disabled acct_mgr.* = enabled }}}

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

To view the list of active components, go to the ‘’Plugins’’ section of ‘’About Trac’’ (requires CONFIG_VIEW [TracPermissions permission]).

See also: TracPlugins

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.

Non-absolute paths are relative to the Environment conf directory.

base_url

Base URL of the Trac site.

This is used to produce documents outside of the web browsing context, such as URLs in notification e-mails that point to Trac resources.

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.

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.

anonymous_session_lifetime

Lifetime of the anonymous session, in days.

Set the option to 0 to disable purging old anonymous sessions. (‘’since 1.0.17’’)

project_name

Name of the project.

project_description

Short description of the project.

project_url

URL of the project web site.

This is usually the domain in which the base_url resides. For example, the project URL might be !https://myproject.com, with the Trac site (base_url) residing at either !https://trac.myproject.com or !https://myproject.com/trac. The project URL is added to the footer of notification e-mails.

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.

Page footer text (right-aligned).

project_icon

URL of the icon of the project.

log_type

Logging facility to use.

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

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_level

Level of verbosity in log.

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

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

name

The environment name.

Since:1.2
env

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

system_info

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

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

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.

enable_component(cls)

Enable a component or module.

component_guard(**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.
verify()

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

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 ...")
shutdown(tid=None)

Close the environment.

create(options=[], default_data=True)

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_version

Returns the current version of the database.

Since 1.0.2:
database_initial_version

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

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

Since 1.0.2:
trac_version

Returns the version of Trac. :since: 1.2

setup_config()

Load the configuration file.

config_file_path

Path of the trac.ini file.

log_file_path

Path to the log file.

attachments_dir

Absolute path to the attachments directory.

Since:1.3.1
conf_dir

Absolute path to the conf directory.

Since:1.0.11
files_dir

Absolute path to the files directory.

Since:1.3.2
htdocs_dir

Absolute path to the htdocs directory.

Since:1.0.11
log_dir

Absolute path to the log directory.

Since:1.0.11
plugins_dir

Absolute path to the plugins directory.

Since:1.0.11
templates_dir

Absolute path to the templates directory.

Since:1.0.11
setup_log()

Initialize the logging sub-system.

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 an 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.
invalidate_known_users_cache()

Clear the known_users cache.

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

Return whether the environment needs to be upgraded.

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

href

The application root path

abs_href

The application URL

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.