<commit_before>:tocdepth: 3

*************
Configuration
*************

Configuration in CherryPy is implemented via dictionaries. Keys are strings
which name the mapped value; values may be of any type.

In CherryPy 3, you use configuration (files or dicts) to set attributes
directly on the engine, server, request, response, and log objects. So the
best way to know the full range of what's available in the config file is to
simply import those objects and see what ``help(obj)`` tells you.

Architecture
============

The first thing you need to know about CherryPy 3's configuration is that it
separates *global* config from *application* config. If you're deploying
multiple *applications* at the same *site* (and more and more people are,
as Python web apps are tending to decentralize), you need to be careful to
separate the configurations, as well. There's only ever one "global config",
but there is a separate "app config" for each app you deploy.

CherryPy *Requests* are part of an *Application*, which runs in a *global*
context, and configuration data may apply to any of those three scopes.
Let's look at each of those scopes in turn.

Global config
-------------

Global config entries apply everywhere, and are stored in
:class:`cherrypy.config <cherrypy._cpconfig.Config>`. This flat dict only holds
global config data; that is, "site-wide" config entries which affect all
mounted applications.

Global config is stored in the
:class:`cherrypy.config <cherrypy._cpconfig.Config>` dict,
and you therefore update it by calling ``cherrypy.config.update(conf)``.
The ``conf`` argument can be either a filename, an open file, or a dict of
config entries. Here's an example of passing a dict argument::

    cherrypy.config.update({'server.socket_host': '172.16.58.3',
                            'server.socket_port': 80,
                           })

The ``server.socket_host`` option in this example determines on which network
interface CherryPy will listen. The ``server.socket_port`` option declares
the TCP port on which to listen.

Application config
------------------

Application entries apply to a single mounted application, and are stored on
each Application object itself as
:attr:`app.config <cherrypy._cptree.Application.config>`. This is a two-level
dict where each top-level key is a path, or "relative URL" (for example,
``"/"`` or ``"/my/page"``), and each value is a dict of config entries.
The URL's are relative to the script name (mount point) of the Application.
Usually, all this data is provided in the call to
``tree.mount(root(), script_name='/path/to', config=conf)``,
although you may also use ``app.merge(conf)``.
The ``conf`` argument can be either a filename, an open file, or a dict of
config entries.

Configuration file example::

    [/]
    tools.trailing_slash.on = False
    request.dispatch: cherrypy.dispatch.MethodDispatcher()

or, in python code::

    config = {'/': 
        {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.trailing_slash.on': False,
        }
    }
    cherrypy.tree.mount(Root(), config=config)

CherryPy only uses sections that start with ``"/"`` (except
``[global]``, see below). That means you can place your own configuration
entries in a CherryPy config file by giving them a section name which does not
start with ``"/"``. For example, you might include database entries like this::

    [global]
    server.socket_host: "0.0.0.0"

    [Databases]
    driver: "postgres"
    host: "localhost"
    port: 5432

    [/path]
    response.timeout: 6000

Then, in your application code you can read these values during request time
via ``cherrypy.request.app.config['Databases']``. For code that is outside the
request process, you'll have to pass a reference to your Application around.

Request config
--------------

Each Request object possesses a single
:attr:`request.config <cherrypy._cprequest.Request.config>` dict. Early in the
request process, this dict is populated by merging Global config, Application
config, and any config acquired while looking up the page handler (see next).
This dict contains only those config entries which apply to the given request.

.. note::

   when you do an :class:`InternalRedirect<cherrypy._cperror.InternalRedirect`,
   this config attribute is recalculated for the new path.

Declaration
===========

Configuration data may be supplied as a Python dictionary, as a filename,
or as an open file object.

Configuration files
-------------------

When you supply a filename or file, CherryPy uses Python's builtin ConfigParser;
you declare Application config by writing each path as a section header,
and each entry as a ``"key: value"`` (or ``"key = value"``) pair::

    [/path/to/my/page]
    response.stream: True
    tools.trailing_slash.extra = False

