zope.preference


Namezope.preference JSON
Version 5.0 PyPI version JSON
download
home_pagehttp://github.com/zopefoundation/zope.preference
SummaryUser Preferences Framework
upload_time2023-02-10 09:31:35
maintainer
docs_urlNone
authorZope Foundation and Contributors
requires_python>=3.7
licenseZPL 2.1
keywords bluebream zope zope3 user preference
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            This package provides an API to create and maintain hierarchical user
preferences. Preferences can be easily created by defining schemas.


.. contents::

==================
 User Preferences
==================

Implementing user preferences is usually a painful task, since it requires a
lot of custom coding and constantly changing preferences makes it hard to
maintain the data and UI. The `preference` package

  >>> from zope.preference import preference

eases this pain by providing a generic user preferences framework that uses
schemas to categorize and describe the preferences.

Preference Groups
=================

Preferences are grouped in preference groups and the preferences inside a
group are specified via the preferences group schema:

  >>> import zope.interface
  >>> import zope.schema
  >>> class IZMIUserSettings(zope.interface.Interface):
  ...     """Basic User Preferences"""
  ...
  ...     email = zope.schema.TextLine(
  ...         title=u"E-mail Address",
  ...         description=u"E-mail Address used to send notifications")
  ...
  ...     skin = zope.schema.Choice(
  ...         title=u"Skin",
  ...         description=u"The skin that should be used for the ZMI.",
  ...         values=['Rotterdam', 'ZopeTop', 'Basic'],
  ...         default='Rotterdam')
  ...
  ...     showZopeLogo = zope.schema.Bool(
  ...         title=u"Show Zope Logo",
  ...         description=u"Specifies whether Zope logo should be displayed "
  ...                     u"at the top of the screen.",
  ...         default=True)

Now we can instantiate the preference group. Each preference group must have an
ID by which it can be accessed and optional title and description fields for UI
purposes:

  >>> settings = preference.PreferenceGroup(
  ...     "ZMISettings",
  ...     schema=IZMIUserSettings,
  ...     title=u"ZMI User Settings",
  ...     description=u"")

Note that the preferences group provides the interface it is representing:

  >>> IZMIUserSettings.providedBy(settings)
  True

and the id, schema and title of the group are directly available:

  >>> settings.__id__
  'ZMISettings'
  >>> settings.__schema__
  <InterfaceClass zope.preference.README.IZMIUserSettings>
  >>> settings.__title__
  'ZMI User Settings'

So let's ask the preference group for the `skin` setting:

  >>> settings.skin #doctest:+ELLIPSIS
  Traceback (most recent call last):
  ...
  zope.security.interfaces.NoInteraction


So why did the lookup fail? Because we have not specified a principal yet, for
which we want to lookup the preferences. To do that, we have to create a new
interaction:

  >>> class Principal:
  ...     def __init__(self, id):
  ...         self.id = id
  >>> principal = Principal('zope.user')

  >>> class Participation:
  ...     interaction = None
  ...     def __init__(self, principal):
  ...         self.principal = principal

  >>> participation = Participation(principal)

  >>> import zope.security.management
  >>> zope.security.management.newInteraction(participation)

We also need an IAnnotations adapter for principals, so we can store the
settings:

  >>> from zope.annotation.interfaces import IAnnotations
  >>> @zope.interface.implementer(IAnnotations)
  ... class PrincipalAnnotations(dict):
  ...     data = {}
  ...     def __new__(class_, principal, context):
  ...         try:
  ...             annotations = class_.data[principal.id]
  ...         except KeyError:
  ...             annotations = dict.__new__(class_)
  ...             class_.data[principal.id] = annotations
  ...         return annotations
  ...     def __init__(self, principal, context):
  ...         pass

  >>> from zope.component import provideAdapter
  >>> provideAdapter(PrincipalAnnotations,
  ...                (Principal, zope.interface.Interface), IAnnotations)

Let's now try to access the settings again:

  >>> settings.skin
  'Rotterdam'

which is the default value, since we have not set it yet. We can now reassign
the value:

  >>> settings.skin = 'Basic'
  >>> settings.skin
  'Basic'

However, you cannot just enter any value, since it is validated before the
assignment:

  >>> settings.skin = 'MySkin'
  Traceback (most recent call last):
  ...
  ConstraintNotSatisfied: MySkin


Preference Group Trees
======================

The preferences would not be very powerful, if you could create a full
preferences. So let's create a sub-group for our ZMI user settings, where we
can adjust the look and feel of the folder contents view:

  >>> class IFolderSettings(zope.interface.Interface):
  ...     """Basic User Preferences"""
  ...
  ...     shownFields = zope.schema.Set(
  ...         title=u"Shown Fields",
  ...         description=u"Fields shown in the table.",
  ...         value_type=zope.schema.Choice(['name', 'size', 'creator']),
  ...         default=set(['name', 'size']))
  ...
  ...     sortedBy = zope.schema.Choice(
  ...         title=u"Sorted By",
  ...         description=u"Data field to sort by.",
  ...         values=['name', 'size', 'creator'],
  ...         default='name')

  >>> folderSettings = preference.PreferenceGroup(
  ...     "ZMISettings.Folder",
  ...     schema=IFolderSettings,
  ...     title=u"Folder Content View Settings")

