CherryPy / sphinx / source / concepts / config.rst

Robert Brewer 6e177f1 













































Chris Beelby 7142f55 
Robert Brewer 6e177f1 































Chris Beelby 485845b 
Robert Brewer 6e177f1 
Chris Beelby 485845b 
Robert Brewer 6e177f1 



















































































Chris Beelby 23506a1 
Robert Brewer 6e177f1 















































































































Robert Brewer 979df03 














Robert Brewer 6e177f1 


Robert Brewer 979df03 

Robert Brewer 6e177f1 

Robert Brewer 979df03 


Robert Brewer 6e177f1 
Robert Brewer 979df03 



Robert Brewer 6e177f1 

Robert Brewer 979df03 
Robert Brewer 6e177f1 





Robert Brewer 979df03 
Robert Brewer 6e177f1 







Robert Brewer 979df03 
Robert Brewer 6e177f1 



















Robert Brewer 979df03 
Robert Brewer 6e177f1 













Robert Brewer 979df03 
Robert Brewer 6e177f1 


Robert Brewer 979df03 

Robert Brewer 6e177f1 

Robert Brewer 979df03 

Robert Brewer 6e177f1 
Robert Brewer 979df03 



Robert Brewer 6e177f1 






























































  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
: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': '64.72.221.48',
                            '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
created, just like in Python code (assuming they can be found/imported).
Here's an extended example, showing you some of the different types::

    [global]
    log.error_file: "/home/fumanchu/myapp.log"
    environment = 'production'
    server.max_request_body_size: 1200

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

.. _cp_config:

_cp_config: attaching config to handlers
----------------------------------------

Config files have a severe limitation: values are always keyed by URL.
For example::

    [/path/to/page]
    methods_with_bodies = ("POST", "PUT", "PROPPATCH")

It's obvious that the extra method is the norm for that path; in fact,
the code could be considered broken without it. In CherryPy, you can attach
that bit of config directly on the page handler::

    def page(self):
        return "Hello, world!"
    page.exposed = True
    page._cp_config = {"request.methods_with_bodies": ("POST", "PUT", "PROPPATCH")}

``_cp_config`` is a reserved attribute which the dispatcher looks for at
each node in the object tree. The ``_cp_config`` attribute must be a CherryPy
config dictionary. If the dispatcher finds a ``_cp_config`` attribute,
it merges that dictionary into the rest of the config. The entire merged
config dictionary is placed in
:attr:`cherrypy.request.config <cherrypy._cprequest.Request.config>`.

This can be done at any point in the tree of objects; for example, we could have
attached that config to a class which contains the page method::

    class SetOPages:

        _cp_config = {"request.methods_with_bodies": ("POST", "PUT", "PROPPATCH")}

        def page(self):
            return "Hullo, Werld!"
        page.exposed = True

.. note::

   This behavior is only guaranteed for the default dispatcher. Other
   dispatchers may have different restrictions on where you can attach
   ``_cp_config`` attributes.

This technique allows you to:

 * Put config near where it's used for improved readability and maintainability.
 * Attach config to objects instead of URL's. This allows multiple URL's to
   point to the same object, yet you only need to define the config once.
 * Provide defaults which are still overridable in a config file.

.. _namespaces:

Namespaces
==========

Because config entries usually just set attributes on objects, they're almost
all of the form: ``object.attribute``. A few are of the form:
``object.subobject.attribute``. They look like normal Python attribute chains,
because they work like them. We call the first name in the chain the
*"config namespace"*. When you provide a config entry, it is bound as early
as possible to the actual object referenced by the namespace; for example,
the entry ``response.stream`` actually sets the ``stream`` attribute of
:class:`cherrypy.response <cherrypy._cprequest.Response>`! In this way,
you can easily determine the default value by firing up a python interpreter
and typing::

    >>> import cherrypy
    >>> cherrypy.response.stream
    False

Each config namespace has its own handler; for example, the "request" namespace
has a handler which takes your config entry and sets that value on the
appropriate "request" attribute. There are a few namespaces, however, which
don't work like normal attributes behind the scenes; however, they still use
dotted keys and are considered to "have a namespace".

Builtin namespaces
------------------

Entries from each namespace may be allowed in the global, application root
(``"/"``) or per-path config, or a combination:

==========  ======  ==================  =========
Scope       Global  Application Root    App Path
----------  ------  ------------------  ---------
engine      X
hooks       X       X                   X
log         X       X
request     X       X                   X
response    X       X                   X
server      X
tools       X       X                   X
==========  ======  ==================  =========

engine
^^^^^^
Entries in this namespace controls the 'application engine'. These can only be
declared in the global config. Any attribute of
:class:`cherrypy.engine<cherrypy.process.wspbus.Bus>` may be set
in config; however, there are a few extra entries available in config:

 * Plugin attributes. Many of the :ref:`Engine Plugins<plugins>` are themselves
   attributes of ``cherrypy.engine``. You can set any attribute of an attached
   plugin by simply naming it. For example, there is an instance of the
   :class:`Autoreloader<cherrypy.process.plugins.Autoreloader>` class at
   ``engine.autoreload``; you can set its "frequency" attribute via the config
   entry ``engine.autoreload.frequency = 60``. In addition, you can turn such
   plugins on and off by setting ``engine.autoreload.on = True`` or ``False``.
 * ``engine.SIGHUP/SIGTERM``: These entries can be used to set the list of
   listeners for the given :ref:`channel<channels>`. Mostly, this is used
   to turn off the signal handling one gets automatically via
   :func:`cherrypy.quickstart`.