Combined Configuration Files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If you are only deploying a single application, you can make a single config
file that contains both global and app entries. Just stick the global entries
into a config section named ``[global]``, and pass the same file to both
:func:`config.update <cherrypy._cpconfig.Config.update>` and
:func:`tree.mount <cherrypy._cptree.Tree.mount`. If you're calling
``cherrypy.quickstart(app root, script name, config)``, it will pass the
config to both places for you. But as soon as you decide to add another
application to the same site, you need to separate the two config files/dicts.

Separate Configuration Files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If you're deploying more than one application in the same process, you need
(1) file for global config, plus (1) file for *each* Application.
The global config is applied by calling
:func:`cherrypy.config.update <cherrypy._cpconfig.Config.update>`,
and application config is usually passed in a call to
:func:`cherrypy.tree.mount <cherrypy._cptree.Tree.mount>`.

In general, you should set global config first, and then mount each
application with its own config. Among other benefits, this allows you to set
up global logging so that, if something goes wrong while trying to mount
an application, you'll see the tracebacks. In other words, use this order::

    # global config
    cherrypy.config.update({'environment': 'production',
                            'log.error_file': 'site.log',
                            # ...
                            })

    # Mount each app and pass it its own config
    cherrypy.tree.mount(root1, "/", appconf1)
    cherrypy.tree.mount(root2, "/forum", appconf2)
    cherrypy.tree.mount(root3, "/blog", appconf3)

    if hasattr(cherrypy.engine, 'block'):
        # 3.1 syntax
        cherrypy.engine.start()
        cherrypy.engine.block()
    else:
        # 3.0 syntax
        cherrypy.server.quickstart()
        cherrypy.engine.start()

Values in config files use Python syntax
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Config entries are always a key/value pair, like ``server.socket_port = 8080``.
The key is always a name, and the value is always a Python object. That is,
if the value you are setting is an ``int`` (or other number), it needs to look
like a Python ``int``; for example, ``8080``. If the value is a string, it
needs to be quoted, just like a Python string. Arbitrary objects can also be<commit_msg>Update another example which incorrectly used script_name of "/" for the root of the application.<commit_after>:tocdepth: 3

*************
Configuration
*************

Configuration in CherryPy is implemented via dictionaries. Keys are strings
which name the mapped value; values may be of any type.

In CherryPy 3, you use configuration (files or dicts) to set attributes
directly on the engine, server, request, response, and log objects. So the
best way to know the full range of what's available in the config file is to
simply import those objects and see what ``help(obj)`` tells you.

Architecture
============

The first thing you need to know about CherryPy 3's configuration is that it
separates *global* config from *application* config. If you're deploying
multiple *applications* at the same *site* (and more and more people are,
as Python web apps are tending to decentralize), you need to be careful to
separate the configurations, as well. There's only ever one "global config",
but there is a separate "app config" for each app you deploy.

CherryPy *Requests* are part of an *Application*, which runs in a *global*
context, and configuration data may apply to any of those three scopes.
Let's look at each of those scopes in turn.

Global config
-------------

Global config entries apply everywhere, and are stored in
:class:`cherrypy.config <cherrypy._cpconfig.Config>`. This flat dict only holds
global config data; that is, "site-wide" config entries which affect all
mounted applications.

Global config is stored in the
:class:`cherrypy.config <cherrypy._cpconfig.Config>` dict,
and you therefore update it by calling ``cherrypy.config.update(conf)``.
The ``conf`` argument can be either a filename, an open file, or a dict of
config entries. Here's an example of passing a dict argument::

    cherrypy.config.update({'server.socket_host': '172.16.58.3',
                            'server.socket_port': 80,
                           })

The ``server.socket_host`` option in this example determines on which network
interface CherryPy will listen. The ``server.socket_port`` option declares
the TCP port on which to listen.

Application config
------------------

Application entries apply to a single mounted application, and are stored on
each Application object itself as
:attr:`app.config <cherrypy._cptree.Application.config>`. This is a two-level
dict where each top-level key is a path, or "relative URL" (for example,
``"/"`` or ``"/my/page"``), and each value is a dict of config entries.
The URL's are relative to the script name (mount point) of the Application.
Usually, all this data is provided in the call to
``tree.mount(root(), script_name='/path/to', config=conf)``,
although you may also use ``app.merge(conf)``.
The ``conf`` argument can be either a filename, an open file, or a dict of
config entries.

