plone.caching


Nameplone.caching JSON
Version 2.0.1 PyPI version JSON
download
home_pagehttps://pypi.org/project/plone.caching
SummaryZope 2 integration for z3c.caching
upload_time2023-10-06 22:45:42
maintainer
docs_urlNone
authorPlone Foundation
requires_python>=3.8
licenseGPL
keywords plone http caching
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            .. contents:: Table of Contents


Introduction
------------

The ``plone.caching`` package provides a framework for the management of cache headers, built
atop `z3c.caching`_. It consists of the following elements:

* An interface ``ICachingOperation``, describing components which:
    * Modify the response for caching purposes. The most common operation will
      be to set cache headers.
    * Intercept a request before view rendering (but after traversal and
      authorisation) to provide a cached response. The most common operation
      will be to set a "304 Not Modified" response header and return an empty
      response, although it is also possible to provide a full response body.

  Caching operations are named multi-adapters on the published object (e.g. a
  view) and the request.

* An interfaces ``ICachingOperationType`` which is used for utilities
  describing caching operations. This is mainly for UI purposes, although this
  package does not provide any UI of its own.

* Hooks into the Zope 2 ZPublisher (installed provided ZPublisher is
  available) which will execute caching operations as appropriate.

* Helper functions for looking up configuration options caching operations in
  a registry managed by `plone.registry`_

* An operation called ``plone.caching.operations.chain``, which can be used to
  chain together multiple operations. It will look up the option
  ``plone.caching.operations.chain.${rulename}.operations`` in the
  registry, expecting a list of strings indicating the names of operations to
  execute. (${rulename} refers to the name of the caching rule set in use -
  more on this later).


Usage
-----

To use ``plone.caching``, you must first install it into your build and load
its configuration. If you are using Plone, you can do that by installing
`plone.app.caching`_. Otherwise, depend on ``plone.caching`` in your
own package's ``setup.py``::

    install_requires = [
        ...
        'plone.caching',
        ]

Then load the package's configuration from your own package's
``configure.zcml``::

    <include package="plone.caching" />

Next, you must ensure that the the cache settings records are installed in
the registry. (``plone.caching`` uses ``plone.registry`` to store various
settings, and provides helpers for caching operations to do the same.)

To use the registry, you must register a (usually local) utility providing
``plone.registry.interfaces.IRegistry``. If you are using Plone, installing
``plone.app.registry`` will do this for you. Otherwise, configure one manually
using the ``zope.component`` API.

In tests, you can do the following::

    from zope.component import provideAdapter
    from plone.registry.interfaces import IRegistry
    from plone.registry import Registry

    provideAdapter(Registry(), IRegistry)

Next, you must add the ``plone.caching`` settings to the registry. If you use
`plone.app.caching`_, it will do this for you. Otherwise, you can register
them like so::

    from zope.component import getUtility
    from plone.registry.interfaces import IRegistry
    from plone.caching.interfaces import ICacheSettings

    registry = getUtility(IRegistry)
    registry.registerInterface(ICacheSettings)

Finally, you must turn on the caching engine, by setting the registry value
``plone.caching.interfaces.ICacheSettings.enabled`` to ``True``.
If you are using Plone and have installed `plone.app.caching`_, you can do
this from the caching control panel. In code, you can do::

    registry['plone.caching.interfaces.ICacheSettings.enabled'] = True


Declaring cache rules for a view
--------------------------------

The entry point for caching is a *cache rule set*. A rule set is simply a name
given to a collection of publishable resources, such as views, for caching
purposes. Take a look at `z3c.caching`_ for details, but a simple example may
look like this::

    <configure
        xmlns="http://namespaces.zope.org/zope"
        xmlns:browser="http://namespaces.zope.org/browser"
        xmlns:cache="http://namespaces.zope.org/cache">

        <cache:ruleset
            for=".frontpage.FrontpageView"
            ruleset="plone.contentTypes"
            />

        <browser:page
            for="..interfaces.IFrontpage"
            class=".frontpage.FrontpageView"
            name="frontpage_view"
            template="templates/frontpage_view.pt"
            permission="zope2.View"
            />

    </configure>

Here, the view implemented by the class ``FrontpageView`` is associated with
the rule set ``plone.contentTypes``.

**NOTE:** Ruleset names should be *dotted names*. That is, they should consist
only of upper or lowercase letters, digits, underscores and/or periods (dots).
The idea is that this forms a namespace similar to namespaces created by
packages and modules in Python.