Note that the id was chosen so that the parent id is the prefix of the child's
id. Our new preference sub-group should now be available as an attribute or an
item on the parent group ...

  >>> settings.Folder
  Traceback (most recent call last):
  ...
  AttributeError: 'Folder' is not a preference or sub-group.
  >>> settings['Folder']
  Traceback (most recent call last):
  ...
  KeyError: 'Folder'

but not before we register the groups as utilities:

  >>> from zope.preference import interfaces
  >>> from zope.component import provideUtility

  >>> provideUtility(settings, interfaces.IPreferenceGroup,
  ...                name='ZMISettings')
  >>> provideUtility(folderSettings, interfaces.IPreferenceGroup,
  ...                name='ZMISettings.Folder')

If we now try to lookup the sub-group again, we should be successful:

  >>> settings.Folder #doctest:+ELLIPSIS
  <zope.preference.preference.PreferenceGroup object at ...>

  >>> settings['Folder'] #doctest:+ELLIPSIS
  <zope.preference.preference.PreferenceGroup object at ...>
  >>> 'Folder' in settings
  True
  >>> list(settings)
  [<zope.preference.preference.PreferenceGroup object at ...>]

While the registry of the preference groups is flat, the careful naming of the
ids allows us to have a tree of preferences. Note that this pattern is very
similar to the way modules are handled in Python; they are stored in a flat
dictionary in ``sys.modules``, but due to the naming they appear to be in a
namespace tree.

While we are at it, there are also preference categories that can be compared
to Python packages. They basically are just a higher level grouping concept
that is used by the UI to better organize the preferences. A preference group
can be converted to a category by simply providing an additional interface:

  >>> zope.interface.alsoProvides(folderSettings, interfaces.IPreferenceCategory)

  >>> interfaces.IPreferenceCategory.providedBy(folderSettings)
  True

Preference group objects can also hold arbitrary attributes, but since
they're not persistent this must be used with care:

  >>> settings.not_in_schema = 1
  >>> settings.not_in_schema
  1
  >>> del settings.not_in_schema
  >>> settings.not_in_schema
  Traceback (most recent call last):
  ...
  AttributeError: 'not_in_schema' is not a preference or sub-group.

Default Preferences
===================

It is sometimes desirable to define default settings on a site-by-site
basis, instead of just using the default value from the schema. The
preferences package provides a module that implements a default
preferences provider that can be added as a unnamed utility for each
site:

  >>> from zope.preference import default

We'll begin by creating a new root site:

  >>> from zope.site.folder import rootFolder
  >>> root = rootFolder()
  >>> from zope.site.site import LocalSiteManager
  >>> rsm = LocalSiteManager(root)
  >>> root.setSiteManager(rsm)

And we'll make the new site the current site:

  >>> zope.component.hooks.setSite(root)

Now we can register the default preference provider with the root site:

  >>> provider = addUtility(
  ...     rsm, default.DefaultPreferenceProvider(),
  ...     interfaces.IDefaultPreferenceProvider)

So before we set an explicit default value for a preference, the schema field
default is used:

  >>> settings.Folder.sortedBy
  'name'

But if we now set a new default value with the provider,

  >>> defaultFolder = provider.getDefaultPreferenceGroup('ZMISettings.Folder')
  >>> defaultFolder.sortedBy = 'size'

then the default of the setting changes:

  >>> settings.Folder.sortedBy
  'size'

Because the ``ZMISettings.Folder`` was declared as a preference
category, the default implementation is too:

  >>> interfaces.IPreferenceCategory.providedBy(defaultFolder)
  True

The default preference providers also implicitly acquire default
values from parent sites. So if we add a new child folder called
``folder1``, make it a site and set it as the active site:

  >>> from zope.site.folder import Folder
  >>> root['folder1'] = Folder()
  >>> folder1 = root['folder1']

  >>> from zope.site.site import LocalSiteManager
  >>> sm1 = LocalSiteManager(folder1)
  >>> folder1.setSiteManager(sm1)
  >>> zope.component.hooks.setSite(folder1)

and add a default provider there,

  >>> provider1 = addUtility(
  ...     sm1, default.DefaultPreferenceProvider(),
  ...     interfaces.IDefaultPreferenceProvider)

then we still get the root's default values, because we have not defined any
in the higher default provider:

  >>> settings.Folder.sortedBy
  'size'

But if we provide the new provider with a default value for `sortedBy`,

  >>> defaultFolder1 = provider1.getDefaultPreferenceGroup('ZMISettings.Folder')
  >>> defaultFolder1.sortedBy = 'creator'

then it is used instead:

  >>> settings.Folder.sortedBy
  'creator'

