Configuration — Alembic 1.18.2 documentation

Skip to main content
`Ctrl`+`K`

# Configuration

Note

this section discusses the internal API of Alembic as regards internal configuration constructs. This section is only useful for developers who wish to extend the capabilities of Alembic. For documentation on configuration of an Alembic environment, please see Tutorial.

The `Config` object represents the configuration passed to the Alembic environment. From an API usage perspective, it is needed for the following use cases:

- to create a `ScriptDirectory`, which allows you to work with the actual script files in a migration environment

- to create an `EnvironmentContext`, which allows you to actually run the `env.py` module within the migration environment

- to programmatically run any of the commands in the Commands module.

The `Config` is not needed for these cases:

- to instantiate a `MigrationContext` directly - this object only needs a SQLAlchemy connection or dialect name.

- to instantiate a `Operations` object - this object only needs a `MigrationContext`.

class alembic.config.CommandFunction(*args, **kwargs)

  A function that may be registered in the CLI as an alembic command. It must be a named function and it must accept a `Config` object as the first argument.

  Added in version 1.15.3.

class alembic.config.CommandLine(prog: str | None = None)

  Provides the command line interface to Alembic.

  main(argv: Sequence[str] | None = None) → None

    Executes the command line with the provided arguments.

  register_command(fn: CommandFunction) → None

    Registers a function as a CLI subcommand. The subcommand name matches the function name, the arguments are extracted from the signature and the help text is read from the docstring.

    Added in version 1.15.3.

    See also

    Extend CommandLine with custom commands