Elsewhere (or in the same file) the ``plone.contentTypes`` ruleset should be
declared with a title and description. This is can be used by a UI such as
that provided by `plone.app.caching`_. If "explicit" mode is set in
``z3c.caching``, this is required. By default it is optional::

        <cache:rulesetType
            name="plone.contentTypes"
            title="Plone content types"
            description="Non-container content types"
            />

Hints:

* Try to reuse existing rule sets rather than invent your own.
* Rule sets inherit according to the same rules as those that apply to
  adapters. Thus, you can register a generic rule set for a generic interface
  or base class, and then override it for a more specific class or interface.
* If you need to modify rule sets declared by packages not under your control,
  you can use an ``overrides.zcml`` file for your project.


Mapping cache rules to operations
---------------------------------

``plone.caching`` maintains a mapping of rule sets to caching operations in
the registry. This mapping is stored in a dictionary of dotted name string
keys to dotted name string values, under the record
``plone.caching.interfaces.ICacheSettings.operationMapping``.

To set the name of the operation to use for the ``plone.contentTypes`` rule
shown above, a mapping like the following might be used::

    from zope.component import getUtility
    from plone.registry.interfaces import IRegistry
    from plone.caching.interfaces import ICacheSettings

    registry = getUtility(IRegistry)
    settings = registry.forInterface(ICacheSettings)
    if settings.operationMapping is None: # initialise if not set already
        settings.operationMapping = {}
    settings.operationMapping['plone.contentTypes'] = 'my.package.operation'

Here, ``my.package.operation`` is the name of a caching operation. We will
see an example of using one shortly.

If you want to use several operations, you can chain them together using the
``plone.caching.operations.chain`` operation::

    settings.operationMapping['plone.contentTypes'] = 'plone.caching.operations.chain'

    registry['plone.caching.operations.chain.plone.contentTypes.operations'] = \
        ['my.package.operation1', 'my.package.operation2']

The last line here is setting the ``operations`` option for the chain
operation, in a way that is specific to the ``plone.contentTypes`` rule set.
More on the configuration syntax shortly.

If you need to list all operations for UI purposes, you can look up
the registered instances of the ``ICachingOperationType`` utility::

    from zope.component import getUtilitiesFor
    from plone.caching.interfaces import ICachingOperationType

    for name, type_ in getUtilitiesFor(ICachingOperationType):
        ...

The ``ICachingOperationType`` utility provides properties like ``title`` and
``description`` to help build a user interface around caching operations.
`plone.app.caching`_ provides just such an interface.


Setting options for caching operations
--------------------------------------

``plone.caching`` does not strictly enforce how caching operations configure
themselves, if at all. However, it provides helper functionality to encourage
a pattern based on settings stored in ``plone.registry``. We have already seen
this pattern in use for the chain operation above. Let's now take a closer
look.

The chain operation is implemented by the class
``plone.caching.operations.Chain``. The ``ICachingOperationType`` utility
named ``plone.caching.operations.chain`` provides two attributes in addition
to the ``title`` and ``description`` attributes mentioned above:

prefix
    A dotted name prefix used for all registry keys. This key must be unique.
    By convention, it is the name of the caching operation
options
    A tuple of option names

Taken together, these attributes describe the configurable options (if any)
of the caching operation. By default, the two are concatenated, so that if
you have an operation called ``my.package.operation``, the prefix is the same
string, and the options are ``('option1', 'option2')``, two registry keys
will be used: ``my.package.operation.option1`` and
``my.package.operation.option2``. (The type of those records and their value
will obviously depend on how the registry is configured. Typically, the
installation routine for a given operation will create them with sensible
defaults).

If you need to change these settings on a per-cache-rule basis, you can do
so by inserting the cache rule name between the prefix and the option name.
For example, for the cache rule ``my.rule``, the rule-specific version of
``option1`` would be ``my.package.operation.my.rule.option1``.

In this case, you probably want to use a field reference (``FieldRef``) for
the "override" record that references the field of the "base" record. See
the `plone.registry`_ documentation for details.

Finally, note that it is generally safe to use caching operations if their
registry keys are not installed. That is, they should fall back on sensible
defaults and not crash.


Writing caching operations
--------------------------

Now that we have seen how to configure cache rules and operations, let's look
at how we can write our own caching operations

Caching operations consist of two components:

* A named multi-adapter implementing the operation itself
* A named utility providing metadata about the operation