hooks
^^^^^

Declares additional request-processing functions. Use this to append your own
:class:`Hook<cherrypy._cprequest.Hook>` functions to the request. For example,
to add ``my_hook_func`` to the ``before_handler`` hookpoint::

    [/]
    hooks.before_handler = myapp.my_hook_func

log
^^^

Configures logging. These can only be declared in the global config (for global
logging) or ``[/]`` config (for each application).
See :class:`LogManager<cherrypy._cplogging.LogManager>` for the list of
configurable attributes. Typically, the "access_file", "error_file", and
"screen" attributes are the most commonly configured.

request
^^^^^^^

Sets attributes on each Request. See the
:class:`Request<cherrypy._cprequest.Request>` class for a complete list.

response
^^^^^^^^

Sets attributes on each Response. See the
:class:`Response<cherrypy._cprequest.Response>` class for a complete list.

server
^^^^^^
Controls the default HTTP server via
:class:`cherrypy.server<cherrypy._cpserver.Server>` (see that class for a
complete list of configurable attributes). These can only be
declared in the global config.

tools
^^^^^

Enables and configures additional request-processing packages. See the
:doc:`/concepts/tools` overview for more information.

wsgi
^^^^

Adds WSGI middleware to an Application's "pipeline". These can only be
declared in the app's root config ("/").

 * ``wsgi.pipeline``: Appends to the WSGi pipeline. The value must be a list of
   (name, app factory) pairs. Each app factory must be a WSGI callable class
   (or callable that returns a WSGI callable); it must take an initial
   'nextapp' argument, plus any optional keyword arguments. The optional
   arguments may be configured via ``wsgi.<name>.<arg>``.
 * ``wsgi.response_class``: Overrides the default
   :class:`Response<cherrypy._cprequest.Response>` class.

checker
^^^^^^^

Controls the "checker", which looks for common errors in app state (including
config) when the engine starts. You can turn off individual checks by setting
them to ``False`` in config. See :class:`cherrypy._cpchecker.Checker` for a
complete list. Global config only.


Custom config namespaces
------------------------

You can define your own namespaces if you like, and they can do far more than
simply set attributes. The ``test/test_config`` module, for example, shows an
example of a custom namespace that coerces incoming params and outgoing body
content. The :mod:`cherrypy._cpwsgi` module includes an additional, builtin
namespace for invoking WSGI middleware.

In essence, a config namespace handler is just a function, that gets passed
any config entries in its namespace. You add it to a namespaces registry
(a dict), where keys are namespace names and values are handler functions.
When a config entry for your namespace is encountered, the corresponding
handler function will be called, passing the config key and value; that is,
``namespaces[namespace](k, v)``. For example, if you write::

    def db_namespace(k, v):
        if k == 'connstring':
            orm.connect(v)
    cherrypy.config.namespaces['db'] = db_namespace

then ``cherrypy.config.update({"db.connstring": "Oracle:host=1.10.100.200;sid=TEST"})``
will call ``db_namespace('connstring', 'Oracle:host=1.10.100.200;sid=TEST')``.

The point at which your namespace handler is called depends on where you add it:

===========  =============================================================================  ===================================
Scope        Namespace dict                                                                 Handler is called in  
-----------  -----------------------------------------------------------------------------  -----------------------------------
Global       :attr:`cherrypy.config.namespaces <cherrypy._cpconfig.Config.namespaces>`      cherrypy.config.update
Application  :attr:`app.namespaces <cherrypy._cptree.Application.namespaces>`               Application.merge (which is called by cherrypy.tree.mount)
Request      :attr:`app.request_class.namespaces <cherrypy._cprequest.Request.namespaces>`  Request.configure (called for each request, after the handler is looked up)
===========  =============================================================================  ===================================

The name can be any string, and the handler must be either a callable or a
(Python 2.5 style) context manager.

If you need additional code to run when all your namespace keys are collected,
you can supply a callable context manager in place of a normal function for
the handler. Context managers are defined in :pep:`343`.

.. _environments:

Environments
============

The only key that does not exist in a namespace is the *"environment"* entry.
This special entry *imports* other config entries from a template stored in
``cherrypy._cpconfig.environments[environment]``. It only applies to the
global config, and only when you use
:func:`cherrypy.config.update <cherrypy._cpconfig.Config.update>`.

If you find the set of existing environments (production, staging, etc) too
limiting or just plain wrong, feel free to extend them or add new environments::

    cherrypy._cpconfig.environments['staging']['log.screen'] = False

    cherrypy._cpconfig.environments['Greek'] = {
        'tools.encode.encoding': 'ISO-8859-7',
        'tools.decode.encoding': 'ISO-8859-7',
        }
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.