Configuration file example::

    [/]
    tools.trailing_slash.on = False
    request.dispatch: cherrypy.dispatch.MethodDispatcher()

or, in python code::

    config = {'/': 
        {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.trailing_slash.on': False,
        }
    }
    cherrypy.tree.mount(Root(), config=config)

CherryPy only uses sections that start with ``"/"`` (except
``[global]``, see below). That means you can place your own configuration
entries in a CherryPy config file by giving them a section name which does not
start with ``"/"``. For example, you might include database entries like this::

    [global]
    server.socket_host: "0.0.0.0"

    [Databases]
    driver: "postgres"
    host: "localhost"
    port: 5432

    [/path]
    response.timeout: 6000

Then, in your application code you can read these values during request time
via ``cherrypy.request.app.config['Databases']``. For code that is outside the
request process, you'll have to pass a reference to your Application around.

Request config
--------------

Each Request object possesses a single
:attr:`request.config <cherrypy._cprequest.Request.config>` dict. Early in the
request process, this dict is populated by merging Global config, Application
config, and any config acquired while looking up the page handler (see next).
This dict contains only those config entries which apply to the given request.

.. note::

   when you do an :class:`InternalRedirect<cherrypy._cperror.InternalRedirect`,
   this config attribute is recalculated for the new path.

Declaration
===========

Configuration data may be supplied as a Python dictionary, as a filename,
or as an open file object.

Configuration files
-------------------

When you supply a filename or file, CherryPy uses Python's builtin ConfigParser;
you declare Application config by writing each path as a section header,
and each entry as a ``"key: value"`` (or ``"key = value"``) pair::

    [/path/to/my/page]
    response.stream: True
    tools.trailing_slash.extra = False

Combined Configuration Files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If you are only deploying a single application, you can make a single config
file that contains both global and app entries. Just stick the global entries
into a config section named ``[global]``, and pass the same file to both
:func:`config.update <cherrypy._cpconfig.Config.update>` and
:func:`tree.mount <cherrypy._cptree.Tree.mount`. If you're calling
``cherrypy.quickstart(app root, script name, config)``, it will pass the
config to both places for you. But as soon as you decide to add another
application to the same site, you need to separate the two config files/dicts.

Separate Configuration Files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If you're deploying more than one application in the same process, you need
(1) file for global config, plus (1) file for *each* Application.
The global config is applied by calling
:func:`cherrypy.config.update <cherrypy._cpconfig.Config.update>`,
and application config is usually passed in a call to
:func:`cherrypy.tree.mount <cherrypy._cptree.Tree.mount>`.

In general, you should set global config first, and then mount each
application with its own config. Among other benefits, this allows you to set
up global logging so that, if something goes wrong while trying to mount
an application, you'll see the tracebacks. In other words, use this order::

    # global config
    cherrypy.config.update({'environment': 'production',
                            'log.error_file': 'site.log',
                            # ...
                            })

    # Mount each app and pass it its own config
    cherrypy.tree.mount(root1, "", appconf1)
    cherrypy.tree.mount(root2, "/forum", appconf2)
    cherrypy.tree.mount(root3, "/blog", appconf3)

    if hasattr(cherrypy.engine, 'block'):
        # 3.1 syntax
        cherrypy.engine.start()
        cherrypy.engine.block()
    else:
        # 3.0 syntax
        cherrypy.server.quickstart()
        cherrypy.engine.start()

Values in config files use Python syntax
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Config entries are always a key/value pair, like ``server.socket_port = 8080``.
The key is always a name, and the value is always a Python object. That is,
if the value you are setting is an ``int`` (or other number), it needs to look
like a Python ``int``; for example, ``8080``. If the value is a string, it
needs to be quoted, just like a Python string. Arbitrary objects can also be
{'fraction_non_alphanumeric': 0.11036880496284682, 'fraction_numerical': 0.006135387551980367, 'mean_word_length': 3.7049390635022452, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 4, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4131518', 'n_tokens_mistral': 4046, 'n_tokens_neox': 3864, 'n_words': 1840}