Package trac :: Module env :: Class Environment

Class Environment

source code

           object --+    
                    |    
       core.Component --+
                        |
           object --+   |
                    |   |
core.ComponentManager --+
                        |
                       Environment
Known Subclasses:

Trac environment manager.

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

Nested Classes

Inherited from core.Component: __metaclass__

Instance Methods
 
__init__(self, path, create=False, options=[])
Initialize the Trac environment.
source code
 
backup(self, dest=None)
Create a backup of the database.
source code
 
component_activated(self, component)
Initialize additional member variables for components.
source code
 
components_section(...)
This section is used to enable or disable components provided by plugins, as well as by Trac itself.
source code
 
create(self, options=[])
Create the basic directory structure of the environment, initialize the database and populate the configuration file with default values.
source code
 
enable_component(self, cls)
Enable a component or module.
source code
 
get_db_cnx(self)
Return a database connection from the connection pool
source code
 
get_htdocs_dir(self)
Return absolute path to the htdocs directory.
source code
 
get_known_users(self, cnx=None)
Generator that yields information about all known users, i.e.
source code
 
get_log_dir(self)
Return absolute path to the log directory.
source code
 
get_read_db(self)
Return a database connection for read purposes.
source code
 
get_repository(self, reponame=None, authname=None)
Return the version control repository with the given name, or the default repository if None.
source code
 
get_system_info(self) source code
 
get_systeminfo(self)
Return a list of (name, version) tuples describing the name and version information of external packages used by Trac and plugins.
source code
 
get_templates_dir(self)
Return absolute path to the templates directory.
source code
 
get_version(self, db=None, initial=False)
Return the current version of the database.
source code
 
invalidate_known_users_cache(self)
Clear the known_users cache.
source code
 
is_component_enabled(self, cls)
Implemented to only allow activation of components that are not disabled in the configuration.
source code
 
needs_upgrade(self)
Return whether the environment needs to be upgraded.
source code
 
setup_config(self)
Load the configuration file.
source code
 
setup_log(self)
Initialize the logging sub-system.
source code
 
shutdown(self, tid=None)
Close the environment.
source code
 
upgrade(self, backup=False, backup_dest=None)
Upgrade database.
source code
 
verify(self)
Verify that the provided path points to a valid Trac environment directory.
source code
 
with_transaction(self, db=None)
Decorator for transaction functions.
source code

Inherited from core.ComponentManager: __contains__, __getitem__, disable_component, is_enabled

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__

Static Methods

Inherited from core.Component: implements

Class Variables
  abs_href = <trac.util.lazy object at 0x7f41cce585d0>
  anonymous_session_lifetime = <IntOption [trac] "anonymous_sess...
  base_url = <Option [trac] "base_url">
  base_url_for_redirect = <BoolOption [trac] "use_base_url_for_r...
  conf_dir = <trac.util.lazy object at 0x7f41cce58450>
  database_initial_version = <trac.util.lazy object at 0x7f41cce...
  database_version = <trac.util.lazy object at 0x7f41cce58410>
  db_exc = <trac.util.lazy object at 0x7f41cce58350>
  href = <trac.util.lazy object at 0x7f41cce58590>
  htdocs_dir = <trac.util.lazy object at 0x7f41cce58490>
  log_dir = <trac.util.lazy object at 0x7f41cce584d0>
  log_file = <Option [logging] "log_file">
  log_format = <Option [logging] "log_format">
  log_level = <Option [logging] "log_level">
  log_type = <Option [logging] "log_type">
  plugins_dir = <trac.util.lazy object at 0x7f41cce58510>
  project_admin = <Option [project] "admin">
  project_admin_trac_url = <Option [project] "admin_trac_url">
  project_description = <Option [project] "descr">
  project_footer = <Option [project] "footer">
  project_icon = <Option [project] "icon">
  project_name = <Option [project] "name">
  project_url = <Option [project] "url">
  required = True
  secure_cookies = <BoolOption [trac] "secure_cookies">
  shared_plugins_dir = <PathOption [inherit] "plugins_dir">
  templates_dir = <trac.util.lazy object at 0x7f41cce58550>
Properties
  db_query
Return a context manager (~trac.db.api.QueryContextManager) which can be used to obtain a read-only database connection.
  db_transaction
Return a context manager (~trac.db.api.TransactionContextManager) which can be used to obtain a writable database connection.
  env
Property returning the Environment object, which is often required for functions and methods that take a Component instance.
  setup_participants
List of components that implement ~trac.env.IEnvironmentSetupParticipant
  system_info_providers
List of components that implement ~trac.env.ISystemInfoProvider

Inherited from object: __class__

Method Details

__init__(self, path, create=False, options=[])
(Constructor)

source code 
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
Overrides: object.__init__

backup(self, dest=None)

source code 
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

component_activated(self, component)

source code 

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

Overrides: core.ComponentManager.component_activated

components_section(...)

source code 

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(self, options=[])

source code 

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.

enable_component(self, cls)

source code 
Enable a component or module.
Parameters:
  • component - can be a class or an instance.
Overrides: core.ComponentManager.enable_component

get_db_cnx(self)

source code 
Return a database connection from the connection pool

:deprecated: Use :meth:`db_transaction` or :meth:`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_known_users(self, cnx=None)

source code 

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

get_read_db(self)

source code 
Return a database connection for read purposes.

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

:deprecated: Use :meth:`db_query` instead.
             Will be removed in Trac 1.3.1.

get_repository(self, reponame=None, authname=None)

source code 

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_version(self, db=None, initial=False)

source code 

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

is_component_enabled(self, cls)

source code 

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.

Overrides: core.ComponentManager.is_component_enabled

upgrade(self, backup=False, backup_dest=None)

source code 
Upgrade database.
Parameters:
  • backup - whether or not to backup before upgrading
  • backup_dest - name of the backup file
Returns:
whether the upgrade was performed

with_transaction(self, db=None)

source code 
Decorator for transaction functions.

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


Class Variable Details

anonymous_session_lifetime

Value:
<IntOption [trac] "anonymous_session_lifetime">

base_url_for_redirect

Value:
<BoolOption [trac] "use_base_url_for_redirect">

database_initial_version

Value:
<trac.util.lazy object at 0x7f41cce58390>

Property Details

db_query

Return a context manager (~trac.db.api.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 ..."):
        ...

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

for row in env.db_query("SELECT ..."):
    ...
Get Method:
unreachable.db_query(self) - Return a context manager (~trac.db.api.QueryContextManager) which can be used to obtain a read-only database connection.

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

db_transaction

Return a context manager (~trac.db.api.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 ...")

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

env.db_transaction("UPDATE ...")
Get Method:
unreachable.db_transaction(self) - Return a context manager (~trac.db.api.TransactionContextManager) which can be used to obtain a writable database connection.

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

env

Property returning the Environment object, which is often required for functions and methods that take a Component instance.
Get Method:
unreachable.env(self) - Property returning the Environment object, which is often required for functions and methods that take a Component instance.

setup_participants

List of components that implement ~trac.env.IEnvironmentSetupParticipant
Get Method:
unreachable.extensions(component) - Return a list of components that declare to implement the extension point interface.

system_info_providers

List of components that implement ~trac.env.ISystemInfoProvider
Get Method:
unreachable.extensions(component) - Return a list of components that declare to implement the extension point interface.