Typically, both of these are implemented within a single class, although this
is not a requirement. Typically, the operation will also look up options in
accordance with the configuration methodology outlines above.

Here is an example of an operation that sets a fixed max-age cache control
header. It is registered for any published resource, and for any HTTP request
(but not other types of request.)::

    from plone.caching.interfaces import _
    from plone.caching.interfaces import ICachingOperation
    from plone.caching.interfaces import ICachingOperationType
    from plone.caching.utils import lookupOptions
    from zope.component import adapter
    from zope.component import queryMultiAdapter
    from zope.interface import implementer
    from zope.interface import Interface
    from zope.interface import provider
    from zope.publisher.interfaces.http import IHTTPRequest


    @implementer(ICachingOperation)
    @adapter(Interface, IHTTPRequest)
    @provider(ICachingOperationType)
    class MaxAge(object):

        # Type metadata
        title = _(u"Max age")
        description = _(u"Sets a fixed max age value")
        prefix = 'plone.caching.tests.maxage'
        options = ('maxAge',)

        def __init__(self, published, request):
            self.published = published
            self.request = request

        def interceptResponse(self, rulename, response):
            return None

        def modifyResponse(self, rulename, response):
            options = lookupOptions(MaxAge, rulename)
            maxAge = options['maxAge'] or 3600
            response.setHeader('Cache-Control', 'max-age=%s, must-revalidate' % maxAge)

There are two methods here:

* ``interceptResponse()`` is called before Zope attempts to render the
  published object. If this returns None, publication continues as normal. If
  it returns a string, the request is intercepted and the cached response is
  returned.
* ``modifyResponse()`` is called after Zope has rendered the response (in a
  late stage of the transformation chain set up by `plone.transformchain`_).
  This should not return a value, but can modify the response passed in. It
  should not modify the response body (in fact, doing so will have on effect),
  but may set headers.

Note the use of the ``lookupOptions()`` helper method. You can pass this
either an ``ICachingOperationType`` instance, or the name of one (in which
case it will be looked up from the utility registry), as well as the current
rule name. It will return a dictionary of all the options listed (only
``maxAge`` in this case), taking rule set overrides into account. The
options are guaranteed to be there, but will fall back on a default of
``None`` if not set.

To register this component in ZCML, we would do::

    <adapter factory=".maxage.MaxAge" name="plone.caching.tests.maxage" />
    <utility component=".maxage.MaxAge" name="plone.caching.tests.maxage" />

Note that by using ``component`` instead of ``factory`` in the ``<utility />``
declaration, we register the class object itself as the utility. The
attributes are provided as class variables for that reason - setting them in
``__init__()``, for example, would not work.

What about the ``interceptResponse()`` method? Here is a simple example that
sends a 304 not modified response always. (This is probably not very useful,
but it serves as an example.)::

    from plone.caching.interfaces import _
    from plone.caching.interfaces import ICachingOperation
    from plone.caching.interfaces import ICachingOperationType
    from plone.caching.utils import lookupOptions
    from zope.component import adapter
    from zope.component import queryMultiAdapter
    from zope.interface import implementer
    from zope.interface import Interface
    from zope.interface import provider
    from zope.publisher.interfaces.http import IHTTPRequest


    @implementer(ICachingOperation)
    @adapter(Interface, IHTTPRequest)
    @provider(ICachingOperationType)
    class Always304(object):

        # Type metadata
        title = _(u"Always send 304")
        description = _(u"It's not modified, dammit!")
        prefix = 'plone.caching.tests.always304'
        options = ('temporarilyDisable',)

        def __init__(self, published, request):
            self.published = published
            self.request = request

        def interceptResponse(self, rulename, response):
            options = lookupOptions(self.__class__, rulename)
            if options['temporarilyDisable']:
                return None

            response.setStatus(304)
            return u""

        def modifyResponse(self, rulename, response):
            pass

Here, we return ``None`` to indicate that the request should not be
intercepted if the ``temporarilyDisable`` option is set to ``True``.
Otherwise, we modify the response and return a response body. The return value
must be a unicode string. In this case, an empty string will suffice.

The ZCML registration would look like this::

    <adapter factory=".always.Always304" name="plone.caching.tests.always304" />
    <utility component=".always.Always304" name="plone.caching.tests.always304" />