class alembic.config.Config(file_: str | PathLike[str] | None = None, toml_file: str | PathLike[str] | None = None, ini_section: str = 'alembic', output_buffer: TextIO | None = None, stdout: TextIO = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, cmd_opts: Namespace | None = None, config_args: Mapping[str, ~typing.Any]={}, attributes: Dict[str, ~typing.Any] | None=None)

  Represent an Alembic configuration.

  Within an `env.py` script, this is available via the `EnvironmentContext.config` attribute, which in turn is available at `alembic.context`:

      from alembic import context

      some_param = context.config.get_main_option("my option")

  When invoking Alembic programmatically, a new `Config` can be created by passing the name of an .ini file to the constructor:

      from alembic.config import Config
      alembic_cfg = Config("/path/to/yourapp/alembic.ini")

  With a `Config` object, you can then run Alembic commands programmatically using the directives in `alembic.command`.

  The `Config` object can also be constructed without a filename. Values can be set programmatically, and new sections will be created as needed:

      from alembic.config import Config
      alembic_cfg = Config()
      alembic_cfg.set_main_option("script_location", "myapp:migrations")
      alembic_cfg.set_main_option("sqlalchemy.url", "postgresql://foo/bar")
      alembic_cfg.set_section_option("mysection", "foo", "bar")

  Warning

  When using programmatic configuration, make sure the `env.py` file in use is compatible with the target configuration; including that the call to Python `logging.fileConfig()` is omitted if the programmatic configuration doesn’t actually include logging directives.

  For passing non-string values to environments, such as connections and engines, use the `Config.attributes` dictionary:

      with engine.begin() as connection:
          alembic_cfg.attributes['connection'] = connection
          command.upgrade(alembic_cfg, "head")

  Parameters:

    - file_ – name of the .ini file to open if an `alembic.ini` is to be used. This should refer to the `alembic.ini` file, either as a filename or a full path to the file. This filename if passed must refer to an ini file in ConfigParser format only.

    - toml_file –

      name of the pyproject.toml file to open if a `pyproject.toml` file is to be used. This should refer to the `pyproject.toml` file, either as a filename or a full path to the file. This file must be in toml format. Both `Config.file_` and `Config.toml_file` may be passed simultaneously, or exclusively.

      Added in version 1.16.0.

    - ini_section – name of the main Alembic section within the .ini file

    - output_buffer – optional file-like input buffer which will be passed to the `MigrationContext` - used to redirect the output of “offline generation” when using Alembic programmatically.

    - stdout – buffer where the “print” output of commands will be sent. Defaults to `sys.stdout`.

    - config_args – A dictionary of keys and values that will be used for substitution in the alembic config file, as well as the pyproject.toml file, depending on which / both are used. The dictionary as given is copied to two new, independent dictionaries, stored locally under the attributes `.config_args` and `.toml_args`. Both of these dictionaries will also be populated with the replacement variable `%(here)s`, which refers to the location of the .ini and/or .toml file as appropriate.

    - attributes –

      optional dictionary of arbitrary Python keys/values, which will be populated into the `Config.attributes` dictionary.

      See also

      Sharing a Connection across one or more programmatic migration commands

  Construct a new `Config`

  attributes

    A Python dictionary for storage of additional state.

    This is a utility dictionary which can include not just strings but engines, connections, schema objects, or anything else. Use this to pass objects into an env.py script, such as passing a `sqlalchemy.engine.base.Connection` when calling commands from `alembic.command` programmatically.

    See also

    Sharing a Connection across one or more programmatic migration commands

    `Config.attributes`

  cmd_opts: Namespace | None = None

    The command-line options passed to the `alembic` script.

    Within an `env.py` script this can be accessed via the `EnvironmentContext.config` attribute.

    See also

    `EnvironmentContext.get_x_argument()`

  config_file_name: str | None = None

    Filesystem path to the .ini file in use.

  config_ini_section: str = None

    Name of the config file section to read basic configuration from. Defaults to `alembic`, that is the `[alembic]` section of the .ini file. This value is modified using the `-n/--name` option to the Alembic runner.

  file_config

    Return the underlying `ConfigParser` object.

    Dir*-ect access to the .ini file is available here, though the `Config.get_section()` and `Config.get_main_option()` methods provide a possibly simpler interface.

  get_alembic_option(name: str, default: str) → str
  get_alembic_option(name: str, default: str | None = None) → str | None

    Return an option from the “[alembic]” or “[tool.alembic]” section of the configparser-parsed .ini file (e.g. `alembic.ini`) or toml-parsed `pyproject.toml` file.

    The value returned is expected to be None, string, list of strings, or dictionary of strings. Within each type of string value, the `%(here)s` token is substituted out with the absolute path of the `pyproject.toml` file, as are other tokens which are extracted from the `Config.config_args` dictionary.

    Searches always prioritize the configparser namespace first, before searching in the toml namespace.

    If Alembic was run using the `-n/--name` flag to indicate an alternate main section name, this is taken into account only for the configparser-parsed .ini file. The section name in toml is always `[tool.alembic]`.

    Added in version 1.16.0.

  get_main_option(name: str, default: str) → str
  get_main_option(name: str, default: str | None = None) → str | None

    Return an option from the ‘main’ section of the .ini file.

    This defaults to being a key from the `[alembic]` section, unless the `-n/--name` flag were used to indicate a different section.

    Does NOT consume from the pyproject.toml file.

    See also

    `Config.get_alembic_option()` - includes pyproject support

  get_section(name: str, default: None = None) → Dict[str, str] | None
  get_section(name: str, default: Dict[str, str]) → Dict[str, str]
  get_section(name: str, default: Mapping[str, str]) → Dict[str, str] | Mapping[str, str]

    Return all the configuration options from a given .ini file section as a dictionary.

    If the given section does not exist, the value of `default` is returned, which is expected to be a dictionary or other mapping.

  get_section_option(section: str, name: str, default: str | None = None) → str | None

    Return an option from the given section of the .ini file.

  get_template_directory() → str

    Return the directory where Alembic setup templates are found.

    This method is used by the alembic `init` and `list_templates` commands.

  messaging_opts

    The messaging options.

  print_stdout(text: str, *arg: Any) → None

    Render a message to standard out.

    When `Config.print_stdout()` is called with additional args those arguments will formatted against the provided text, otherwise we simply output the provided text verbatim.

    This is a no-op when the``quiet`` messaging option is enabled.

    e.g.:

        >>> config.print_stdout('Some text %s', 'arg')
        Some Text arg

  set_main_option(name: str, value: str) → None

    Set an option programmatically within the ‘main’ section.

    This overrides whatever was in the .ini file.

    Parameters:

      - name – name of the value

      - value – the value. Note that this value is passed to `ConfigParser.set`, which supports variable interpolation using pyformat (e.g. `%(some_value)s`). A raw percent sign not part of an interpolation symbol must therefore be escaped, e.g. `%%`. The given value may refer to another value already in the file using the interpolation format.

  set_section_option(section: str, name: str, value: str) → None

    Set an option programmatically within the given section.

    The section is created if it doesn’t exist already. The value here will override whatever was in the .ini file.

    Does NOT consume from the pyproject.toml file.

    See also

    `Config.get_alembic_option()` - includes pyproject support

    Parameters:

      - section – name of the section

      - name – name of the value

      - value – the value. Note that this value is passed to `ConfigParser.set`, which supports variable interpolation using pyformat (e.g. `%(some_value)s`). A raw percent sign not part of an interpolation symbol must therefore be escaped, e.g. `%%`. The given value may refer to another value already in the file using the interpolation format.

  toml_alembic_config

    Return a dictionary of the [tool.alembic] section from pyproject.toml

  toml_file_name: str | None = None

    Filesystem path to the pyproject.toml file in use.

    Added in version 1.16.0.

class alembic.config.MessagingOptions

alembic.config.main(argv: Sequence[str] | None = None, prog: str | None = None, **kwargs: Any) → None

  The console runner function for Alembic.