Of course, once the root site becomes our active site again

  >>> zope.component.hooks.setSite(root)

the default value of the root provider is used:

  >>> settings.Folder.sortedBy
  'size'

Of course, all the defaults in the world are not relevant anymore as soon as
the user actually provides a value:

  >>> settings.Folder.sortedBy = 'name'
  >>> settings.Folder.sortedBy
  'name'

Oh, and have I mentioned that entered values are always validated? So you
cannot just assign any old value:

  >>> settings.Folder.sortedBy = 'foo'
  Traceback (most recent call last):
  ...
  ConstraintNotSatisfied: foo

Finally, if the user deletes his/her explicit setting, we are back to the
default value:

  >>> del settings.Folder.sortedBy
  >>> settings.Folder.sortedBy
  'size'

Just as with regular preference groups, the default preference groups
are arranged in a matching hierarchy:

  >>> defaultSettings = provider.getDefaultPreferenceGroup('ZMISettings')
  >>> defaultSettings.get('Folder')
  <zope.preference.default.DefaultPreferenceGroup object at ...>
  >>> defaultSettings.Folder
  <zope.preference.default.DefaultPreferenceGroup object at ...>

They also report useful AttributeErrors for bad accesses:

  >>> defaultSettings.not_in_schema
  Traceback (most recent call last):
  ...
  AttributeError: 'not_in_schema' is not a preference or sub-group.


Creating Preference Groups Using ZCML
=====================================

If you are using the user preference system in Zope 3, you will not have to
manually setup the preference groups as we did above (of course). We will use
ZCML instead. First, we need to register the directives:

  >>> from zope.configuration import xmlconfig
  >>> import zope.preference
  >>> context = xmlconfig.file('meta.zcml', zope.preference)

Then the system sets up a root preference group:

  >>> context = xmlconfig.string('''
  ...     <configure
  ...         xmlns="http://namespaces.zope.org/zope"
  ...         i18n_domain="test">
  ...
  ...       <preferenceGroup
  ...           id=""
  ...           title="User Preferences"
  ...           />
  ...
  ...     </configure>''', context)

Now we can use the preference system in its intended way. We access the folder
settings as follows:

  >>> import zope.component
  >>> prefs = zope.component.getUtility(interfaces.IPreferenceGroup)
  >>> prefs.ZMISettings.Folder.sortedBy
  'size'

Let's register the ZMI settings again under a new name via ZCML:

  >>> context = xmlconfig.string('''
  ...     <configure
  ...         xmlns="http://namespaces.zope.org/zope"
  ...         i18n_domain="test">
  ...
  ...       <preferenceGroup
  ...           id="ZMISettings2"
  ...           title="ZMI Settings NG"
  ...           schema="zope.preference.README.IZMIUserSettings"
  ...           category="true"
  ...           />
  ...
  ...     </configure>''', context)

  >>> prefs.ZMISettings2 #doctest:+ELLIPSIS
  <zope.preference.preference.PreferenceGroup object at ...>

  >>> prefs.ZMISettings2.__title__
  'ZMI Settings NG'

  >>> IZMIUserSettings.providedBy(prefs.ZMISettings2)
  True
  >>> interfaces.IPreferenceCategory.providedBy(prefs.ZMISettings2)
  True

And the tree can built again by carefully constructing the id:

  >>> context = xmlconfig.string('''
  ...     <configure
  ...         xmlns="http://namespaces.zope.org/zope"
  ...         i18n_domain="test">
  ...
  ...       <preferenceGroup
  ...           id="ZMISettings2.Folder"
  ...           title="Folder Settings"
  ...           schema="zope.preference.README.IFolderSettings"
  ...           />
  ...
  ...     </configure>''', context)

  >>> prefs.ZMISettings2 #doctest:+ELLIPSIS
  <zope.preference.preference.PreferenceGroup object at ...>

  >>> prefs.ZMISettings2.Folder.__title__
  'Folder Settings'

  >>> IFolderSettings.providedBy(prefs.ZMISettings2.Folder)
  True
  >>> interfaces.IPreferenceCategory.providedBy(prefs.ZMISettings2.Folder)
  False


Simple Python-Level Access
==========================

If a site is set, getting the user preferences is very simple:

  >>> from zope.preference import UserPreferences
  >>> prefs2 = UserPreferences()
  >>> prefs2.ZMISettings.Folder.sortedBy
  'size'

This function is also commonly registered as an adapter,

  >>> from zope.location.interfaces import ILocation
  >>> provideAdapter(UserPreferences, [ILocation], interfaces.IUserPreferences)

so that you can adapt any location to the user preferences:

  >>> prefs3 = interfaces.IUserPreferences(folder1)
  >>> prefs3.ZMISettings.Folder.sortedBy
  'creator'


Traversal
=========

Okay, so all these objects are nice, but they do not make it any easier to
access the preferences in page templates. Thus, a special traversal namespace
has been created that makes it very simple to access the preferences via a
traversal path. But before we can use the path expressions, we have to
register all necessary traversal components and the special `preferences`
namespace:

  >>> import zope.traversing.interfaces
  >>> provideAdapter(preference.preferencesNamespace, [None],
  ...                      zope.traversing.interfaces.ITraversable,
  ...                      'preferences')