.. _z3c.caching: http://pypi.python.org/pypi/z3c.caching
.. _plone.registry: http://pypi.python.org/pypi/plone.registry
.. _plone.app.caching: http://pypi.python.org/pypi/plone.app.caching
.. _plone.transformchain: http://pypi.python.org/pypi/plone.transformchain

Changelog
=========

.. You should *NOT* be adding new change log entries to this file.
   You should create a file in the news directory instead.
   For helpful instructions, please see:
   https://github.com/plone/plone.releaser/blob/master/ADD-A-NEWS-ITEM.rst

.. towncrier release notes start

2.0.1 (2023-10-07)
------------------

Internal:


- Update configuration files.
  [plone devs] (cfffba8c)


2.0.0 (2023-04-15)
------------------

Breaking changes:


- Drop python 2 support.
  [gforcada] (#1)


Internal:


- Update configuration files.
  [plone devs] (3b8337e6)


1.2.2 (2020-04-20)
------------------

Bug fixes:


- Minor packaging updates. (#1)


1.2.1 (2018-11-29)
------------------

Bug fixes:

- Remove five.globalrequest usage.
  [gforcada]

1.2.0 (2018-09-28)
------------------

New features:

- Add support for Python 3.
  [pbauer]

Bug fixes:

- Fix caching and tests in python 3
  [ale-rt, pbauer]


1.1.2 (2016-09-16)
------------------

Bug fixes:

- Cleanup: isort, readability, pep8, utf8-headers.
  [jensens]


1.1.1 (2016-08-12)
------------------

Bug fixes:

- Use zope.interface decorator.
  [gforcada]


1.1.0 (2016-05-18)
------------------

Fixes:

- Use plone i18n domain.  [klinger]


1.0.1 (2015-03-21)
------------------

- Fix ruleset registry test isolation so that is no longer order dependent.
  [jone]


1.0 - 2011-05-13
----------------

- Release 1.0 Final.
  [esteele]

- Add MANIFEST.in.
  [WouterVH]


1.0b2 - 2011-02-10
------------------

- Updated tests to reflect operation parameter overrides can now use
  plone.registry FieldRefs. Requires plone.registry >= 1.0b3.
  [optilude]

- Removed monkey patches unneeded since Zope 2.12.4.
  [optilude]


1.0b1 - 2010-08-04
------------------

- Preparing release to coincide with plone.app.caching 1.0b1
  [optilude]


1.0a1 - 2010-04-22
------------------

- Initial release
  [optilude, newbery]

            

Raw data

            {
    "_id": null,
    "home_page": "https://pypi.org/project/plone.caching",
    "name": "plone.caching",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "plone http caching",
    "author": "Plone Foundation",
    "author_email": "plone-developers@lists.sourceforge.net",
    "download_url": "https://files.pythonhosted.org/packages/6b/33/430b128b194310baafabf31e4730e9e16b87b468fc34c13e1222216f4fbd/plone.caching-2.0.1.tar.gz",
    "platform": null,
    "description": ".. contents:: Table of Contents\n\n\nIntroduction\n------------\n\nThe ``plone.caching`` package provides a framework for the management of cache headers, built\natop `z3c.caching`_. It consists of the following elements:\n\n* An interface ``ICachingOperation``, describing components which:\n    * Modify the response for caching purposes. The most common operation will\n      be to set cache headers.\n    * Intercept a request before view rendering (but after traversal and\n      authorisation) to provide a cached response. The most common operation\n      will be to set a \"304 Not Modified\" response header and return an empty\n      response, although it is also possible to provide a full response body.\n\n  Caching operations are named multi-adapters on the published object (e.g. a\n  view) and the request.\n\n* An interfaces ``ICachingOperationType`` which is used for utilities\n  describing caching operations. This is mainly for UI purposes, although this\n  package does not provide any UI of its own.\n\n* Hooks into the Zope 2 ZPublisher (installed provided ZPublisher is\n  available) which will execute caching operations as appropriate.\n\n* Helper functions for looking up configuration options caching operations in\n  a registry managed by `plone.registry`_\n\n* An operation called ``plone.caching.operations.chain``, which can be used to\n  chain together multiple operations. It will look up the option\n  ``plone.caching.operations.chain.${rulename}.operations`` in the\n  registry, expecting a list of strings indicating the names of operations to\n  execute. (${rulename} refers to the name of the caching rule set in use -\n  more on this later).\n\n\nUsage\n-----\n\nTo use ``plone.caching``, you must first install it into your build and load\nits configuration. If you are using Plone, you can do that by installing\n`plone.app.caching`_. Otherwise, depend on ``plone.caching`` in your\nown package's ``setup.py``::\n\n    install_requires = [\n        ...\n        'plone.caching',\n        ]\n\nThen load the package's configuration from your own package's\n``configure.zcml``::\n\n    <include package=\"plone.caching\" />\n\nNext, you must ensure that the the cache settings records are installed in\nthe registry. (``plone.caching`` uses ``plone.registry`` to store various\nsettings, and provides helpers for caching operations to do the same.)\n\nTo use the registry, you must register a (usually local) utility providing\n``plone.registry.interfaces.IRegistry``. If you are using Plone, installing\n``plone.app.registry`` will do this for you. Otherwise, configure one manually\nusing the ``zope.component`` API.\n\nIn tests, you can do the following::\n\n    from zope.component import provideAdapter\n    from plone.registry.interfaces import IRegistry\n    from plone.registry import Registry\n\n    provideAdapter(Registry(), IRegistry)\n\nNext, you must add the ``plone.caching`` settings to the registry. If you use\n`plone.app.caching`_, it will do this for you. Otherwise, you can register\nthem like so::\n\n    from zope.component import getUtility\n    from plone.registry.interfaces import IRegistry\n    from plone.caching.interfaces import ICacheSettings\n\n    registry = getUtility(IRegistry)\n    registry.registerInterface(ICacheSettings)\n\nFinally, you must turn on the caching engine, by setting the registry value\n``plone.caching.interfaces.ICacheSettings.enabled`` to ``True``.\nIf you are using Plone and have installed `plone.app.caching`_, you can do\nthis from the caching control panel. In code, you can do::\n\n    registry['plone.caching.interfaces.ICacheSettings.enabled'] = True\n\n\nDeclaring cache rules for a view\n--------------------------------\n\nThe entry point for caching is a *cache rule set*. A rule set is simply a name\ngiven to a collection of publishable resources, such as views, for caching\npurposes. Take a look at `z3c.caching`_ for details, but a simple example may\nlook like this::\n\n    <configure\n        xmlns=\"http://namespaces.zope.org/zope\"\n        xmlns:browser=\"http://namespaces.zope.org/browser\"\n        xmlns:cache=\"http://namespaces.zope.org/cache\">\n\n        <cache:ruleset\n            for=\".frontpage.FrontpageView\"\n            ruleset=\"plone.contentTypes\"\n            />\n\n        <browser:page\n            for=\"..interfaces.IFrontpage\"\n            class=\".frontpage.FrontpageView\"\n            name=\"frontpage_view\"\n            template=\"templates/frontpage_view.pt\"\n            permission=\"zope2.View\"\n            />\n\n    </configure>\n\nHere, the view implemented by the class ``FrontpageView`` is associated with\nthe rule set ``plone.contentTypes``.\n\n**NOTE:** Ruleset names should be *dotted names*. That is, they should consist\nonly of upper or lowercase letters, digits, underscores and/or periods (dots).\nThe idea is that this forms a namespace similar to namespaces created by\npackages and modules in Python.\n\nElsewhere (or in the same file) the ``plone.contentTypes`` ruleset should be\ndeclared with a title and description. This is can be used by a UI such as\nthat provided by `plone.app.caching`_. If \"explicit\" mode is set in\n``z3c.caching``, this is required. By default it is optional::\n\n        <cache:rulesetType\n            name=\"plone.contentTypes\"\n            title=\"Plone content types\"\n            description=\"Non-container content types\"\n            />\n\nHints:\n\n* Try to reuse existing rule sets rather than invent your own.\n* Rule sets inherit according to the same rules as those that apply to\n  adapters. Thus, you can register a generic rule set for a generic interface\n  or base class, and then override it for a more specific class or interface.\n* If you need to modify rule sets declared by packages not under your control,\n  you can use an ``overrides.zcml`` file for your project.\n\n\nMapping cache rules to operations\n---------------------------------\n\n``plone.caching`` maintains a mapping of rule sets to caching operations in\nthe registry. This mapping is stored in a dictionary of dotted name string\nkeys to dotted name string values, under the record\n``plone.caching.interfaces.ICacheSettings.operationMapping``.\n\nTo set the name of the operation to use for the ``plone.contentTypes`` rule\nshown above, a mapping like the following might be used::\n\n    from zope.component import getUtility\n    from plone.registry.interfaces import IRegistry\n    from plone.caching.interfaces import ICacheSettings\n\n    registry = getUtility(IRegistry)\n    settings = registry.forInterface(ICacheSettings)\n    if settings.operationMapping is None: # initialise if not set already\n        settings.operationMapping = {}\n    settings.operationMapping['plone.contentTypes'] = 'my.package.operation'\n\nHere, ``my.package.operation`` is the name of a caching operation. We will\nsee an example of using one shortly.\n\nIf you want to use several operations, you can chain them together using the\n``plone.caching.operations.chain`` operation::\n\n    settings.operationMapping['plone.contentTypes'] = 'plone.caching.operations.chain'\n\n    registry['plone.caching.operations.chain.plone.contentTypes.operations'] = \\\n        ['my.package.operation1', 'my.package.operation2']\n\nThe last line here is setting the ``operations`` option for the chain\noperation, in a way that is specific to the ``plone.contentTypes`` rule set.\nMore on the configuration syntax shortly.\n\nIf you need to list all operations for UI purposes, you can look up\nthe registered instances of the ``ICachingOperationType`` utility::\n\n    from zope.component import getUtilitiesFor\n    from plone.caching.interfaces import ICachingOperationType\n\n    for name, type_ in getUtilitiesFor(ICachingOperationType):\n        ...\n\nThe ``ICachingOperationType`` utility provides properties like ``title`` and\n``description`` to help build a user interface around caching operations.\n`plone.app.caching`_ provides just such an interface.\n\n\nSetting options for caching operations\n--------------------------------------\n\n``plone.caching`` does not strictly enforce how caching operations configure\nthemselves, if at all. However, it provides helper functionality to encourage\na pattern based on settings stored in ``plone.registry``. We have already seen\nthis pattern in use for the chain operation above. Let's now take a closer\nlook.\n\nThe chain operation is implemented by the class\n``plone.caching.operations.Chain``. The ``ICachingOperationType`` utility\nnamed ``plone.caching.operations.chain`` provides two attributes in addition\nto the ``title`` and ``description`` attributes mentioned above:\n\nprefix\n    A dotted name prefix used for all registry keys. This key must be unique.\n    By convention, it is the name of the caching operation\noptions\n    A tuple of option names\n\nTaken together, these attributes describe the configurable options (if any)\nof the caching operation. By default, the two are concatenated, so that if\nyou have an operation called ``my.package.operation``, the prefix is the same\nstring, and the options are ``('option1', 'option2')``, two registry keys\nwill be used: ``my.package.operation.option1`` and\n``my.package.operation.option2``. (The type of those records and their value\nwill obviously depend on how the registry is configured. Typically, the\ninstallation routine for a given operation will create them with sensible\ndefaults).\n\nIf you need to change these settings on a per-cache-rule basis, you can do\nso by inserting the cache rule name between the prefix and the option name.\nFor example, for the cache rule ``my.rule``, the rule-specific version of\n``option1`` would be ``my.package.operation.my.rule.option1``.\n\nIn this case, you probably want to use a field reference (``FieldRef``) for\nthe \"override\" record that references the field of the \"base\" record. See\nthe `plone.registry`_ documentation for details.\n\nFinally, note that it is generally safe to use caching operations if their\nregistry keys are not installed. That is, they should fall back on sensible\ndefaults and not crash.\n\n\nWriting caching operations\n--------------------------\n\nNow that we have seen how to configure cache rules and operations, let's look\nat how we can write our own caching operations\n\nCaching operations consist of two components:\n\n* A named multi-adapter implementing the operation itself\n* A named utility providing metadata about the operation\n\nTypically, both of these are implemented within a single class, although this\nis not a requirement. Typically, the operation will also look up options in\naccordance with the configuration methodology outlines above.\n\nHere is an example of an operation that sets a fixed max-age cache control\nheader. It is registered for any published resource, and for any HTTP request\n(but not other types of request.)::\n\n    from plone.caching.interfaces import _\n    from plone.caching.interfaces import ICachingOperation\n    from plone.caching.interfaces import ICachingOperationType\n    from plone.caching.utils import lookupOptions\n    from zope.component import adapter\n    from zope.component import queryMultiAdapter\n    from zope.interface import implementer\n    from zope.interface import Interface\n    from zope.interface import provider\n    from zope.publisher.interfaces.http import IHTTPRequest\n\n\n    @implementer(ICachingOperation)\n    @adapter(Interface, IHTTPRequest)\n    @provider(ICachingOperationType)\n    class MaxAge(object):\n\n        # Type metadata\n        title = _(u\"Max age\")\n        description = _(u\"Sets a fixed max age value\")\n        prefix = 'plone.caching.tests.maxage'\n        options = ('maxAge',)\n\n        def __init__(self, published, request):\n            self.published = published\n            self.request = request\n\n        def interceptResponse(self, rulename, response):\n            return None\n\n        def modifyResponse(self, rulename, response):\n            options = lookupOptions(MaxAge, rulename)\n            maxAge = options['maxAge'] or 3600\n            response.setHeader('Cache-Control', 'max-age=%s, must-revalidate' % maxAge)\n\nThere are two methods here:\n\n* ``interceptResponse()`` is called before Zope attempts to render the\n  published object. If this returns None, publication continues as normal. If\n  it returns a string, the request is intercepted and the cached response is\n  returned.\n* ``modifyResponse()`` is called after Zope has rendered the response (in a\n  late stage of the transformation chain set up by `plone.transformchain`_).\n  This should not return a value, but can modify the response passed in. It\n  should not modify the response body (in fact, doing so will have on effect),\n  but may set headers.\n\nNote the use of the ``lookupOptions()`` helper method. You can pass this\neither an ``ICachingOperationType`` instance, or the name of one (in which\ncase it will be looked up from the utility registry), as well as the current\nrule name. It will return a dictionary of all the options listed (only\n``maxAge`` in this case), taking rule set overrides into account. The\noptions are guaranteed to be there, but will fall back on a default of\n``None`` if not set.\n\nTo register this component in ZCML, we would do::\n\n    <adapter factory=\".maxage.MaxAge\" name=\"plone.caching.tests.maxage\" />\n    <utility component=\".maxage.MaxAge\" name=\"plone.caching.tests.maxage\" />\n\nNote that by using ``component`` instead of ``factory`` in the ``<utility />``\ndeclaration, we register the class object itself as the utility. The\nattributes are provided as class variables for that reason - setting them in\n``__init__()``, for example, would not work.\n\nWhat about the ``interceptResponse()`` method? Here is a simple example that\nsends a 304 not modified response always. (This is probably not very useful,\nbut it serves as an example.)::\n\n    from plone.caching.interfaces import _\n    from plone.caching.interfaces import ICachingOperation\n    from plone.caching.interfaces import ICachingOperationType\n    from plone.caching.utils import lookupOptions\n    from zope.component import adapter\n    from zope.component import queryMultiAdapter\n    from zope.interface import implementer\n    from zope.interface import Interface\n    from zope.interface import provider\n    from zope.publisher.interfaces.http import IHTTPRequest\n\n\n    @implementer(ICachingOperation)\n    @adapter(Interface, IHTTPRequest)\n    @provider(ICachingOperationType)\n    class Always304(object):\n\n        # Type metadata\n        title = _(u\"Always send 304\")\n        description = _(u\"It's not modified, dammit!\")\n        prefix = 'plone.caching.tests.always304'\n        options = ('temporarilyDisable',)\n\n        def __init__(self, published, request):\n            self.published = published\n            self.request = request\n\n        def interceptResponse(self, rulename, response):\n            options = lookupOptions(self.__class__, rulename)\n            if options['temporarilyDisable']:\n                return None\n\n            response.setStatus(304)\n            return u\"\"\n\n        def modifyResponse(self, rulename, response):\n            pass\n\nHere, we return ``None`` to indicate that the request should not be\nintercepted if the ``temporarilyDisable`` option is set to ``True``.\nOtherwise, we modify the response and return a response body. The return value\nmust be a unicode string. In this case, an empty string will suffice.\n\nThe ZCML registration would look like this::\n\n    <adapter factory=\".always.Always304\" name=\"plone.caching.tests.always304\" />\n    <utility component=\".always.Always304\" name=\"plone.caching.tests.always304\" />\n\n.. _z3c.caching: http://pypi.python.org/pypi/z3c.caching\n.. _plone.registry: http://pypi.python.org/pypi/plone.registry\n.. _plone.app.caching: http://pypi.python.org/pypi/plone.app.caching\n.. _plone.transformchain: http://pypi.python.org/pypi/plone.transformchain\n\nChangelog\n=========\n\n.. You should *NOT* be adding new change log entries to this file.\n   You should create a file in the news directory instead.\n   For helpful instructions, please see:\n   https://github.com/plone/plone.releaser/blob/master/ADD-A-NEWS-ITEM.rst\n\n.. towncrier release notes start\n\n2.0.1 (2023-10-07)\n------------------\n\nInternal:\n\n\n- Update configuration files.\n  [plone devs] (cfffba8c)\n\n\n2.0.0 (2023-04-15)\n------------------\n\nBreaking changes:\n\n\n- Drop python 2 support.\n  [gforcada] (#1)\n\n\nInternal:\n\n\n- Update configuration files.\n  [plone devs] (3b8337e6)\n\n\n1.2.2 (2020-04-20)\n------------------\n\nBug fixes:\n\n\n- Minor packaging updates. (#1)\n\n\n1.2.1 (2018-11-29)\n------------------\n\nBug fixes:\n\n- Remove five.globalrequest usage.\n  [gforcada]\n\n1.2.0 (2018-09-28)\n------------------\n\nNew features:\n\n- Add support for Python 3.\n  [pbauer]\n\nBug fixes:\n\n- Fix caching and tests in python 3\n  [ale-rt, pbauer]\n\n\n1.1.2 (2016-09-16)\n------------------\n\nBug fixes:\n\n- Cleanup: isort, readability, pep8, utf8-headers.\n  [jensens]\n\n\n1.1.1 (2016-08-12)\n------------------\n\nBug fixes:\n\n- Use zope.interface decorator.\n  [gforcada]\n\n\n1.1.0 (2016-05-18)\n------------------\n\nFixes:\n\n- Use plone i18n domain.  [klinger]\n\n\n1.0.1 (2015-03-21)\n------------------\n\n- Fix ruleset registry test isolation so that is no longer order dependent.\n  [jone]\n\n\n1.0 - 2011-05-13\n----------------\n\n- Release 1.0 Final.\n  [esteele]\n\n- Add MANIFEST.in.\n  [WouterVH]\n\n\n1.0b2 - 2011-02-10\n------------------\n\n- Updated tests to reflect operation parameter overrides can now use\n  plone.registry FieldRefs. Requires plone.registry >= 1.0b3.\n  [optilude]\n\n- Removed monkey patches unneeded since Zope 2.12.4.\n  [optilude]\n\n\n1.0b1 - 2010-08-04\n------------------\n\n- Preparing release to coincide with plone.app.caching 1.0b1\n  [optilude]\n\n\n1.0a1 - 2010-04-22\n------------------\n\n- Initial release\n  [optilude, newbery]\n",
    "bugtrack_url": null,
    "license": "GPL",
    "summary": "Zope 2 integration for z3c.caching",
    "version": "2.0.1",
    "project_urls": {
        "Homepage": "https://pypi.org/project/plone.caching"
    },
    "split_keywords": [
        "plone",
        "http",
        "caching"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "bf50357769a5d3347a49500a62b0d3fd82a75acb79d80644af72f5f00d52ed61",
                "md5": "17a883e5660daf1ad2fc1dbb96ba3ef0",
                "sha256": "caba0f9aa46d11f475e4d65199681e9e47e56381f25058b0c925e59ea7f17182"
            },
            "downloads": -1,
            "filename": "plone.caching-2.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "17a883e5660daf1ad2fc1dbb96ba3ef0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 21684,
            "upload_time": "2023-10-06T22:45:41",
            "upload_time_iso_8601": "2023-10-06T22:45:41.107469Z",
            "url": "https://files.pythonhosted.org/packages/bf/50/357769a5d3347a49500a62b0d3fd82a75acb79d80644af72f5f00d52ed61/plone.caching-2.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6b33430b128b194310baafabf31e4730e9e16b87b468fc34c13e1222216f4fbd",
                "md5": "560cce85426db4b1ee673984f8728565",
                "sha256": "f4bdd1b2816f3e2257e9727a6287965898cd2f3b3cde1ee12d4fc75a93512e6f"
            },
            "downloads": -1,
            "filename": "plone.caching-2.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "560cce85426db4b1ee673984f8728565",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 30477,
            "upload_time": "2023-10-06T22:45:42",
            "upload_time_iso_8601": "2023-10-06T22:45:42.470874Z",
            "url": "https://files.pythonhosted.org/packages/6b/33/430b128b194310baafabf31e4730e9e16b87b468fc34c13e1222216f4fbd/plone.caching-2.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-06 22:45:42",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "plone.caching"
}
        
Elapsed time: 0.12105s