We can now access the preferences as follows:

  >>> from zope.traversing.api import traverse
  >>> traverse(None, '++preferences++ZMISettings/skin')
  'Basic'
  >>> traverse(None, '++preferences++/ZMISettings/skin')
  'Basic'


Security
========

You might already wonder under which permissions the preferences are
available. They are actually available publicly (`CheckerPublic`), but that
is not a problem, since the available values are looked up specifically for
the current user. And why should a user not have full access to his/her
preferences?

Let's create a checker using the function that the security machinery is
actually using:

  >>> checker = preference.PreferenceGroupChecker(settings)
  >>> checker.permission_id('skin')
  Global(CheckerPublic,zope.security.checker)
  >>> checker.setattr_permission_id('skin')
  Global(CheckerPublic,zope.security.checker)

The id, title, description, and schema are publicly available for access,
but are not available for mutation at all:

  >>> checker.permission_id('__id__')
  Global(CheckerPublic,zope.security.checker)
  >>> checker.setattr_permission_id('__id__') is None
  True


The only way security could be compromised is when one could override the
annotations property. However, this property is not available for public
consumption at all, including read access:

  >>> checker.permission_id('annotation') is None
  True
  >>> checker.setattr_permission_id('annotation') is None
  True


=========
 CHANGES
=========

5.0 (2023-02-10)
================

- Drop support for Python 2.7, 3.4, 3.5, 3.6.

- Add support for Python 3.8, 3.9, 3.10, 3.11.


4.1.0 (2018-09-27)
==================

- Support newer zope.configuration and persistent. See `issue 2
  <https://github.com/zopefoundation/zope.preference/issues/2>`_.

- Add support for Python 3.7 and PyPy3.

- Drop support for Python 3.3.

4.0.0 (2017-05-09)
==================

- Add support for Python 3.4, 3.5 and 3.6.

- Add support for PyPy.

- Drop support for Python 2.6.


4.0.0a1 (2013-02-24)
====================

- Added support for Python 3.3.

- Replaced deprecated ``zope.interface.implements`` usage with equivalent
  ``zope.interface.implementer`` decorator.

- Dropped support for Python 2.4 and 2.5.

- Refactored tests not to rely on ``zope.app.testing`` anymore.

- Fixed a bug while accessing the parent of a preference group.


3.8.0 (2010-06-12)
==================

- Split out from `zope.app.preference`.

- Removed dependency on `zope.app.component.hooks` by using
  `zope.component.hooks`.

- Removed dependency on `zope.app.container` by using
  `zope.container`.

            

Raw data

            {
    "_id": null,
    "home_page": "http://github.com/zopefoundation/zope.preference",
    "name": "zope.preference",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "bluebream zope zope3 user preference",
    "author": "Zope Foundation and Contributors",
    "author_email": "zope-dev@zope.dev",
    "download_url": "https://files.pythonhosted.org/packages/d4/4d/6fd771cc0be13581c8f0c2c362f6b692d7c4ed4a8acef9ac1414e76036a9/zope.preference-5.0.tar.gz",
    "platform": null,
    "description": "This package provides an API to create and maintain hierarchical user\npreferences. Preferences can be easily created by defining schemas.\n\n\n.. contents::\n\n==================\n User Preferences\n==================\n\nImplementing user preferences is usually a painful task, since it requires a\nlot of custom coding and constantly changing preferences makes it hard to\nmaintain the data and UI. The `preference` package\n\n  >>> from zope.preference import preference\n\neases this pain by providing a generic user preferences framework that uses\nschemas to categorize and describe the preferences.\n\nPreference Groups\n=================\n\nPreferences are grouped in preference groups and the preferences inside a\ngroup are specified via the preferences group schema:\n\n  >>> import zope.interface\n  >>> import zope.schema\n  >>> class IZMIUserSettings(zope.interface.Interface):\n  ...     \"\"\"Basic User Preferences\"\"\"\n  ...\n  ...     email = zope.schema.TextLine(\n  ...         title=u\"E-mail Address\",\n  ...         description=u\"E-mail Address used to send notifications\")\n  ...\n  ...     skin = zope.schema.Choice(\n  ...         title=u\"Skin\",\n  ...         description=u\"The skin that should be used for the ZMI.\",\n  ...         values=['Rotterdam', 'ZopeTop', 'Basic'],\n  ...         default='Rotterdam')\n  ...\n  ...     showZopeLogo = zope.schema.Bool(\n  ...         title=u\"Show Zope Logo\",\n  ...         description=u\"Specifies whether Zope logo should be displayed \"\n  ...                     u\"at the top of the screen.\",\n  ...         default=True)\n\nNow we can instantiate the preference group. Each preference group must have an\nID by which it can be accessed and optional title and description fields for UI\npurposes:\n\n  >>> settings = preference.PreferenceGroup(\n  ...     \"ZMISettings\",\n  ...     schema=IZMIUserSettings,\n  ...     title=u\"ZMI User Settings\",\n  ...     description=u\"\")\n\nNote that the preferences group provides the interface it is representing:\n\n  >>> IZMIUserSettings.providedBy(settings)\n  True\n\nand the id, schema and title of the group are directly available:\n\n  >>> settings.__id__\n  'ZMISettings'\n  >>> settings.__schema__\n  <InterfaceClass zope.preference.README.IZMIUserSettings>\n  >>> settings.__title__\n  'ZMI User Settings'\n\nSo let's ask the preference group for the `skin` setting:\n\n  >>> settings.skin #doctest:+ELLIPSIS\n  Traceback (most recent call last):\n  ...\n  zope.security.interfaces.NoInteraction\n\n\nSo why did the lookup fail? Because we have not specified a principal yet, for\nwhich we want to lookup the preferences. To do that, we have to create a new\ninteraction:\n\n  >>> class Principal:\n  ...     def __init__(self, id):\n  ...         self.id = id\n  >>> principal = Principal('zope.user')\n\n  >>> class Participation:\n  ...     interaction = None\n  ...     def __init__(self, principal):\n  ...         self.principal = principal\n\n  >>> participation = Participation(principal)\n\n  >>> import zope.security.management\n  >>> zope.security.management.newInteraction(participation)\n\nWe also need an IAnnotations adapter for principals, so we can store the\nsettings:\n\n  >>> from zope.annotation.interfaces import IAnnotations\n  >>> @zope.interface.implementer(IAnnotations)\n  ... class PrincipalAnnotations(dict):\n  ...     data = {}\n  ...     def __new__(class_, principal, context):\n  ...         try:\n  ...             annotations = class_.data[principal.id]\n  ...         except KeyError:\n  ...             annotations = dict.__new__(class_)\n  ...             class_.data[principal.id] = annotations\n  ...         return annotations\n  ...     def __init__(self, principal, context):\n  ...         pass\n\n  >>> from zope.component import provideAdapter\n  >>> provideAdapter(PrincipalAnnotations,\n  ...                (Principal, zope.interface.Interface), IAnnotations)\n\nLet's now try to access the settings again:\n\n  >>> settings.skin\n  'Rotterdam'\n\nwhich is the default value, since we have not set it yet. We can now reassign\nthe value:\n\n  >>> settings.skin = 'Basic'\n  >>> settings.skin\n  'Basic'\n\nHowever, you cannot just enter any value, since it is validated before the\nassignment:\n\n  >>> settings.skin = 'MySkin'\n  Traceback (most recent call last):\n  ...\n  ConstraintNotSatisfied: MySkin\n\n\nPreference Group Trees\n======================\n\nThe preferences would not be very powerful, if you could create a full\npreferences. So let's create a sub-group for our ZMI user settings, where we\ncan adjust the look and feel of the folder contents view:\n\n  >>> class IFolderSettings(zope.interface.Interface):\n  ...     \"\"\"Basic User Preferences\"\"\"\n  ...\n  ...     shownFields = zope.schema.Set(\n  ...         title=u\"Shown Fields\",\n  ...         description=u\"Fields shown in the table.\",\n  ...         value_type=zope.schema.Choice(['name', 'size', 'creator']),\n  ...         default=set(['name', 'size']))\n  ...\n  ...     sortedBy = zope.schema.Choice(\n  ...         title=u\"Sorted By\",\n  ...         description=u\"Data field to sort by.\",\n  ...         values=['name', 'size', 'creator'],\n  ...         default='name')\n\n  >>> folderSettings = preference.PreferenceGroup(\n  ...     \"ZMISettings.Folder\",\n  ...     schema=IFolderSettings,\n  ...     title=u\"Folder Content View Settings\")\n\nNote that the id was chosen so that the parent id is the prefix of the child's\nid. Our new preference sub-group should now be available as an attribute or an\nitem on the parent group ...\n\n  >>> settings.Folder\n  Traceback (most recent call last):\n  ...\n  AttributeError: 'Folder' is not a preference or sub-group.\n  >>> settings['Folder']\n  Traceback (most recent call last):\n  ...\n  KeyError: 'Folder'\n\nbut not before we register the groups as utilities:\n\n  >>> from zope.preference import interfaces\n  >>> from zope.component import provideUtility\n\n  >>> provideUtility(settings, interfaces.IPreferenceGroup,\n  ...                name='ZMISettings')\n  >>> provideUtility(folderSettings, interfaces.IPreferenceGroup,\n  ...                name='ZMISettings.Folder')\n\nIf we now try to lookup the sub-group again, we should be successful:\n\n  >>> settings.Folder #doctest:+ELLIPSIS\n  <zope.preference.preference.PreferenceGroup object at ...>\n\n  >>> settings['Folder'] #doctest:+ELLIPSIS\n  <zope.preference.preference.PreferenceGroup object at ...>\n  >>> 'Folder' in settings\n  True\n  >>> list(settings)\n  [<zope.preference.preference.PreferenceGroup object at ...>]\n\nWhile the registry of the preference groups is flat, the careful naming of the\nids allows us to have a tree of preferences. Note that this pattern is very\nsimilar to the way modules are handled in Python; they are stored in a flat\ndictionary in ``sys.modules``, but due to the naming they appear to be in a\nnamespace tree.\n\nWhile we are at it, there are also preference categories that can be compared\nto Python packages. They basically are just a higher level grouping concept\nthat is used by the UI to better organize the preferences. A preference group\ncan be converted to a category by simply providing an additional interface:\n\n  >>> zope.interface.alsoProvides(folderSettings, interfaces.IPreferenceCategory)\n\n  >>> interfaces.IPreferenceCategory.providedBy(folderSettings)\n  True\n\nPreference group objects can also hold arbitrary attributes, but since\nthey're not persistent this must be used with care:\n\n  >>> settings.not_in_schema = 1\n  >>> settings.not_in_schema\n  1\n  >>> del settings.not_in_schema\n  >>> settings.not_in_schema\n  Traceback (most recent call last):\n  ...\n  AttributeError: 'not_in_schema' is not a preference or sub-group.\n\nDefault Preferences\n===================\n\nIt is sometimes desirable to define default settings on a site-by-site\nbasis, instead of just using the default value from the schema. The\npreferences package provides a module that implements a default\npreferences provider that can be added as a unnamed utility for each\nsite:\n\n  >>> from zope.preference import default\n\nWe'll begin by creating a new root site:\n\n  >>> from zope.site.folder import rootFolder\n  >>> root = rootFolder()\n  >>> from zope.site.site import LocalSiteManager\n  >>> rsm = LocalSiteManager(root)\n  >>> root.setSiteManager(rsm)\n\nAnd we'll make the new site the current site:\n\n  >>> zope.component.hooks.setSite(root)\n\nNow we can register the default preference provider with the root site:\n\n  >>> provider = addUtility(\n  ...     rsm, default.DefaultPreferenceProvider(),\n  ...     interfaces.IDefaultPreferenceProvider)\n\nSo before we set an explicit default value for a preference, the schema field\ndefault is used:\n\n  >>> settings.Folder.sortedBy\n  'name'\n\nBut if we now set a new default value with the provider,\n\n  >>> defaultFolder = provider.getDefaultPreferenceGroup('ZMISettings.Folder')\n  >>> defaultFolder.sortedBy = 'size'\n\nthen the default of the setting changes:\n\n  >>> settings.Folder.sortedBy\n  'size'\n\nBecause the ``ZMISettings.Folder`` was declared as a preference\ncategory, the default implementation is too:\n\n  >>> interfaces.IPreferenceCategory.providedBy(defaultFolder)\n  True\n\nThe default preference providers also implicitly acquire default\nvalues from parent sites. So if we add a new child folder called\n``folder1``, make it a site and set it as the active site:\n\n  >>> from zope.site.folder import Folder\n  >>> root['folder1'] = Folder()\n  >>> folder1 = root['folder1']\n\n  >>> from zope.site.site import LocalSiteManager\n  >>> sm1 = LocalSiteManager(folder1)\n  >>> folder1.setSiteManager(sm1)\n  >>> zope.component.hooks.setSite(folder1)\n\nand add a default provider there,\n\n  >>> provider1 = addUtility(\n  ...     sm1, default.DefaultPreferenceProvider(),\n  ...     interfaces.IDefaultPreferenceProvider)\n\nthen we still get the root's default values, because we have not defined any\nin the higher default provider:\n\n  >>> settings.Folder.sortedBy\n  'size'\n\nBut if we provide the new provider with a default value for `sortedBy`,\n\n  >>> defaultFolder1 = provider1.getDefaultPreferenceGroup('ZMISettings.Folder')\n  >>> defaultFolder1.sortedBy = 'creator'\n\nthen it is used instead:\n\n  >>> settings.Folder.sortedBy\n  'creator'\n\nOf course, once the root site becomes our active site again\n\n  >>> zope.component.hooks.setSite(root)\n\nthe default value of the root provider is used:\n\n  >>> settings.Folder.sortedBy\n  'size'\n\nOf course, all the defaults in the world are not relevant anymore as soon as\nthe user actually provides a value:\n\n  >>> settings.Folder.sortedBy = 'name'\n  >>> settings.Folder.sortedBy\n  'name'\n\nOh, and have I mentioned that entered values are always validated? So you\ncannot just assign any old value:\n\n  >>> settings.Folder.sortedBy = 'foo'\n  Traceback (most recent call last):\n  ...\n  ConstraintNotSatisfied: foo\n\nFinally, if the user deletes his/her explicit setting, we are back to the\ndefault value:\n\n  >>> del settings.Folder.sortedBy\n  >>> settings.Folder.sortedBy\n  'size'\n\nJust as with regular preference groups, the default preference groups\nare arranged in a matching hierarchy:\n\n  >>> defaultSettings = provider.getDefaultPreferenceGroup('ZMISettings')\n  >>> defaultSettings.get('Folder')\n  <zope.preference.default.DefaultPreferenceGroup object at ...>\n  >>> defaultSettings.Folder\n  <zope.preference.default.DefaultPreferenceGroup object at ...>\n\nThey also report useful AttributeErrors for bad accesses:\n\n  >>> defaultSettings.not_in_schema\n  Traceback (most recent call last):\n  ...\n  AttributeError: 'not_in_schema' is not a preference or sub-group.\n\n\nCreating Preference Groups Using ZCML\n=====================================\n\nIf you are using the user preference system in Zope 3, you will not have to\nmanually setup the preference groups as we did above (of course). We will use\nZCML instead. First, we need to register the directives:\n\n  >>> from zope.configuration import xmlconfig\n  >>> import zope.preference\n  >>> context = xmlconfig.file('meta.zcml', zope.preference)\n\nThen the system sets up a root preference group:\n\n  >>> context = xmlconfig.string('''\n  ...     <configure\n  ...         xmlns=\"http://namespaces.zope.org/zope\"\n  ...         i18n_domain=\"test\">\n  ...\n  ...       <preferenceGroup\n  ...           id=\"\"\n  ...           title=\"User Preferences\"\n  ...           />\n  ...\n  ...     </configure>''', context)\n\nNow we can use the preference system in its intended way. We access the folder\nsettings as follows:\n\n  >>> import zope.component\n  >>> prefs = zope.component.getUtility(interfaces.IPreferenceGroup)\n  >>> prefs.ZMISettings.Folder.sortedBy\n  'size'\n\nLet's register the ZMI settings again under a new name via ZCML:\n\n  >>> context = xmlconfig.string('''\n  ...     <configure\n  ...         xmlns=\"http://namespaces.zope.org/zope\"\n  ...         i18n_domain=\"test\">\n  ...\n  ...       <preferenceGroup\n  ...           id=\"ZMISettings2\"\n  ...           title=\"ZMI Settings NG\"\n  ...           schema=\"zope.preference.README.IZMIUserSettings\"\n  ...           category=\"true\"\n  ...           />\n  ...\n  ...     </configure>''', context)\n\n  >>> prefs.ZMISettings2 #doctest:+ELLIPSIS\n  <zope.preference.preference.PreferenceGroup object at ...>\n\n  >>> prefs.ZMISettings2.__title__\n  'ZMI Settings NG'\n\n  >>> IZMIUserSettings.providedBy(prefs.ZMISettings2)\n  True\n  >>> interfaces.IPreferenceCategory.providedBy(prefs.ZMISettings2)\n  True\n\nAnd the tree can built again by carefully constructing the id:\n\n  >>> context = xmlconfig.string('''\n  ...     <configure\n  ...         xmlns=\"http://namespaces.zope.org/zope\"\n  ...         i18n_domain=\"test\">\n  ...\n  ...       <preferenceGroup\n  ...           id=\"ZMISettings2.Folder\"\n  ...           title=\"Folder Settings\"\n  ...           schema=\"zope.preference.README.IFolderSettings\"\n  ...           />\n  ...\n  ...     </configure>''', context)\n\n  >>> prefs.ZMISettings2 #doctest:+ELLIPSIS\n  <zope.preference.preference.PreferenceGroup object at ...>\n\n  >>> prefs.ZMISettings2.Folder.__title__\n  'Folder Settings'\n\n  >>> IFolderSettings.providedBy(prefs.ZMISettings2.Folder)\n  True\n  >>> interfaces.IPreferenceCategory.providedBy(prefs.ZMISettings2.Folder)\n  False\n\n\nSimple Python-Level Access\n==========================\n\nIf a site is set, getting the user preferences is very simple:\n\n  >>> from zope.preference import UserPreferences\n  >>> prefs2 = UserPreferences()\n  >>> prefs2.ZMISettings.Folder.sortedBy\n  'size'\n\nThis function is also commonly registered as an adapter,\n\n  >>> from zope.location.interfaces import ILocation\n  >>> provideAdapter(UserPreferences, [ILocation], interfaces.IUserPreferences)\n\nso that you can adapt any location to the user preferences:\n\n  >>> prefs3 = interfaces.IUserPreferences(folder1)\n  >>> prefs3.ZMISettings.Folder.sortedBy\n  'creator'\n\n\nTraversal\n=========\n\nOkay, so all these objects are nice, but they do not make it any easier to\naccess the preferences in page templates. Thus, a special traversal namespace\nhas been created that makes it very simple to access the preferences via a\ntraversal path. But before we can use the path expressions, we have to\nregister all necessary traversal components and the special `preferences`\nnamespace:\n\n  >>> import zope.traversing.interfaces\n  >>> provideAdapter(preference.preferencesNamespace, [None],\n  ...                      zope.traversing.interfaces.ITraversable,\n  ...                      'preferences')\n\nWe can now access the preferences as follows:\n\n  >>> from zope.traversing.api import traverse\n  >>> traverse(None, '++preferences++ZMISettings/skin')\n  'Basic'\n  >>> traverse(None, '++preferences++/ZMISettings/skin')\n  'Basic'\n\n\nSecurity\n========\n\nYou might already wonder under which permissions the preferences are\navailable. They are actually available publicly (`CheckerPublic`), but that\nis not a problem, since the available values are looked up specifically for\nthe current user. And why should a user not have full access to his/her\npreferences?\n\nLet's create a checker using the function that the security machinery is\nactually using:\n\n  >>> checker = preference.PreferenceGroupChecker(settings)\n  >>> checker.permission_id('skin')\n  Global(CheckerPublic,zope.security.checker)\n  >>> checker.setattr_permission_id('skin')\n  Global(CheckerPublic,zope.security.checker)\n\nThe id, title, description, and schema are publicly available for access,\nbut are not available for mutation at all:\n\n  >>> checker.permission_id('__id__')\n  Global(CheckerPublic,zope.security.checker)\n  >>> checker.setattr_permission_id('__id__') is None\n  True\n\n\nThe only way security could be compromised is when one could override the\nannotations property. However, this property is not available for public\nconsumption at all, including read access:\n\n  >>> checker.permission_id('annotation') is None\n  True\n  >>> checker.setattr_permission_id('annotation') is None\n  True\n\n\n=========\n CHANGES\n=========\n\n5.0 (2023-02-10)\n================\n\n- Drop support for Python 2.7, 3.4, 3.5, 3.6.\n\n- Add support for Python 3.8, 3.9, 3.10, 3.11.\n\n\n4.1.0 (2018-09-27)\n==================\n\n- Support newer zope.configuration and persistent. See `issue 2\n  <https://github.com/zopefoundation/zope.preference/issues/2>`_.\n\n- Add support for Python 3.7 and PyPy3.\n\n- Drop support for Python 3.3.\n\n4.0.0 (2017-05-09)\n==================\n\n- Add support for Python 3.4, 3.5 and 3.6.\n\n- Add support for PyPy.\n\n- Drop support for Python 2.6.\n\n\n4.0.0a1 (2013-02-24)\n====================\n\n- Added support for Python 3.3.\n\n- Replaced deprecated ``zope.interface.implements`` usage with equivalent\n  ``zope.interface.implementer`` decorator.\n\n- Dropped support for Python 2.4 and 2.5.\n\n- Refactored tests not to rely on ``zope.app.testing`` anymore.\n\n- Fixed a bug while accessing the parent of a preference group.\n\n\n3.8.0 (2010-06-12)\n==================\n\n- Split out from `zope.app.preference`.\n\n- Removed dependency on `zope.app.component.hooks` by using\n  `zope.component.hooks`.\n\n- Removed dependency on `zope.app.container` by using\n  `zope.container`.\n",
    "bugtrack_url": null,
    "license": "ZPL 2.1",
    "summary": "User Preferences Framework",
    "version": "5.0",
    "split_keywords": [
        "bluebream",
        "zope",
        "zope3",
        "user",
        "preference"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "26267858841ab4336347dc3e242bee34d504ae6b14aeac264989cb200e9c04b0",
                "md5": "a8a3f95aa9ce89bc307632409263f97b",
                "sha256": "99e50e3364983f8e31b7606c2fdabaef0e278a60d32a378c73862a8c481766ed"
            },
            "downloads": -1,
            "filename": "zope.preference-5.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "a8a3f95aa9ce89bc307632409263f97b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 23687,
            "upload_time": "2023-02-10T09:31:32",
            "upload_time_iso_8601": "2023-02-10T09:31:32.938222Z",
            "url": "https://files.pythonhosted.org/packages/26/26/7858841ab4336347dc3e242bee34d504ae6b14aeac264989cb200e9c04b0/zope.preference-5.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "d44d6fd771cc0be13581c8f0c2c362f6b692d7c4ed4a8acef9ac1414e76036a9",
                "md5": "a53021e206dbb47306293a44b39ebda8",
                "sha256": "6b3d63c75e4e0c051a89a6adfc67c9f0a9e7c884de2cd8054cc435dc37d7f3d8"
            },
            "downloads": -1,
            "filename": "zope.preference-5.0.tar.gz",
            "has_sig": false,
            "md5_digest": "a53021e206dbb47306293a44b39ebda8",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 24797,
            "upload_time": "2023-02-10T09:31:35",
            "upload_time_iso_8601": "2023-02-10T09:31:35.257199Z",
            "url": "https://files.pythonhosted.org/packages/d4/4d/6fd771cc0be13581c8f0c2c362f6b692d7c4ed4a8acef9ac1414e76036a9/zope.preference-5.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-02-10 09:31:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "zopefoundation",
    "github_project": "zope.preference",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "zope.preference"
}
        
Elapsed time: 0.06847s