code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
__docformat__ = 'restructuredtext'
import persistent
import zope.interface
import zope.component
import zope.event
import zope.lifecycleevent
from zope.i18n.interfaces import INegotiator
from zope.security.interfaces import NoInteraction
from zope.security.management import getInteraction
from z3c.language.switch import II18n
def getRequest():
try:
interaction = getInteraction()
request = interaction.participations[0]
except NoInteraction:
request = None
except IndexError:
request = None
return request
class I18n(persistent.Persistent, object):
"""Mixin implementation of II18n.
Set a factory class in our implementation. The _create method will initalize
this class and use it as a child object providing the attributes without
languages.
You can use this class as mixin for i18n implementations:
>>> from z3c.language.switch.app import I18n
>>> class Person(object):
... def __init__(self, firstname, lastname):
... self.firstname = firstname
... self.lastname = lastname
>>> class I18nPerson(I18n):
... _defaultLanguage = 'en'
... _factory = Person
Now you can initialize the default translation:
>>> i18n = I18nPerson(firstname='Bob', lastname='Miller')
>>> i18n.getDefaultLanguage()
'en'
>>> i18n.getPreferedLanguage()
'en'
You can access the attributes of the default translation:
>>> i18n.getAttribute('firstname')
'Bob'
>>> i18n.getAttribute('lastname')
'Miller'
That is the same as accessing the attribute using a language parameter:
>>> i18n.getAttribute('firstname', 'en')
'Bob'
If an attribute is not available a AttributeError is raised. The
queryAttribute method offers a save way for unsecure access:
>>> i18n.getAttribute('name')
Traceback (most recent call last):
...
AttributeError: 'Person' object has no attribute 'name'
>>> i18n.queryAttribute('name') is None
True
You can set the attributes an other time:
>>> i18n.setAttributes('en', firstname='Foo', lastname='Bar')
>>> i18n.getAttribute('firstname')
'Foo'
>>> i18n.getAttribute('lastname')
'Bar'
You can initialize the default translation using a specific language:
>>> i18n = I18nPerson(defaultLanguage='fr', firstname='Robert',
... lastname='Moulin')
>>> i18n.getDefaultLanguage()
'fr'
>>> i18n.getPreferedLanguage()
'fr'
"""
_data = None
# sublclasses should overwrite this attributes.
_defaultLanguage = None
_factory = None
# private method (subclasses might overwrite this method)
def _defaultArgs(self):
return None
zope.interface.implements(II18n)
def __init__(self, defaultLanguage=None, *args, **kws):
# preconditions
if self._defaultLanguage is None:
raise NotImplementedError('_defaultLanguage')
if self._factory is None:
raise NotImplementedError('_factory')
# essentials
if defaultLanguage is None:
defaultLanguage = self._defaultLanguage
# initialize data store for translations
self._setDataOnce()
# initialize default translation
self._get_or_add(defaultLanguage, *args, **kws)
# set default language
self.setDefaultLanguage(defaultLanguage)
# private method
def _setDataOnce(self):
if self._data is None:
self._data = {}
# private method: access self._data only using this method
def _getData(self):
return self._data
# z3c.langauge.switch.IReadI18n
def getAvailableLanguages(self):
"""See `z3c.langauge.switch.interfaces.IReadI18n`"""
keys = self._getData().keys()
keys.sort()
return keys
def getDefaultLanguage(self):
"""See `z3c.langauge.switch.interfaces.IReadI18n`"""
return self._defaultLanguage
def getPreferedLanguage(self):
# evaluate the negotiator
language = None
request = getRequest()
negotiator = None
try:
negotiator = zope.component.queryUtility(INegotiator,
name='', context=self)
except zope.component.ComponentLookupError:
# can happens during tests without a site and sitemanager
pass
if request and negotiator:
language = negotiator.getLanguage(self.getAvailableLanguages(), request)
if language is None:
language = self.getDefaultLanguage()
if language is None:
# fallback language for functional tests, there we have a cookie request
language = 'en'
return language
def getAttribute(self, name, language=None):
# preconditions
if language is None:
language = self.getDefaultLanguage()
if not language in self.getAvailableLanguages():
raise KeyError(language)
# essentials
data = self._getData()[language]
return getattr(data, name)
def queryAttribute(self, name, language=None, default=None):
try:
return self.getAttribute(name, language)
except (KeyError, AttributeError):
return default
# z3c.langauge.switch.IReadI18n
def setDefaultLanguage(self, language):
"""See `z3c.langauge.switch.interfaces.IWriteI18n`"""
data = self._getData()
if language not in data:
raise ValueError(
'cannot set nonexistent language (%s) as default' % language)
self._defaultLanguage = language
def addLanguage(self, language, *args, **kw):
"""See `z3c.langauge.switch.interfaces.IWriteI18n`"""
if not args and not kw:
if self._defaultArgs() is not None:
args = self._defaultArgs()
self._get_or_add(language, *args, **kw)
zope.event.notify(zope.lifecycleevent.ObjectModifiedEvent(self))
def removeLanguage(self, language):
"""See `z3c.langauge.switch.interfaces.IWriteI18n`"""
data = self._getData()
if language == self.getDefaultLanguage():
raise ValueError('cannot remove default language (%s)' % language)
elif language not in data:
raise ValueError('cannot remove nonexistent language (%s)'
% language)
else:
del data[language]
self._p_changed = True
zope.event.notify(zope.lifecycleevent.ObjectModifiedEvent(self))
def setAttributes(self, language, **kws):
# preconditions
if not language in self.getAvailableLanguages():
raise KeyError(language)
data = self._getData()
obj = data[language]
for key in kws:
if not hasattr(obj, key):
raise KeyError(key)
# essentials
for key in kws:
setattr(obj, key, kws[key])
else:
self._p_changed = True
zope.event.notify(zope.lifecycleevent.ObjectModifiedEvent(self))
# private helper methods
def _create(self, *args, **kw):
"""Create a new subobject of the type document."""
factory = self._factory
obj = factory(*args, **kw)
zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj))
return obj
def _get(self, language):
"""Helper function -- return a subobject for a given language,
and if it does not exist, return a subobject for the default
language.
"""
data = self._getData()
obj = data.get(language, None)
if obj is None:
obj = data[self.getDefaultLanguage()]
return obj
def _get_or_add(self, language, *args, **kw):
"""Helper function -- return a subobject for a given language,
and if it does not exist, create and return a new subobject.
"""
data = self._getData()
language = self._getLang(language)
obj = data.get(language, None)
if obj is None:
obj = self._create(*args, **kw)
data[language] = obj
# this (ILocation info) is needed for the pickler used by the
# locationCopy method in the ObjectCopier class
obj.__parent__ = self
obj.__name__ = language
self._p_changed = 1
return obj
def _getLang(self, language):
"""Returns the given language or the default language."""
if language == None:
language = self.getDefaultLanguage()
return language | z3c.language.switch | /z3c.language.switch-1.1.0.zip/z3c.language.switch-1.1.0/src/z3c/language/switch/app.py | app.py |
=================
Langauge Switcher
=================
Let's show how ``z3c.language.switch`` works:
Imports and placeless setup:
>>> import zope.component
>>> from zope.app.testing import placelesssetup
>>> from z3c.language.switch import II18nLanguageSwitch
>>> from z3c.language.switch.testing import IContentObject
>>> from z3c.language.switch.testing import II18nContentObject
>>> from z3c.language.switch.testing import I18nContentObject
>>> from z3c.language.switch.testing import I18nContentObjectLanguageSwitch
>>> from z3c.language.switch.testing import ContentObject
>>> placelesssetup.setUp()
Setup test object:
>>> en_title = u'en_title'
>>> obj = I18nContentObject(en_title)
>>> obj.title
u'en_title'
Add additional languages:
>>> de_title = u'de_title'
>>> fr_title = u'fr_title'
>>> deObj = obj.addLanguage('de', de_title)
>>> frObj = obj.addLanguage('fr', fr_title)
Switch default language:
>>> obj.title
u'en_title'
>>> obj.setDefaultLanguage('de')
>>> obj.title
u'de_title'
Remove the 'en' language object:
>>> obj._data.keys()
['de', 'en', 'fr']
>>> obj.removeLanguage('en')
>>> obj._data.keys()
['de', 'fr']
Remove default language object will end in a ``ValueError`` error:
>>> obj.removeLanguage('de')
Traceback (most recent call last):
...
ValueError: cannot remove default language (de)
Remove nonexistent language object will end in a ``ValueError`` error:
>>> obj.removeLanguage('undefined')
Traceback (most recent call last):
...
ValueError: cannot remove nonexistent language (undefined)
Set default language to a non existent language will end in a ``ValueError``:
>>> obj.setDefaultLanguage('en')
Traceback (most recent call last):
...
ValueError: cannot set nonexistent language (en) as default
Access the language directly via the ``II18nLanguageSwitch`` adapter,
first register the adapter for the ``I18nContentObject``:
>>> zope.component.provideAdapter(I18nContentObjectLanguageSwitch,
... (II18nContentObject,), provides=II18nLanguageSwitch)
The adapter is set to the default language in the init method:
>>> adapted = II18nLanguageSwitch(obj)
>>> adapted.title
u'de_title'
Change the default language and access the title again, the title should not
switch to another language:
>>> obj.setDefaultLanguage('fr')
>>> adapted.title
u'de_title'
Switch the language to 'fr' via the adapter:
>>> adapted.setLanguage('fr')
>>> adapted.title
u'fr_title'
Finally, clean up:
>>> placelesssetup.tearDown()
``AvailableLanguagesVocabulary`` Vocabulary
-------------------------------------------
Use this vocabulary for get the available languages from the object
itself.
>>> from z3c.language.switch import vocabulary
>>> vocab = vocabulary.AvailableLanguagesVocabulary(obj)
>>> len(vocab._terms)
2
>>> vocab._terms[0].value
'de'
>>> vocab._terms[0].token
'de'
>>> vocab._terms[0].title
'de'
>>> vocab._terms[1].value
'fr'
>>> vocab._terms[1].token
'fr'
>>> vocab._terms[1].title
'fr'
| z3c.language.switch | /z3c.language.switch-1.1.0.zip/z3c.language.switch-1.1.0/src/z3c/language/switch/README.txt | README.txt |
__docformat__ = 'restructuredtext'
_marker = object()
class I18nFieldProperty(object):
"""Computed attributes based on schema fields and i18n implementation.
Field properties provide default values, data validation and error messages
based on data found in field meta-data.
Note that I18nFieldProperties can only be used for attributes stored in
a translation object. The class using this I18nFieldProperty must implement
z3c.langauge.switch.II18n.
"""
def __init__(self, field, name=None):
if name is None:
name = field.__name__
self.__field = field
self.__name = name
def __get__(self, inst, klass):
if inst is None:
return self
value = inst.queryAttribute(self.__name, inst.getPreferedLanguage(), _marker)
if value is _marker:
field = self.__field.bind(inst)
value = getattr(field, 'default', _marker)
if value is _marker:
raise AttributeError, self.__name
return value
def __set__(self, inst, value):
field = self.__field.bind(inst)
field.validate(value)
# make kws dict
kws = {}
kws[self.__name] = value
inst.setAttributes(inst.getPreferedLanguage(), **kws)
def __getattr__(self, name):
return getattr(self.__field, name)
class I18nLanguageSwitchFieldProperty(object):
"""Computed attributes based on schema fields and i18n language switch implementation.
Field properties provide default values, data validation and error messages
based on data found in field meta-data.
Note that I18nLanguageSwitchFieldProperty can only be used for attributes stored in
self.i18n.
If you use this field in simply object, there is a adapter called
'I18nLanguageSwitch' where the context attribute is setting to i18n.
"""
def __init__(self, field, name=None):
if name is None:
name = field.__name__
self.__field = field
self.__name = name
def __get__(self, inst, klass):
# essentails
if inst is None:
return self
i18n = inst.i18n
lang = inst.getLanguage()
value = i18n.queryAttribute(self.__name, lang, _marker)
if value is _marker:
field = self.__field.bind(inst)
value = getattr(field, 'default', _marker)
if value is _marker:
raise AttributeError, self.__name
return value
def __set__(self, inst, value):
# essentails
i18n = inst.i18n
lang = inst.getLanguage()
field = self.__field.bind(inst)
field.validate(value)
# make kws dict
kws = {}
kws[self.__name] = value
i18n.setAttributes(lang, **kws)
def __getattr__(self, name):
return getattr(self.__field, name) | z3c.language.switch | /z3c.language.switch-1.1.0.zip/z3c.language.switch-1.1.0/src/z3c/language/switch/property.py | property.py |
=============
Trusted layer
=============
This package contains the trusted layer. This layer support a correct set of
component registration and can be used for inheritation in custom skins.
The ITrustedBrowserLayer supports the same registration set like the
IMinimalBrowserLayer. The only difference is, that the trusted layer offers
trusted traversal adapters. This means a skin using this layer can traverse
over a PAU (pluggable IAuthentication utility) without to run into a
Unautorized exception.
For more information see also the README.txt in
z3c.layer.minimal. (`Minimal Layer`_)
Testing
-------
For testing the ITrustedBrowserLayer we use the testing skin defined in the
tests package which uses the ITrustedBrowserLayer. This means, that our
testing skin provides also the views defined in the minimal package
and it's testing views defined in the minimal tests.
Login as manager first:
>>> from zope.testbrowser.testing import Browser
>>> manager = Browser()
>>> manager.addHeader('Authorization', 'Basic mgr:mgrpw')
Check if we can access the public page.html view which is registred in the
ftesting.zcml file with our skin:
>>> skinURL = 'http://localhost/++skin++TrustedTesting'
>>> manager.open(skinURL + '/page.html')
>>> manager.url
'http://localhost/++skin++TrustedTesting/page.html'
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<BLANKLINE>
test page
<BLANKLINE>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
Now check the not found page which is a exception view on the exception
``zope.publisher.interfaces.INotFound``:
>>> manager.open(skinURL + '/foobar.html')
Traceback (most recent call last):
...
HTTPError: HTTP Error 404: Not Found
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<br />
<br />
<h3>
The page you are trying to access is not available
</h3>
<br />
<b>
Please try the following:
</b>
<br />
<ol>
<li>
Make sure that the Web site address is spelled correctly.
</li>
<li>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</li>
</ol>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check the user error page which is a view registred for
``zope.exceptions.interfaces.IUserError`` exceptions:
>>> manager.open(skinURL + '/@@usererror.html')
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<div>simply user error</div>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check error view registred for
``zope.interface.common.interfaces.IException``:
>>> manager.open(skinURL + '/@@systemerror.html')
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<br />
<br />
<h3>A system error occurred</h3>
<br />
<b>Please contact the administrator.</b>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check the ``zope.security.interfaces.IUnauthorized`` view, use a new
unregistred user (test browser) for this:
>>> unauthorized = Browser()
>>> unauthorized.open(skinURL + '/@@forbidden.html')
Traceback (most recent call last):
...
HTTPError: HTTP Error 401: Unauthorized
>>> print unauthorized.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<BLANKLINE>
<h1>Unauthorized</h1>
<BLANKLINE>
<p>You are not authorized</p>
<BLANKLINE>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
| z3c.layer | /z3c.layer-0.3.1.tar.gz/z3c.layer-0.3.1/src/z3c/layer/trusted/README.txt | README.txt |
=============
Pagelet layer
=============
This package contains the pagelet layer. This layer supports a correct set of
component registration and can be used for inheritation in custom skins.
Right now the default implementation in Zope3 has different restriction in the
traversal concept and use to much registration on the default layer.
Important
---------
This layer supports the z3c.pagelet pattern. this means every page e.g. the
error page is based on the z3c.pagelet concept.
IPageletBrowserLayer
--------------------
The pagelet layer is useful for build custom presentation skins without access
to ZMI menus like zmi_views etc. This means there is no menu item registred if
you use this layer.
This layer is NOT derived from IDefaultBrowserLayer. Therefore it provides
only a minimal set of the most important public views such as @@absolute_url.
The following packages are accounted:
- zope.app.http.exception
- zope.app.publication
- zope.app.publisher.browser
- zope.app.traversing
- zope.app.traversing.browser
Testing
-------
For testing the IPageletBrowserLayer we use the testing skin defined in the
tests package which uses the IPageletBrowserLayer as the only base layer.
This means, that our testing skin provides only the views defined in the
minimal package and it's testing views defined in tests.
Login as manager first:
>>> from zope.testbrowser.testing import Browser
>>> manager = Browser()
>>> manager.addHeader('Authorization', 'Basic mgr:mgrpw')
Check if we can access the page.html view which is registred in the
ftesting.zcml file with our skin:
>>> manager = Browser()
>>> manager.addHeader('Authorization', 'Basic mgr:mgrpw')
>>> skinURL = 'http://localhost/++skin++MinimalTesting'
>>> manager.open(skinURL + '/page.html')
>>> manager.url
'http://localhost/++skin++MinimalTesting/page.html'
>>> print manager.contents
<!DOCTYPE...
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>TestingSkin</title>
</head>
<body>
test page
<BLANKLINE>
</body>
</html>
<BLANKLINE>
Now check the not found page which is a exception view on the exception
``zope.publisher.interfaces.INotFound``:
>>> manager.open(skinURL + '/foobar.html')
Traceback (most recent call last):
...
HTTPError: HTTP Error 404: Not Found
>>> print manager.contents
<!DOCTYPE...
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>TestingSkin</title>
</head>
<body>
<div>
<br />
<br />
<h3>
The page you are trying to access is not available
</h3>
<br />
<b>
Please try the following:
</b>
<br />
<ol>
<li>
Make sure that the Web site address is spelled correctly.
</li>
<li>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</li>
</ol>
</div>
<BLANKLINE>
</body>
</html>
<BLANKLINE>
And check the user error page which is a view registred for
``zope.exceptions.interfaces.IUserError`` exceptions:
>>> manager.open(skinURL + '/@@usererror.html')
>>> print manager.contents
<!DOCTYPE...
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>TestingSkin</title>
</head>
<body>
<div>
<div>simply user error</div>
</div>
<BLANKLINE>
</body>
</html>
<BLANKLINE>
And check error view registred for
``zope.interface.common.interfaces.IException``:
>>> manager.open(skinURL + '/@@systemerror.html')
>>> print manager.contents
<!DOCTYPE...
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>TestingSkin</title>
</head>
<body>
<div>
<br />
<br />
<h3>A system error occurred</h3>
<br />
<b>Please contact the administrator.</b>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</div>
<BLANKLINE>
</body>
</html>
<BLANKLINE>
And check the ``zope.security.interfaces.IUnauthorized`` view, use a new
unregistred user (test browser) for this:
>>> unauthorized = Browser()
>>> unauthorized.open(skinURL + '/@@forbidden.html')
Traceback (most recent call last):
...
HTTPError: HTTP Error 401: Unauthorized
>>> print unauthorized.contents
<!DOCTYPE...
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>TestingSkin</title>
</head>
<body>
<div>
<br />
<br />
<h3>Unauthorized</h3>
<br />
<b>You are not authorized.</b>
</div>
<BLANKLINE>
</body>
</html>
<BLANKLINE>
| z3c.layer | /z3c.layer-0.3.1.tar.gz/z3c.layer-0.3.1/src/z3c/layer/pagelet/README.txt | README.txt |
=============
Minimal layer
=============
This package contains the minimal layer. This layer supports a correct set of
component registration and can be used for inheritation in custom skins.
Right now the default implementation in Zope3 has different restriction in the
traversal concept and use to much registration on the default layer.
IMinimalBrowserLayer
--------------------
The minimal layer is useful for build custom presentation skins without access
to ZMI menus like zmi_views etc. This means there is no menu item registred if
you use this layer.
This layer is NOT derived from IDefaultBrowserLayer. Therefore it provides
only a minimal set of the most important public views such as @@absolute_url.
The following packages are accounted:
- zope.app.http.exception
- zope.app.publication
- zope.app.publisher.browser
- zope.app.traversing
- zope.app.traversing.browser
Testing
-------
For testing the IMinimalBrowserLayer we use the testing skin defined in the
tests package which uses the IMinimalBrowserLayer as the only base layer.
This means, that our testing skin provides only the views defined in the
minimal package and it's testing views defined in tests.
Login as manager first:
>>> from zope.testbrowser.testing import Browser
>>> manager = Browser()
>>> manager.addHeader('Authorization', 'Basic mgr:mgrpw')
Check if we can access the page.html view which is registred in the
ftesting.zcml file with our skin:
>>> manager = Browser()
>>> manager.addHeader('Authorization', 'Basic mgr:mgrpw')
>>> skinURL = 'http://localhost/++skin++MinimalTesting'
>>> manager.open(skinURL + '/page.html')
>>> manager.url
'http://localhost/++skin++MinimalTesting/page.html'
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<BLANKLINE>
test page
<BLANKLINE>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
Now check the not found page which is a exception view on the exception
``zope.publisher.interfaces.INotFound``:
>>> manager.open(skinURL + '/foobar.html')
Traceback (most recent call last):
...
HTTPError: HTTP Error 404: Not Found
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<br />
<br />
<h3>
The page you are trying to access is not available
</h3>
<br />
<b>
Please try the following:
</b>
<br />
<ol>
<li>
Make sure that the Web site address is spelled correctly.
</li>
<li>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</li>
</ol>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check the user error page which is a view registred for
``zope.exceptions.interfaces.IUserError`` exceptions:
>>> manager.open(skinURL + '/@@usererror.html')
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<div>simply user error</div>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check error view registred for
``zope.interface.common.interfaces.IException``:
>>> manager.open(skinURL + '/@@systemerror.html')
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<br />
<br />
<h3>A system error occurred</h3>
<br />
<b>Please contact the administrator.</b>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check the ``zope.security.interfaces.IUnauthorized`` view, use a new
unregistred user (test browser) for this:
>>> unauthorized = Browser()
>>> unauthorized.open(skinURL + '/@@forbidden.html')
Traceback (most recent call last):
...
HTTPError: HTTP Error 401: Unauthorized
>>> print unauthorized.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<BLANKLINE>
<h1>Unauthorized</h1>
<BLANKLINE>
<p>You are not authorized</p>
<BLANKLINE>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
| z3c.layer | /z3c.layer-0.3.1.tar.gz/z3c.layer-0.3.1/src/z3c/layer/minimal/README.txt | README.txt |
================================
Minimal Browser Layer for Zope 3
================================
This package contains the minimal layer. This layer supports a correct set of
component registration and can be used for inheritation in custom skins.
Right now the default implementation in Zope3 has different restriction in the
traversal concept and use to much registration on the default layer.
``IMinimalBrowserLayer`` Interface
----------------------------------
The minimal layer is useful for build custom presentation skins without access
to ZMI menus like `zmi_views` etc. This means there is no menu item registred
if you use this layer.
This layer is NOT derived from ``IDefaultBrowserLayer``. Therefore it provides
only a minimal set of the most important public views such as
``@@absolute_url``. The following packages are accounted:
- ``zope.app.http.exception``
- ``zope.app.publication``
- ``zope.app.publisher.browser``
- ``zope.app.traversing``
- ``zope.app.traversing.browser``
Testing
-------
For testing the ``IMinimalBrowserLayer`` layer we use the testing skin defined
in the tests package which uses the ``IMinimalBrowserLayer`` layer as the only
base layer. This means, that our testing skin provides only the views defined
in the minimal package and it's testing views defined in tests.
Login as manager first:
>>> from zope.testbrowser.testing import Browser
>>> manager = Browser()
>>> manager.addHeader('Authorization', 'Basic mgr:mgrpw')
Check if we can access the page.html view which is registred in the
ftesting.zcml file with our skin:
>>> manager = Browser()
>>> manager.addHeader('Authorization', 'Basic mgr:mgrpw')
>>> skinURL = 'http://localhost/++skin++MinimalTesting'
>>> manager.open(skinURL + '/page.html')
>>> manager.url
'http://localhost/++skin++MinimalTesting/page.html'
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<BLANKLINE>
test page
<BLANKLINE>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
Now check the not found page which is a exception view on the exception
``zope.publisher.interfaces.INotFound``:
>>> manager.open(skinURL + '/foobar.html')
Traceback (most recent call last):
...
HTTPError: HTTP Error 404: Not Found
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<br />
<br />
<h3>
The page you are trying to access is not available
</h3>
<br />
<b>
Please try the following:
</b>
<br />
<ol>
<li>
Make sure that the Web site address is spelled correctly.
</li>
<li>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</li>
</ol>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check the user error page which is a view registred for
``zope.exceptions.interfaces.IUserError`` exceptions:
>>> manager.open(skinURL + '/@@usererror.html')
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<div>simply user error</div>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check error view registred for
``zope.interface.common.interfaces.IException``:
>>> manager.open(skinURL + '/@@systemerror.html')
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<br />
<br />
<h3>A system error occurred</h3>
<br />
<b>Please contact the administrator.</b>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check the ``zope.security.interfaces.IUnauthorized`` view, use a new
unregistred user (test browser) for this:
>>> unauthorized = Browser()
>>> unauthorized.open(skinURL + '/@@forbidden.html')
Traceback (most recent call last):
...
HTTPError: HTTP Error 401: Unauthorized
>>> print unauthorized.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<BLANKLINE>
<h1>Unauthorized</h1>
<BLANKLINE>
<p>You are not authorized</p>
<BLANKLINE>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
| z3c.layer.minimal | /z3c.layer.minimal-1.2.1.tar.gz/z3c.layer.minimal-1.2.1/src/z3c/layer/minimal/README.txt | README.txt |
=======
CHANGES
=======
3.0 (2023-02-17)
----------------
- Add support for Python 3.8, 3.9, 3.10, 3.11.
- Drop support for Python 2.7, 3.4, 3.5, 3.6.
2.1 (2018-12-01)
----------------
- Add support for Python 3.5 up to 3.7.
- Drop support for Python 2.6 and 3.3.
- Drop the ability to run the tests using `python setup.py test`.
2.0.0 (2015-11-09)
------------------
- Standardize namespace __init__.
- Claim Python 3.4 support.
2.0.0a1 (2013-03-03)
--------------------
- Added support for Python 3.3.
- Changed ``zope.testbrowser`` tests to ``WebTest``, since ``zope.testbrowser``
is not yet ported.
- Replaced deprecated ``zope.interface.implements`` usage with equivalent
``zope.interface.implementer`` decorator.
- Dropped support for Python 2.4 and 2.5.
1.10.1 (2012-03-03)
-------------------
- Added adapter registration for `zope.browserresource.interfaces.IETag`
interface to be available on ``IPageletBrowserLayer``. This adapter is
necessary to deliver file resources.
1.10.0 (2012-02-23)
-------------------
- Sets HTTP status code to 500 on system errors but only in devmode and in
tests.
1.9.0 (2010-10-13)
------------------
- Re-release of 1.8.1 as the changes in it require a new major release
because they broke `z3c.authviewlet`.
1.8.2 (2010-10-13)
------------------
- Re-release of 1.8.0 as the changes in 1.8.1 require a new major
release because they break `z3c.authviewlet`.
1.8.1 (2010-10-11)
------------------
- Doing redirect in ``UnauthorizedPagelet`` now in ``update`` method instead
of ``render`` so the layout templage does not get rendered when
redirecting.
- Fixed tests: Using manager account, so anonymous user does not need to get
all permissions for running tests successfully.
- Got rid of `zope.app.testing` test dependency by using `zope.app.wsgi`.
- Got rid of `zope.app.authentication` test dependency.
- Added a test for ``403 Forbidden``.
1.8.0 (2010-08-20)
------------------
- Requiring `zope.login` so tests run with `zope.publisher` >= 3.12.
1.7.0 (2009-12-24)
------------------
- Added i18n domains to templates, so they can be translated. (Done
using `z3c.locales`.)
1.6.1 (2009-12-23)
------------------
- Moved `zope.browserresource` from test dependencies to install
dependencies as it is needed in the ZCML configuration.
1.6.0 (2009-11-30)
------------------
- Changed view for ``zope.publisher.interfaces.ITraversalException`` from
system error pagelet to not found pagelet.
- Moved authentication viewlets to `z3c.authviewlet`.
- Cleaned up dependencies, reflecting changes in zope packages.
- Cleaned up test dependencies.
1.5.0 (2009-05-28)
------------------
- Removed dependency on ``zope.app.exception`` by using
``zope.browser>=1.2`` and by implementing the exception view classes
directly instead of inheriting them (Quite nothing of the base
classes was in use here.)
- Removed not necessary test dependency on ``zope.app.twisted``.
- Removed no longer necessary test dependency on ``zope.app.component``.
1.4.0 (2009-03-16)
------------------
- Removed direct dependency on ``zope.app.security`` by using the new
packages ``zope.authentication`` and ``zope.principalregistry``.
- Removed not needed test-dependency on ``zope.app.zcmlfiles``.
- Fixed namespace package declaration in ``setup.py``.
1.3.0 (2009-03-13)
------------------
- Implemented login and logout using pagelets resp. viewlets.
- Updated tests to use new ``zope.configuration`` which containts the
exclude directive.
1.2.1 (2009-02-21)
------------------
- Release 1.2.0 was missing the test file for the security issue.
1.2.0 (2009-02-21)
------------------
- **Security issue:** The traverser defined for
``IPageletBrowserLayer`` was a trusted adapter, so the security
proxy got removed from each traversed object. Thus all sub-objects
were publically accessable, too.
1.1.0 (2009-02-14)
------------------
- Bugfix: use IContentTemplate instead of IPageTemplate which avoids to get the
layout template if no IPageTemplate is registered.
- Using ``zope.location.interfaces.ISite`` instead of
``zope.app.component.interfaces.ISite``.
- Using ``zope.container`` instead of ``zope.app.container``.
- Cleaned up dependencies.
1.0.2 (2009-04-03)
------------------
- backport release, see release date
- **Security issue:** The traverser defined for
``IPageletBrowserLayer`` was a trusted adapter, so the security
proxy got removed from each traversed object. Thus all sub-objects
were publically accessable, too.
Making this change might BREAK your application!
That means if security is not well declared.
- Bugfix: use IContentTemplate instead of IPageTemplate which avoids to get the
layout template if no IPageTemplate is registered
1.0.1 (2008-01-24)
------------------
- Bug: Update meta data.
1.0.0 (2008-01-21)
------------------
- Restructure: Move ``z3c.layer.pagelet`` package to it's own top level
package form ``z3c.layer`` to ``z3c.layer.pagelet``.
- Restructure: Removed ``zope.app.form`` support from pagelet layer.
0.2.3 (2007-11-07)
------------------
- Forward-Bug: Due to a bug in mechanize, the testbrowser throws
``httperror_seek_wrapper`` instead of ``HTTPError`` errors. Thanks to RE
normalizers, the code will now work whether the bug is fixed or not in
mechanize.
0.2.2 (2007-10-31)
------------------
- Bug: Fixed package meta-data.
- Bug: Fixed test failures due to depency updates.
- Restructure: Fixed deprecation warning for ``ZopeSecurityPolicy``.
0.2.1 (2007-??-??)
------------------
- Changes unknown.
0.2.0 (2007-??-??)
------------------
- Initial release.
| z3c.layer.pagelet | /z3c.layer.pagelet-3.0.tar.gz/z3c.layer.pagelet-3.0/CHANGES.rst | CHANGES.rst |
.. image:: https://img.shields.io/pypi/v/z3c.layer.pagelet.svg
:target: https://pypi.org/project/z3c.layer.pagelet/
:alt: Latest Version
.. image:: https://img.shields.io/pypi/pyversions/z3c.layer.pagelet.svg
:target: https://pypi.org/project/z3c.layer.pagelet/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/z3c.layer.pagelet/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/z3c.layer.pagelet/actions/workflows/tests.yml
:alt: Build Status
.. image:: https://coveralls.io/repos/github/zopefoundation/z3c.layer.pagelet/badge.svg
:target: https://coveralls.io/github/zopefoundation/z3c.layer.pagelet
:alt: Code Coverage
This package provides a pagelet based layer setup for Zope3.
| z3c.layer.pagelet | /z3c.layer.pagelet-3.0.tar.gz/z3c.layer.pagelet-3.0/README.rst | README.rst |
==============================
Pagelet-based Layer for Zope 3
==============================
This package contains the pagelet layer. This layer supports a correct set of
component registration and can be used for inheritation in custom skins.
Right now the default implementation in Zope3 has different restriction in the
traversal concept and use to much registration on the default layer.
Important
---------
This layer ia based on the pagelet pattern. This means every page e.g. the
error page is based on the pagelet concept.
``IPageletBrowserLayer`` Layer
------------------------------
The pagelet layer is useful for build custom presentation skins without access
to ZMI menus like ``zmi_views`` etc. This means there is no menu item
registred if you use this layer.
This layer is *NOT* derived from ``IDefaultBrowserLayer`` layer. Therefore it
provides only a minimal set of the most important public views such as
``@@absolute_url`` which get registered in zope packages for the IHTTPRequest
and IBrowserRequest. Next to this views, this package will only provide error
views and traversers which are normaly regsitered in the following zope
packages:
- ``zope.app.http.exception``
- ``zope.app.publication``
- ``zope.browserresource``
- ``zope.traversing``
Note, this package does not depend on all the packages described above. We only
need to depend on the same interfaces where this package will define views and
traversers for.
Testing
-------
For testing the ``IPageletBrowserLayer`` layer we use the testing skin defined
in the tests package which uses the ``IPageletBrowserLayer`` layer as the only
base layer. This means, that our testing skin provides only the views defined
in the minimal package and it's testing views defined in tests.
Login as manager first:
>>> from webtest.app import TestApp
>>> manager = TestApp(
... make_wsgi_app(), extra_environ={
... 'wsgi.handleErrors': False,
... 'HTTP_AUTHORIZATION': 'Basic mgr:mgrpw'})
Check if we can access the ``page.html`` view which is registred in the
``ftesting.zcml`` file with our skin:
>>> skinURL = 'http://localhost/++skin++PageletTestSkin'
>>> res = manager.get(skinURL + '/page.html')
>>> res.request.url
'http://localhost/++skin++PageletTestSkin/page.html'
>>> print(res.html)
<!DOCTYPE...
<html ...>
<head>
<title>PageletTestLayout</title>
</head>
<body>
test page
<BLANKLINE>
</body>
</html>
<BLANKLINE>
Not Found
~~~~~~~~~
Now check the not found page which is a exception view on the exception
``zope.publisher.interfaces.INotFound``:
>>> err_manager = TestApp(
... make_wsgi_app(), extra_environ={
... 'HTTP_AUTHORIZATION': 'Basic mgr:mgrpw'})
>>> res = err_manager.get(skinURL + '/foobar.html', status=404)
>>> print(res.html)
<!DOCTYPE...
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<br/>
<br/>
<h3>
The page you are trying to access is not available
</h3>
<br/>
<b>
Please try the following:
</b>
<br/>
<ol>
<li>
Make sure that the Web site address is spelled correctly.
</li>
<li>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</li>
</ol>
</div>
<BLANKLINE>
</body>
</html>
<BLANKLINE>
User error
~~~~~~~~~~
And check the user error page which is a view registred for
``zope.exceptions.interfaces.IUserError`` exceptions:
>>> manager.get(skinURL + '/@@usererror.html')
Traceback (most recent call last):
...
zope.exceptions.interfaces.UserError: simply user error
>>> res = err_manager.get(skinURL + '/@@usererror.html')
>>> print(res.html)
<!DOCTYPE ...
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<div>simply user error</div>
</div>
<BLANKLINE>
</body>
</html>
<BLANKLINE>
Common exception (system error)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
And check error view registred for
``zope.interface.common.interfaces.IException``, it sets the HTTP status
code to 500 if called during tests or if development mode is switched on:
>>> res = manager.get(skinURL + '/@@systemerror.html')
Traceback (most recent call last):
...
Exception: simply system error
>>> res = err_manager.get(skinURL + '/@@systemerror.html', status=500)
>>> print(res.html)
<!DOCTYPE...
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<br/>
<br/>
<h3>A system error occurred</h3>
<br/>
<b>Please contact the administrator.</b>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</div>
<BLANKLINE>
</body>
</html>
<BLANKLINE>
Unauthorized
~~~~~~~~~~~~
To check the ``zope.security.interfaces.IUnauthorized`` view, we use a
new unregistred user (test browser). As we have defined an
unauthenticatedPrincipal in ZCML (see tests/ftesting.zcml) ``401
Unauthorized`` is returned instead of ``403 Forbidden`` which would
show up otherwise:
>>> unauthorized = TestApp(make_wsgi_app())
>>> res = unauthorized.get(skinURL + '/@@forbidden.html', status=401)
>>> print(res.html)
<!DOCTYPE ...
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<br/>
<br/>
<h3>Unauthorized</h3>
<br/>
<b>You are not authorized.</b>
</div>
</body>
</html>
Forbidden
~~~~~~~~~
When an authorized user tries to access a URL where he does not have enough
permissions he gets a ``403 Forbidden``, the displayed page contents are the
same like ``401 Unauthorized``. When an authentication utility is registered
it might display a log-in form:
>>> authorized = TestApp(
... make_wsgi_app(), extra_environ={
... 'HTTP_AUTHORIZATION': 'Basic mgr:mgrpw'})
>>> res = authorized.get(skinURL + '/@@forbidden.html', status=403)
>>> print(res.html)
<!DOCTYPE ...
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<br/>
<br/>
<h3>Unauthorized</h3>
<br/>
<b>You are not authorized.</b>
</div>
</body>
</html>
| z3c.layer.pagelet | /z3c.layer.pagelet-3.0.tar.gz/z3c.layer.pagelet-3.0/src/z3c/layer/pagelet/README.rst | README.rst |
"""Browser Code.
"""
import z3c.pagelet.browser
import z3c.template.interfaces
import zope.authentication.interfaces
import zope.component
import zope.interface
from z3c.layer.pagelet import interfaces
def inDevMode():
"""Are we are running in debug mode? Can error messages be more telling?"""
try:
from zope.app.appsetup.appsetup import getConfigContext
except ImportError:
# We are outside a Zope 3 context, so let's play safe:
return False
config_context = getConfigContext()
if config_context is None:
# We are probably inside a test:
return True
return config_context.hasFeature('devmode')
@zope.interface.implementer(interfaces.ISystemErrorPagelet)
class SystemErrorPagelet(z3c.pagelet.browser.BrowserPagelet):
"""SystemError pagelet."""
def update(self):
if inDevMode():
self.request.response.setStatus(500)
def isSystemError(self):
return True
@zope.interface.implementer(interfaces.IUnauthorizedPagelet)
class UnauthorizedPagelet(z3c.pagelet.browser.BrowserPagelet):
"""Unauthorized pagelet."""
def update(self):
# Set the error status to 403 (Forbidden) in the case when we don't
# challenge the user
self.request.response.setStatus(403)
# make sure that squid does not keep the response in the cache
self.request.response.setHeader(
'Expires', 'Mon, 26 Jul 1997 05:00:00 GMT')
self.request.response.setHeader(
'Cache-Control', 'no-store, no-cache, must-revalidate')
self.request.response.setHeader('Pragma', 'no-cache')
principal = self.request.principal
auth = zope.component.getUtility(
zope.authentication.interfaces.IAuthentication)
auth.unauthorized(principal.id, self.request)
def render(self):
if self.request.response.getStatus() not in (302, 303):
template = zope.component.getMultiAdapter(
(self, self.request), z3c.template.interfaces.IContentTemplate)
return template(self)
@zope.interface.implementer(interfaces.IUserErrorPagelet)
class UserErrorPagelet(z3c.pagelet.browser.BrowserPagelet):
"""UserError pagelet."""
def title(self):
return self.context.__class__.__name__
@zope.interface.implementer(interfaces.INotFoundPagelet)
class NotFoundPagelet(z3c.pagelet.browser.BrowserPagelet):
"""NotFound pagelet."""
def render(self):
self.request.response.setStatus(404)
template = zope.component.getMultiAdapter(
(self, self.request), z3c.template.interfaces.IContentTemplate)
return template(self) | z3c.layer.pagelet | /z3c.layer.pagelet-3.0.tar.gz/z3c.layer.pagelet-3.0/src/z3c/layer/pagelet/browser/__init__.py | __init__.py |
"""Custom Output Checker
"""
import doctest as pythondoctest
import re
import lxml.doctestcompare
import lxml.etree
from lxml.doctestcompare import LHTMLOutputChecker
from zope.testing.renormalizing import RENormalizing
class OutputChecker(LHTMLOutputChecker, RENormalizing):
"""Doctest output checker which is better equippied to identify
HTML markup than the checker from the ``lxml.doctestcompare``
module. It also uses the text comparison function from the
built-in ``doctest`` module to allow the use of ellipsis.
Also, we need to support RENormalizing.
"""
_repr_re = re.compile(
r'^<([A-Z]|[^>]+ (at|object) |[a-z]+ \'[A-Za-z0-9_.]+\'>)')
def __init__(self, doctest=pythondoctest, patterns=()):
RENormalizing.__init__(self, patterns)
self.doctest = doctest
# make sure these optionflags are registered
doctest.register_optionflag('PARSE_HTML')
doctest.register_optionflag('PARSE_XML')
doctest.register_optionflag('NOPARSE_MARKUP')
def _looks_like_markup(self, s):
s = s.replace('<BLANKLINE>', '\n').strip()
return (s.startswith('<')
and not self._repr_re.search(s))
def text_compare(self, want, got, strip):
if want is None:
want = ""
if got is None:
got = ""
checker = self.doctest.OutputChecker()
return checker.check_output(
want, got,
self.doctest.ELLIPSIS | self.doctest.NORMALIZE_WHITESPACE)
def check_output(self, want, got, optionflags):
if got == want:
return True
for transformer in self.transformers:
want = transformer(want)
got = transformer(got)
return LHTMLOutputChecker.check_output(self, want, got, optionflags)
def output_difference(self, example, got, optionflags):
want = example.want
if not want.strip():
return LHTMLOutputChecker.output_difference(
self, example, got, optionflags)
# Dang, this isn't as easy to override as we might wish
original = want
for transformer in self.transformers:
want = transformer(want)
got = transformer(got)
# temporarily hack example with normalized want:
example.want = want
result = LHTMLOutputChecker.output_difference(
self, example, got, optionflags)
example.want = original
return result
def get_parser(self, want, got, optionflags):
NOPARSE_MARKUP = self.doctest.OPTIONFLAGS_BY_NAME.get(
"NOPARSE_MARKUP", 0)
PARSE_HTML = self.doctest.OPTIONFLAGS_BY_NAME.get(
"PARSE_HTML", 0)
PARSE_XML = self.doctest.OPTIONFLAGS_BY_NAME.get(
"PARSE_XML", 0)
parser = None
if NOPARSE_MARKUP & optionflags:
return None
if PARSE_HTML & optionflags:
parser = lxml.doctestcompare.html_fromstring
elif PARSE_XML & optionflags:
parser = lxml.etree.XML
elif (want.strip().lower().startswith('<html')
and got.strip().startswith('<html')):
parser = lxml.doctestcompare.html_fromstring
elif (self._looks_like_markup(want)
and self._looks_like_markup(got)):
parser = self.get_default_parser()
return parser | z3c.layer.ready2go | /z3c.layer.ready2go-2.0.tar.gz/z3c.layer.ready2go-2.0/src/z3c/layer/ready2go/outputchecker.py | outputchecker.py |
===========================
Ready-2-Go Layer for Zope 3
===========================
This package contains the `ready2go` layer. This layer supports a correct set of
component registration and can be used for inheritation in custom skins.
Important
---------
This layer supports the ``z3c.pagelet`` and the ``z3c.form`` pattern. This
means every page e.g. the error page is based on the ``z3c.pagelet``
concept. By default we use the ``<div>``-based layout for z3c forms.
``IReady2GoBrowserLayer`` Layer
-------------------------------
The `ready2go` layer is useful for build custom presentation skins without
access to ZMI menus like ``zmi_views`` etc. This means there is no menu item
registred if you use this layer.
For more information about what this layer offers, see ``z3c.layer.pagelet``.
Testing
-------
For testing the ``IReady2GoBrowserLayer`` layer we use the testing skin
defined in the tests package which uses the ``IReady2GoBrowserLayer`` layer as
the only base layer. This means, that our testing skin provides only the
views defined in the minimal package and it's testing views defined in tests.
Login as manager first:
>>> from webtest.app import TestApp
>>> manager = TestApp(
... make_wsgi_app(), extra_environ={
... 'wsgi.handleErrors': False,
... 'HTTP_AUTHORIZATION': 'Basic mgr:mgrpw'})
>>> err_manager = TestApp(
... make_wsgi_app(), extra_environ={
... 'HTTP_AUTHORIZATION': 'Basic mgr:mgrpw'})
Check if we can access the ``page.html`` view which is registred in the
``ftesting.zcml`` file with our skin:
>>> skinURL = 'http://localhost/++skin++Ready2GoTestSkin'
>>> res = manager.get(skinURL + '/page.html')
>>> res.request.url
'http://localhost/++skin++Ready2GoTestSkin/page.html'
Pagelet support
---------------
Check if we can access the test page given from the ``z3c.layer.pagelet``
``ftesting.zcml`` configuration.
>>> print(res.html) #doctest: +PARSE_HTML
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
test page
</body>
</html>
Not Found
~~~~~~~~~
Now check the not found page which is a exception view on the exception
``zope.publisher.interfaces.INotFound``:
>>> manager.get(skinURL + '/foobar.html')
Traceback (most recent call last):
...
NotFound: Object: <zope.site.folder.Folder ...>, name: 'foobar.html'
>>> res = err_manager.get(skinURL + '/foobar.html', status=404)
>>> print(res.html)
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<br />
<br />
<h3>
The page you are trying to access is not available
</h3>
<br />
<b>
Please try the following:
</b>
<br />
<ol>
<li>
Make sure that the Web site address is spelled correctly.
</li>
<li>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</li>
</ol>
</div>
</body>
</html>
User error
~~~~~~~~~~
And check the user error page which is a view registred for
``zope.exceptions.interfaces.IUserError`` exceptions:
>>> res = err_manager.get(skinURL + '/@@usererror.html')
>>> print(res.html)
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<div>simply user error</div>
</div>
</body>
</html>
Common exception (system error)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
And check error view registred for
``zope.interface.common.interfaces.IException``:
>>> res = err_manager.get(skinURL + '/@@systemerror.html', status=500)
>>> print(res.html)
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<br />
<br />
<h3>A system error occurred</h3>
<br />
<b>Please contact the administrator.</b>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</div>
</body>
</html>
Forbidden 403
~~~~~~~~~~~~~
And check the ``zope.security.interfaces.IUnauthorized`` view, use a new
unregistred user (test browser) for this.
>>> unauthorized = TestApp(make_wsgi_app())
>>> unauthorized.get(skinURL + '/@@forbidden.html')
Traceback (most recent call last):
...
AppError: Bad response: 403 Forbidden
>>> res = unauthorized.get(skinURL + '/@@forbidden.html', status=403)
>>> print(res.html)
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<br />
<br />
<h3>Unauthorized</h3>
<br />
<b>You are not authorized.</b>
</div>
</body>
</html>
As you can see, this test will return a 403 Forbidden error. But this is only
because we do not have an unauthenticated principal available. See the test
below what happens if we register an unauthenticated princiapl.
Unauthorized 401
~~~~~~~~~~~~~~~~
If we use an authenticated principal and access the forbitten page, we will get
a 401 Unauthorized instead of a 403 Forbidden error page.
>>> from zope.configuration import xmlconfig
>>> import zope.principalregistry
>>> def zcml(s):
... context = xmlconfig.file('meta.zcml', zope.principalregistry)
... xmlconfig.string(s, context)
>>> zcml("""
... <configure
... xmlns="http://namespaces.zope.org/zope"
... >
...
... <unauthenticatedPrincipal
... id="zope.unknown"
... title="Anonymous user"
... description="A person we don't know"
... />
...
... </configure>
... """)
>>> manager2 = TestApp(make_wsgi_app(), extra_environ={
... 'wsgi.handleErrors': True})
>>> res = manager2.get(skinURL + '/@@forbidden.html')
Traceback (most recent call last):
...
AppError: Bad response: 401 Unauthorized
>>> res = manager2.get(skinURL + '/@@forbidden.html', status=401)
>>> print(res.html)
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PageletTestLayout</title>
</head>
<body>
<div>
<br />
<br />
<h3>Unauthorized</h3>
<br />
<b>You are not authorized.</b>
</div>
</body>
</html>
Form and form layout support
----------------------------
This layer offers also form macros given from ``z3c.formui``. Let's create a
simple form:
>>> from z3c.form import testing
>>> testing.setupFormDefaults()
Before we can start writing forms, we must have the content to work with:
>>> import zope.interface
>>> import zope.schema
>>> class IPerson(zope.interface.Interface):
...
... name = zope.schema.TextLine(
... title='Name',
... required=True)
...
... age = zope.schema.Int(
... title='Age',
... description=u"The person's age.",
... min=0,
... default=20,
... required=False)
>>> from zope.schema.fieldproperty import FieldProperty
>>> @zope.interface.implementer(IPerson)
... class Person(object):
... name = FieldProperty(IPerson['name'])
... age = FieldProperty(IPerson['age'])
...
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
... def __repr__(self):
... return '<%s %r>' % (self.__class__.__name__, self.name)
Okay, that should suffice for now. Let's now create a working add form:
>>> from z3c.form import field
>>> from z3c.formui import form, layout
>>> class PersonAddForm(form.AddForm):
...
... fields = field.Fields(IPerson)
...
... def create(self, data):
... return Person(**data)
...
... def add(self, object):
... self.context[object.id] = object
...
... def nextURL(self):
... return 'index.html'
Let's create a request:
>>> from z3c.form.testing import TestRequest
>>> from zope.interface import alsoProvides
>>> divRequest = TestRequest()
And support the div form layer for our request:
>>> from z3c.formui.interfaces import IDivFormLayer
>>> alsoProvides(divRequest, IDivFormLayer)
Now create the form:
>>> root = getRootFolder()
>>> addForm = PersonAddForm(root, divRequest)
Since we have not specified a template yet, we have to do this now. We use our
div based form template:
>>> import os
>>> import z3c.formui
>>> divFormTemplate = os.path.join(os.path.dirname(z3c.formui.__file__),
... 'div-form.pt')
>>> from z3c.template.template import TemplateFactory
>>> divFormFactory = TemplateFactory(divFormTemplate, 'text/html')
Now register the form (content) template:
>>> import zope.interface
>>> import zope.component
>>> from z3c.template.interfaces import IContentTemplate
>>> zope.component.provideAdapter(divFormFactory,
... (zope.interface.Interface, IDivFormLayer),
... IContentTemplate)
And let's define a layout template which simply calls the render method. For a
more adavanced content/layout render concept see ``z3c.pagelet``.
>>> import tempfile
>>> temp_dir = tempfile.mkdtemp()
>>> myLayout = os.path.join(temp_dir, 'myLayout.pt')
>>> with open(myLayout, 'w') as file:
... _ = file.write('''<html>
... <body>
... <tal:block content="structure view/render">
... content
... </tal:block>
... </body>
... </html>''')
>>> myLayoutFactory = TemplateFactory(myLayout, 'text/html')
>>> from z3c.template.interfaces import ILayoutTemplate
>>> zope.component.provideAdapter(myLayoutFactory,
... (zope.interface.Interface, zope.interface.Interface), ILayoutTemplate)
Now we can get our layout template:
>>> layout = zope.component.getMultiAdapter((addForm, divRequest),
... ILayoutTemplate)
>>> layout
<zope.browserpage.viewpagetemplatefile.ViewPageTemplateFile object at ...>
DIV-based Layout
----------------
Let's now render the page. Note the output doesn't contain the layout template:
>>> addForm.update()
>>> print(addForm.render())
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="form" name="form">
<div class="viewspace">
<div class="required-info">
<span class="required">*</span>– required
</div>
<div>
<div id="form-widgets-name-row" class="row required">
<div class="label">
<label for="form-widgets-name">
<span>Name</span>
<span class="required">*</span>
</label>
</div>
<div class="widget">
<input id="form-widgets-name" name="form.widgets.name"
class="text-widget required textline-field"
value="" type="text" />
</div>
</div>
<div id="form-widgets-age-row" class="row">
<div class="label">
<label for="form-widgets-age">
<span>Age</span>
</label>
</div>
<div class="widget">
<input id="form-widgets-age" name="form.widgets.age"
class="text-widget int-field"
value="20" type="text" />
</div>
</div>
</div>
</div>
<div>
<div class="buttons">
<input id="form-buttons-add" name="form.buttons.add"
class="submit-widget button-field" value="Add" type="submit" />
</div>
</div>
</form>
Form Macros
-----------
Try at least to load the confguration, which will make sure that all macros
get registered correctly.
>>> from zope.configuration import xmlconfig
>>> import zope.component
>>> import zope.security
>>> import zope.viewlet
>>> import zope.browserpage
>>> import zope.browserresource
>>> import z3c.macro
>>> import z3c.template
>>> import z3c.formui
>>> xmlconfig.XMLConfig('meta.zcml', zope.browserpage)()
>>> xmlconfig.XMLConfig('meta.zcml', zope.browserresource)()
>>> xmlconfig.XMLConfig('meta.zcml', zope.component)()
>>> xmlconfig.XMLConfig('meta.zcml', zope.security)()
>>> xmlconfig.XMLConfig('meta.zcml', zope.viewlet)()
>>> xmlconfig.XMLConfig('meta.zcml', z3c.macro)()
>>> xmlconfig.XMLConfig('meta.zcml', z3c.template)()
>>> xmlconfig.XMLConfig('configure.zcml', z3c.formui)()
Div layout macros
-----------------
Now we can see that we have different form macros available:
>>> from z3c.macro.interfaces import IMacroTemplate
>>> objects = (None, addForm, divRequest)
>>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form')
[...div-form.pt'), ...metal:define-macro': 'form'...
>>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'subform')
[...div-form.pt'), ...define-macro': 'subform'...
>>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-label')
[...div-form.pt'), ...define-macro': 'label'...
>>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-required-info')
[...div-form.pt'), ...define-macro', 'required-info'...
>>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-header')
[...div-form.pt'), ...define-macro': 'header'...
>>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-errors')
[...div-form.pt'), ...define-macro': 'errors'...
>>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'widget-rows')
[...div-form.pt'), ...define-macro': 'widget-rows'...
>>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'widget-row')
[...div-form.pt'), ...define-macro': 'widget-row'...
>>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-groups')
[...div-form.pt'), ...define-macro': 'groups'...
>>> zope.component.getMultiAdapter(objects, IMacroTemplate, 'form-buttons')
[...div-form.pt'), ...define-macro', 'buttons'...
Cleanup
-------
>>> import shutil
>>> shutil.rmtree(temp_dir)
| z3c.layer.ready2go | /z3c.layer.ready2go-2.0.tar.gz/z3c.layer.ready2go-2.0/src/z3c/layer/ready2go/README.txt | README.txt |
======
README
======
This package contains the trusted layer. This layer support a correct set of
component registration and can be used for inheritation in custom skins.
The ITrustedBrowserLayer supports the same registration set like the
IMinimalBrowserLayer. The only difference is, that the trusted layer offers
trusted traversal adapters. This means a skin using this layer can traverse
over a PAU (pluggable IAuthentication utility) without to run into a
Unautorized exception.
For more information see also the README.txt in z3c.layer.minimal.
Testing
-------
For testing the ITrustedBrowserLayer we use the testing skin defined in the
tests package which uses the ITrustedBrowserLayer. This means, that our
testing skin provides also the views defined in the minimal package
and it's testing views defined in the minimal tests.
Login as manager first:
>>> from zope.testbrowser.testing import Browser
>>> manager = Browser()
>>> manager.addHeader('Authorization', 'Basic mgr:mgrpw')
Check if we can access the public page.html view which is registred in the
ftesting.zcml file with our skin:
>>> skinURL = 'http://localhost/++skin++TrustedTesting'
>>> manager.open(skinURL + '/page.html')
>>> manager.url
'http://localhost/++skin++TrustedTesting/page.html'
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<BLANKLINE>
test page
<BLANKLINE>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
Now check the not found page which is a exception view on the exception
``zope.publisher.interfaces.INotFound``:
>>> manager.open(skinURL + '/foobar.html')
Traceback (most recent call last):
...
HTTPError: HTTP Error 404: Not Found
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<br />
<br />
<h3>
The page you are trying to access is not available
</h3>
<br />
<b>
Please try the following:
</b>
<br />
<ol>
<li>
Make sure that the Web site address is spelled correctly.
</li>
<li>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</li>
</ol>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check the user error page which is a view registred for
``zope.exceptions.interfaces.IUserError`` exceptions:
>>> manager.open(skinURL + '/@@usererror.html')
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<div>simply user error</div>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check error view registred for
``zope.interface.common.interfaces.IException``:
>>> manager.open(skinURL + '/@@systemerror.html')
>>> print manager.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<br />
<br />
<h3>A system error occurred</h3>
<br />
<b>Please contact the administrator.</b>
<a href="javascript:history.back(1);">
Go back and try another URL.
</a>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
And check the ``zope.security.interfaces.IUnauthorized`` view, use a new
unregistred user (test browser) for this:
>>> unauthorized = Browser()
>>> unauthorized.open(skinURL + '/@@forbidden.html')
Traceback (most recent call last):
...
HTTPError: HTTP Error 401: Unauthorized
>>> print unauthorized.contents
<BLANKLINE>
<html>
<head>
<title>testing</title>
</head>
<body>
<div>
<BLANKLINE>
<h1>Unauthorized</h1>
<BLANKLINE>
<p>You are not authorized</p>
<BLANKLINE>
</div>
</body>
</html>
<BLANKLINE>
<BLANKLINE>
When an object gets traversed, its security proxy is removed, so its
sub-objects can be publically accessed, too:
>>> import zope.site.folder
>>> getRootFolder()['test'] = zope.site.folder.Folder()
>>> manager.open(skinURL + '/container_contents.html')
The view displays the types of the content objects inside the root
folder. The content objects are not security proxied:
>>> print manager.contents
[<class 'zope.site.folder.Folder'>] | z3c.layer.trusted | /z3c.layer.trusted-1.1.0.tar.gz/z3c.layer.trusted-1.1.0/src/z3c/layer/trusted/README.txt | README.txt |
HTML layout engine
==================
This package implements a page rendering model based on a static HTML
document that is made dynamic from the outside by mapping content
provider definitions to locations in the HTML document tree. This is
called a "layout".
The component architecture is utilized to provide extension points
that allow wide application. Two-phase rendering is supported using
the ``zope.contentprovider`` rendering scheme (update/render).
Static resources, as referenced by the HTML document (images,
stylesheets and javascript files) are included carbon copy and
published as browser resources (see ``zope.app.publisher.browser``).
Benefits:
* No template language required
* Support for two-phase rendering
* Integrates with creative workflow
* Flexible extension points
| z3c.layout | /z3c.layout-0.2.tar.gz/z3c.layout-0.2/README.txt | README.txt |
Walk-through
============
Layouts and regions
-------------------
Let's begin by instantiating a layout. We'll do this manually for the
sake of this demonstration; usually this is done using the included
ZCML-directive <browser:layout>.
>>> from z3c.layout.model import Layout
>>> layout = Layout(
... "test", "%s/templates/default/index.html" % test_path, "test")
Register resource directory.
>>> import zope.configuration.config as config
>>> context = config.ConfigurationMachine()
>>> from zope.app.publisher.browser import resourcemeta
>>> resourcemeta.resourceDirectory(
... context, "test", "%s/templates/default" % test_path)
>>> context.execute_actions()
Layouts are made dynamic by defining one or more regions. They are
mapped to HTML locations using an xpath-expression and an insertion
mode, which is one of "replace", "append", "prepend", "before" or
"after".
Regions can specify the name of a content provider directly or it may
rely on adaptation to yield a content provider component. We'll
investigate both of these approaches:
>>> from z3c.layout.model import Region
First we define a title region where we directly specify the name of a
content provider.
>>> title = Region("title", ".//title", title=u"Title", provider="title")
Then a content region where we leave it the content provider to
component adaptation.
>>> content = Region("content", ".//div", "Content")
To register them with the layout we simply add them.
>>> layout.regions.add(title)
>>> layout.regions.add(content)
Let's define a context class.
>>> class MockContext(object):
... interface.implements(interface.Interface)
We need to provide a general adapter that can provide content
providers for regions that do not specify them directly. As an
example, we'll define an adapter that simply tries to lookup a content
provider with the same name as the region.
>>> from z3c.layout.interfaces import IContentProviderFactory
>>> class EponymousContentProviderFactory(object):
... interface.implements(IContentProviderFactory)
...
... def __init__(self, region):
... self.region = region
...
... def __call__(self, context, request, view):
... name = self.region.name
... return component.getMultiAdapter(
... (view.context, request, view), IContentProvider, name)
>>> from z3c.layout.interfaces import IRegion
>>> component.provideAdapter(
... EponymousContentProviderFactory, (IRegion,))
Rendering
---------
Before we can render the layout, we need to register content providers
for the two regions. We'll use a mock class for demonstration.
>>> from zope.contentprovider.interfaces import IContentProvider
>>> class MockContentProvider(object):
... interface.implements(IContentProvider)
...
... __name__ = u""
...
... def __init__(self, *args):
... pass
...
... def update(self):
... pass
...
... def render(self):
... return self.__name__
...
... def __repr__(self):
... return "<MockContentProvider '%s'>" % self.__name__
>>> from zope.publisher.interfaces.browser import IBrowserRequest
>>> from zope.publisher.interfaces.browser import IBrowserView
>>> component.provideAdapter(
... MockContentProvider, (MockContext, IBrowserRequest, IBrowserView),
... name="title")
>>> component.provideAdapter(
... MockContentProvider, (MockContext, IBrowserRequest, IBrowserView),
... name="content")
Let's instantiate the layout browser-view. We must define a context
and set up a request.
>>> from zope.publisher.browser import TestRequest
>>> context = MockContext()
>>> request = TestRequest()
We need to have the request be annotatable.
>>> from zope.annotation.attribute import AttributeAnnotations
>>> component.provideAdapter(
... AttributeAnnotations, (TestRequest,))
The view expects the context to adapt to ``ILayout``.
>>> from z3c.layout.interfaces import ILayout
>>> component.provideAdapter(
... lambda context: layout, (MockContext,), ILayout)
>>> from z3c.layout.browser.layout import LayoutView
>>> view = LayoutView(context, request)
Verify that the layout view is able to get to these providers.
>>> view.mapping
{'content':
(<Region 'content' .//div (replace) None>, <MockContentProvider 'content'>),
'title':
(<Region 'title' .//title (replace) 'title'>, <MockContentProvider 'title'>)}
Now for the actual output.
>>> print view()
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="test/main.css" type="text/css" media="screen">
<title>title</title>
</head>
<body>
<div id="content">content</div>
</body>
</html>
Transforms
----------
To support special cases where you need to use Python to transform the
static HTML document at compile time, one or more transforms may be
defined.
>>> from z3c.layout.model import Transform
Let's add a transform that adds a language setting to the <html>-tag.
>>> def set_language(node):
... node.attrib["lang"] = "en"
>>> layout.transforms.add(
... Transform(set_language))
>>> layout.parse().getroot().attrib["lang"]
'en'
And another transform that assigns a class to the <body>-tag.
>>> def set_class(node, value):
... node.attrib["class"] = value
>>> layout.transforms.add(
... Transform(lambda body: set_class(body, "front-page"), ".//body"))
>>> layout.parse().xpath('.//body')[0].attrib["class"]
'front-page'
| z3c.layout | /z3c.layout-0.2.tar.gz/z3c.layout-0.2/src/z3c/layout/README.txt | README.txt |
def insert(tree, region, provided):
# look up insertion method
try:
insert = _map[region.mode]
except KeyError:
raise ValueError("Invalid mode: %s" % repr(region.mode))
# insert provided content into nodes
nodes = tree.xpath(region.xpath)
for node in nodes:
insert(node, provided)
def replace(node, provided):
"""Replace node with contents.
>>> from lxml import html
>>> tree = html.fromstring('<div>abc</div>')
>>> from z3c.layout.browser.insertion import replace
>>> replace(tree, html.fromstring('<div>def</div>'))
>>> html.tostring(tree)
'<div>def</div>'
"""
del node[:]
if provided.text:
node.text = provided.text
node.extend(tuple(provided))
def prepend(node, provided):
"""Prepend contents to node.
>>> from lxml import html
>>> tree = html.fromstring('<div>abc<span>def</span></div>')
>>> from z3c.layout.browser.insertion import prepend
>>> prepend(tree, html.fromstring('<div>ghi<p>jkl</p></div>'))
>>> html.tostring(tree)
'<div>ghiabc<p>jkl</p><span>def</span></div>'
"""
if provided.text:
node.text = provided.text + node.text or ""
for element in reversed(provided):
node.insert(0, element)
def append(node, provided):
"""Append contents to node.
>>> from lxml import html
>>> tree = html.fromstring('<div><span>abc</span>def</div>')
>>> from z3c.layout.browser.insertion import append
>>> append(tree, html.fromstring('<div>ghi<p>jkl</p></div>'))
>>> html.tostring(tree)
'<div><span>abc</span>defghi<p>jkl</p></div>'
"""
if provided.text and len(node) > 0:
last = node[-1]
last.tail = (last.tail or "") + provided.text
for element in reversed(provided):
node.append(element)
def before(node, provided):
"""Add contents before node.
>>> from lxml import html
>>> tree = html.fromstring('<div><span>abc</span>def<span>ghi</span></div>')
>>> from z3c.layout.browser.insertion import before
>>> before(tree.xpath('.//span')[1], html.fromstring('<div>jkl<p>mno</p>pqr</div>'))
>>> html.tostring(tree)
'<div><span>abc</span>defjkl<p>mno</p>pqr<span>ghi</span></div>'
"""
prev = node.getprevious()
if prev is not None and provided.text:
prev.tail = (prev.tail or "") + provided.text
for element in reversed(provided):
node.addprevious(element)
def after(node, provided):
"""Add contents after node.
>>> from lxml import html
>>> tree = html.fromstring('<div><span>abc</span>def<span>ghi</span></div>')
>>> from z3c.layout.browser.insertion import after
>>> after(tree.xpath('.//span')[0], html.fromstring('<div>jkl<p>mno</p>pqr</div>'))
>>> html.tostring(tree)
'<div><span>abc</span>jkl<p>mno</p>pqrdef<span>ghi</span></div>'
"""
for element in provided:
node.addnext(element)
if provided.text:
node.tail = node.tail or "" + provided.text
_map = dict(
replace=replace,
prepend=prepend,
append=append,
before=before,
after=after) | z3c.layout | /z3c.layout-0.2.tar.gz/z3c.layout-0.2/src/z3c/layout/browser/insertion.py | insertion.py |
import lxml.etree
import lxml.html
from zope import interface
from zope import component
from zope.publisher.browser import BrowserView
from zope.contentprovider.interfaces import IContentProvider
from z3c.layout import interfaces
from plone.memoize.view import memoize
import insertion
class LayoutView(BrowserView):
def __init__(self, context, request):
BrowserView.__init__(self, context, request)
self._layout = interfaces.ILayout(context)
self.mapping = self._get_region_provider_mapping()
def __call__(self):
# parse tree
tree = self._layout.parse()
# render and insert content providers
for region, provider in self.mapping.values():
self._insert_provider(tree, region, provider)
return lxml.html.tostring(tree, pretty_print=True).rstrip('\n')
def _insert_provider(self, tree, region, provider):
# render and wrap provided content
html = provider.render()
provided = lxml.html.fromstring(
u"<div>%s</div>" % html)
insertion.insert(tree, region, provided)
def _get_provider(self, region):
"""Lookup content provider for region."""
name = region.provider
factory = interfaces.IContentProviderFactory(region, None)
if factory is not None:
return factory(self.context, self.request, self)
if name is not None:
return component.queryMultiAdapter(
(self.context, self.request, self), IContentProvider, name=name)
return None
@memoize
def _get_region_provider_mapping(self):
mapping = {}
for region in self._layout.regions:
provider = self._get_provider(region)
if provider is not None:
provider.__name__ = region.name
mapping[region.name] = (region, provider)
# update content providers
for region, provider in mapping.values():
provider.update()
return mapping | z3c.layout | /z3c.layout-0.2.tar.gz/z3c.layout-0.2/src/z3c/layout/browser/layout.py | layout.py |
z3c.listjs
**********
z3c.listjs contains a widget called ``ListJsWidget`` that is a drop-in
replacement for the ``zope.app.form.browser.ListSequenceWidget``. It
allows users to add and remove list items without the need for server
interaction, using Javascript.
Note: This package only works with ``zope.formlib``
(``zope.app.form``) and is not compatible with ``z3c.form``.
You can use ``ListJsWidget`` for any ``schema.List`` field using the
normal ``zope.formlib`` custom widget pattern::
from z3c.listjs import ListJsWidget
...
form_fields['foo'].custom_widget = ListJsWidget
With the right ZCML override it should also be possible to
automatically use this widget in all cases ``ListSequenceWidget``
would normally be used. Documentation contributions are welcome!
Should you wish to override the CSS for the buttons, the CSS classes
are ``up_button`` and ``down_button``. If you are using hurry.resource
for your overriding CSS, your resource should depend on
``z3c.listjs.listjs_css`` so that ordering is correct to make the
override happen.
| z3c.listjs | /z3c.listjs-1.0b1.tar.gz/z3c.listjs-1.0b1/README.txt | README.txt |
if (typeof Z3C == "undefined" || !Z3C) {
var Z3C = {};
}
// create a new namespace (under Z3C)
Z3C.namespace = function(name) {
var ns = Z3C;
var parts = name.split(".");
if (parts[0] == "Z3C") {
parts = parts.slice(1);
}
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
ns[part] = ns[part] || {};
ns = ns[part];
}
return ns;
};
(function() {
Z3C.namespace('listjs');
var disconnected_editor_ids = [];
// return true if string starts with a prefix
var startswith = function(s, prefix) {
return (s.substring(0, prefix.length) == prefix);
};
// check whether a particular object is a number
var isNumber = function(o) {
return typeof o === 'number' && isFinite(o);
};
// change all numbers in a string with a dotted name to a new number
// also renumber remove_X
var renumber = function(s, nr) {
var i;
var fragment;
var fragments = s.split('.');
var result = [];
for (i = 0; i < fragments.length; i++ ) {
fragment = fragments[i];
if (isNumber(parseInt(fragment))) {
result[result.length] = nr.toString();
} else if (startswith(fragment, 'remove_')) {
result[result.length] = 'remove_' + nr.toString();
} else {
result[result.length] = fragment;
}
};
return result.join('.');
};
var renumberScript = function(s, nr, prefix) {
var tomatch = new RegExp(prefix + '[^"\']*', 'g');
var potentials = s.match(tomatch);
if (potentials == null) {
return s; // nothing to replace
}
var original = potentials[0];
var renumbered = renumber(original, nr);
return s.replace(original, renumbered);
};
// simplistic implementation that doesn't understand
// multiple classes per element
var getElementsByClassName = function(class_name, root_el, tag) {
tag = tag || '*';
var result = [];
var elements = root_el.getElementsByTagName(tag);
for (var i = 0, len = elements.length; i < len; ++i) {
if (elements[i].className == class_name) {
result[result.length] = elements[i];
}
}
return result;
};
// number all relevant attributes under el with nr
var updateNumbers = function(el, nr, prefix) {
// optimization - skip non-element nodes (ELEMENT_NODE 1)
if (el.nodeType != 1) {
return;
}
// if this is a script tag, do textual replace
if (el.tagName.toLowerCase() == 'script') {
el.text = renumberScript(el.text, nr, prefix);
return;
}
var i;
var attributes = ['id', 'name', 'for'];
for (i = 0; i < attributes.length; i++) {
var attr = el.getAttribute(attributes[i]);
if (attr && startswith(attr, prefix)) {
el.setAttribute(attributes[i], renumber(attr, nr));
}
}
var onclick_attr = el.getAttribute('onclick');
if (onclick_attr) {
el.setAttribute('onclick', renumberScript(onclick_attr, nr, prefix));
}
// recursion
var node = el.firstChild;
while (node) {
updateNumbers(node, nr, prefix);
node = node.nextSibling;
}
};
// update all numbers in el root
var updateAllNumbers = function(prefix) {
var table_el = document.getElementById(prefix + '.table');
// update numbering in table
var els = getElementsByClassName('list_item', table_el, 'tr');
var i;
for (i = 0; i < els.length; i++) {
updateNumbers(els[i], i, prefix);
runScripts(els[i]);
}
// update count
var count_el = document.getElementById(prefix + '.count');
count_el.value = els.length;
};
// disconnect all editors in affected elements
var disconnectEditors = function(affected_elements) {
// if tinyMCE is installed, disconnect all editors
if (tinyMCE) {
//tinyMCE.triggerSave();
disconnected_editor_ids = [];
for (var n in tinyMCE.editors) {
var inst = tinyMCE.editors[n];
if (!inAffectedElements(inst.getElement(),
affected_elements)) {
continue;
}
disconnected_editor_ids.push(inst.id);
tinyMCE.execCommand('mceFocus', false, inst.id);
tinyMCE.execCommand('mceRemoveControl', false, inst.id);
}
}
};
// reconnect all editors that aren't reconnected already
var reconnectEditors = function() {
// reconnect all editors
if (tinyMCE) {
for (i = 0; i < disconnected_editor_ids.length; i++) {
var editor_id = disconnected_editor_ids[i];
if (!tinyMCE.get(editor_id)) {
tinyMCE.execCommand('mceAddControl', false, editor_id);
}
}
}
};
// return true if el is inside one of affected_elements
var inAffectedElements = function(el, affected_elements) {
for (var i = 0; i < affected_elements.length; i++) {
if (isAncestor(affected_elements[i], el)) {
return true;
}
}
return false;
};
// return true if a is an ancestor of b
var isAncestor = function(a, b) {
while (b) {
if (a === b) {
return true;
}
b = b.parentNode;
}
return false;
}
// run all embedded scripts (after setting innerHTML)
// see http://brightbyte.de/page/Loading_script_tags_via_AJAX
// combined with
// http://caih.org/open-source-software/loading-javascript-execscript-and-testing/
// to eval in the global scope
var runScripts = function(e) {
if (e.nodeType != 1) {
return;
}
// run any script tag
if (e.tagName.toLowerCase() == 'script') {
if (window.execScript) {
window.execScript(e.text);
} else {
with (window) {
window.eval(e.text);
}
}
} else {
var n = e.firstChild;
while (n) {
if (n.nodeType == 1) {
runScripts(n);
}
n = n.nextSibling;
}
}
};
// add a new repeating element to the list
Z3C.listjs.add = function(prefix) {
var table_el = document.getElementById(prefix + '.table');
var template_el = document.getElementById(prefix + '.template');
var template_text = template_el.value;
var buttons_el = document.getElementById(prefix + '.buttons');
// note that some DOM manipulation is needed as IE cannot
// use innerHTML on tr directly. Instead we create the td
// and put the widget contents in that.
var new_tr = document.createElement('tr');
new_tr.className = 'list_item';
buttons_el.parentNode.insertBefore(new_tr, buttons_el);
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
new_tr.appendChild(td1);
new_tr.appendChild(td2);
new_tr.appendChild(td3);
var cb = document.createElement('input');
cb.className = 'editcheck';
cb.type = 'checkbox';
cb.name = prefix + '.remove_0';
td1.appendChild(cb);
td2.innerHTML = template_text;
// up and down arrows
var div_up = document.createElement('div');
var div_down = document.createElement('div');
var a_up = document.createElement('a');
var a_down = document.createElement('a');
a_up.className = 'up_button';
a_down.className = 'down_button';
a_up.onclick = function() {
Z3C.listjs.up(prefix, this);
};
a_down.onclick = function() {
Z3C.listjs.down(prefix, this);
};
td3.appendChild(div_up);
td3.appendChild(div_down);
div_up.appendChild(a_up);
div_down.appendChild(a_down);
updateAllNumbers(prefix);
};
// remove all selected repeating elements from the list
Z3C.listjs.remove = function(prefix) {
var table_el = document.getElementById(prefix + '.table');
// find all elements that are checked
var els = getElementsByClassName('editcheck', table_el, 'input');
var i;
var to_remove = [];
for (i = 0; i < els.length; i++) {
if (els[i].checked) {
// remove the tr (two levels up from the input box)
to_remove[to_remove.length] = els[i].parentNode.parentNode;
}
}
// now actually remove them
for (i = 0; i < to_remove.length; i++) {
to_remove[i].parentNode.removeChild(to_remove[i]);
}
updateAllNumbers(prefix);
};
Z3C.listjs.up = function(prefix, el) {
while (el.className != 'list_item') {
el = el.parentNode;
}
var previous_el = el.previousSibling;
while (previous_el != null && previous_el.className != 'list_item') {
previous_el = previous_el.previousSibling;
}
// first list element, no move possible
if (previous_el == null) {
return;
}
disconnectEditors([el, previous_el]);
previous_el.parentNode.insertBefore(el, previous_el);
updateAllNumbers(prefix);
reconnectEditors();
};
Z3C.listjs.down = function(prefix, el) {
while (el.className != 'list_item') {
el = el.parentNode;
}
var next_el = el.nextSibling;
while (next_el != null && next_el.className != 'list_item') {
next_el = next_el.nextSibling;
}
// last list element, no move possible
if (next_el == null) {
return;
}
disconnectEditors([el, next_el]);
next_el.parentNode.insertBefore(el, next_el.nextSibling);
updateAllNumbers(prefix);
reconnectEditors();
};
})(); | z3c.listjs | /z3c.listjs-1.0b1.tar.gz/z3c.listjs-1.0b1/src/z3c/listjs/resources/listjs.js | listjs.js |
=======
CHANGES
=======
2.3 (2021-12-16)
----------------
- Add support for Python 3.5, 3.8, 3.9, and 3.10.
2.2.1 (2018-12-05)
------------------
- Fix list of supported Python versions in Trove classifiers: The currently
supported Python versions are 2.7, 3.6, 3.7, PyPy2 and PyPy3.
- Flake8 the code.
2.2.0 (2018-11-13)
------------------
- Removed Python 3.5 support, added Python 3.7.
- Fixed up tests.
- Fix docstring that caused DeprecationWarning.
2.1.0 (2017-10-17)
------------------
- Drop support for Python 2.6 and 3.3.
- Add support for Python 3.4, 3.5 and 3.6.
- Add support for PyPy.
2.0.0 (2015-11-09)
------------------
- Standardize namespace ``__init__``.
2.0.0a1 (2013-02-25)
--------------------
- 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.
1.4.2 (2012-02-15)
------------------
- Remove hooks to use ViewPageTemplateFile from z3c.pt because this breaks when
z3c.pt is available, but z3c.ptcompat is not included. As recommended by notes
in 1.4.0 release.
1.4.1 (2011-11-15)
------------------
- bugfix, missing comma in setup install_requires list
1.4.0 (2011-10-29)
------------------
- Moved z3c.pt include to extras_require chameleon. This makes the package
independent from chameleon and friends and allows to include this
dependencies in your own project.
- Upgrade to chameleon 2.0 template engine and use the newest z3c.pt and
z3c.ptcompat packages adjusted to work with chameleon 2.0.
See the notes from the z3c.ptcompat package:
Update z3c.ptcompat implementation to use component-based template engine
configuration, plugging directly into the Zope Toolkit framework.
The z3c.ptcompat package no longer provides template classes, or ZCML
directives; you should import directly from the ZTK codebase.
Note that the ``PREFER_Z3C_PT`` environment option has been
rendered obsolete; instead, this is now managed via component
configuration.
Also note that the chameleon CHAMELEON_CACHE environment value changed from
True/False to a path. Skip this property if you don't like to use a cache.
None or False defined in buildout environment section doesn't work. At least
with chameleon <= 2.5.4
Attention: You need to include the configure.zcml file from z3c.ptcompat
for enable the z3c.pt template engine. The configure.zcml will plugin the
template engine. Also remove any custom built hooks which will import
z3c.ptcompat in your tests or other places.
1.3.0 (2010-07-05)
------------------
- Tests now require ``zope.browserpage >= 3.12`` instead of
``zope.app.pagetemplate`` as the expression type registration has
been moved there recently.
- No longer using deprecated ``zope.testing.doctestunit`` but built-in
``doctest`` instead.
1.2.1 (2009-03-07)
------------------
- Presence of ``z3c.pt`` is not sufficient to register macro-utility,
``chameleon.zpt`` is required otherwise the factory for the utility
is not defined.
1.2.0 (2009-03-07)
------------------
- Allow use of ``z3c.pt`` using ``z3c.ptcompat`` compatibility layer.
- Change package's mailing list address to zope-dev at zope.org.
1.1.0 (2007-11-01)
------------------
- Update package info data.
- Add z3c namespace package declaration.
1.0.0 (2007-09-30)
------------------
- Initial release.
| z3c.macro | /z3c.macro-2.3.tar.gz/z3c.macro-2.3/CHANGES.rst | CHANGES.rst |
.. image:: https://img.shields.io/pypi/v/z3c.macro.svg
:target: https://pypi.python.org/pypi/z3c.macro/
:alt: Latest release
.. image:: https://img.shields.io/pypi/pyversions/z3c.macro.svg
:target: https://pypi.org/project/z3c.macro/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/z3c.macro/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/z3c.macro/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/z3c.macro/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/z3c.macro?branch=master
This package provides an adapter and a TALES expression for a more explicit and
more flexible macro handling using the adapter registry for macros.
| z3c.macro | /z3c.macro-2.3.tar.gz/z3c.macro-2.3/README.rst | README.rst |
=====
Macro
=====
This package provides a adapter and a TALES expression for a expliciter and
flexibler macro handling using the adapter registry for macros.
We start with creating a content object that is used as a view context later:
>>> import zope.interface
>>> import zope.component
>>> from zope.publisher.interfaces.browser import IBrowserView
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> @zope.interface.implementer(zope.interface.Interface)
... class Content(object):
... pass
>>> content = Content()
We also create a temp dir for sample templates which we define later for
testing:
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
Macro Template
--------------
We define a macro template as a adapter providing IMacroTemplate:
>>> path = os.path.join(temp_dir, 'navigation.pt')
>>> with open(path, 'w') as file:
... _ = file.write('''
... <metal:block define-macro="navigation">
... <div tal:content="title">---</div>
... </metal:block>
... ''')
Let's define the macro factory
>>> from z3c.macro import interfaces
>>> from z3c.macro import zcml
>>> navigationMacro = zcml.MacroFactory(path, 'navigation', 'text/html')
and register them as adapter:
>>> zope.component.provideAdapter(
... navigationMacro,
... (zope.interface.Interface, IBrowserView, IDefaultBrowserLayer),
... interfaces.IMacroTemplate,
... name='navigation')
The TALES ``macro`` Expression
------------------------------
The ``macro`` expression will look up the name of the macro, call a adapter
providing IMacroTemplate and uses them or fills a slot if defined in the
``macro`` expression.
Let's create a page template using the ``navigation`` macros:
>>> path = os.path.join(temp_dir, 'first.pt')
>>> with open(path, 'w') as file:
... _ = file.write('''
... <html>
... <body>
... <h1>First Page</h1>
... <div class="navi">
... <tal:block define="title string:My Navigation">
... <metal:block use-macro="macro:navigation" />
... </tal:block>
... </div>
... <div class="content">
... Content here
... </div>
... </body>
... </html>
... ''')
As you can see, we used the ``macro`` expression to simply look up a macro
called navigation whihc get inserted and replaces the HTML content at this
place.
Let's now create a view using this page template:
>>> from zope.publisher.browser import BrowserView
>>> class simple(BrowserView):
... def __getitem__(self, name):
... return self.index.macros[name]
...
... def __call__(self, **kwargs):
... return self.index(**kwargs)
>>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
>>> def SimpleViewClass(path, name=u''):
... return type(
... "SimpleViewClass", (simple,),
... {'index': ViewPageTemplateFile(path), '__name__': name})
>>> FirstPage = SimpleViewClass(path, name='first.html')
>>> zope.component.provideAdapter(
... FirstPage,
... (zope.interface.Interface, IDefaultBrowserLayer),
... zope.interface.Interface,
... name='first.html')
Finally we look up the view and render it:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> view = zope.component.getMultiAdapter((content, request),
... name='first.html')
>>> print(view().strip())
<html>
<body>
<h1>First Page</h1>
<div class="navi">
<div>My Navigation</div>
</div>
<div class="content">
Content here
</div>
</body>
</html>
Slot
----
We can also define a macro slot and fill it with given content:
>>> path = os.path.join(temp_dir, 'addons.pt')
>>> with open(path, 'w') as file:
... _ = file.write('''
... <metal:block define-macro="addons">
... Content before header
... <metal:block define-slot="header">
... <div>My Header</div>
... </metal:block>
... Content after header
... </metal:block>
... ''')
Let's define the macro factory
>>> addonsMacro = zcml.MacroFactory(path, 'addons', 'text/html')
and register them as adapter:
>>> zope.component.provideAdapter(
... addonsMacro,
... (zope.interface.Interface, IBrowserView, IDefaultBrowserLayer),
... interfaces.IMacroTemplate,
... name='addons')
Let's create a page template using the ``addons`` macros:
>>> path = os.path.join(temp_dir, 'second.pt')
>>> with open(path, 'w') as file:
... _ = file.write('''
... <html>
... <body>
... <h1>Second Page</h1>
... <div class="header">
... <metal:block use-macro="macro:addons">
... This line get ignored
... <metal:block fill-slot="header">
... Header comes from here
... </metal:block>
... This line get ignored
... </metal:block>
... </div>
... </body>
... </html>
... ''')
Let's now create a view using this page template:
>>> SecondPage = SimpleViewClass(path, name='second.html')
>>> zope.component.provideAdapter(
... SecondPage,
... (zope.interface.Interface, IDefaultBrowserLayer),
... zope.interface.Interface,
... name='second.html')
Finally we look up the view and render it:
>>> view = zope.component.getMultiAdapter((content, request),
... name='second.html')
>>> print(view().strip())
<html>
<body>
<h1>Second Page</h1>
<div class="header">
<BLANKLINE>
Content before header
<BLANKLINE>
Header comes from here
<BLANKLINE>
Content after header
</div>
</body>
</html>
Cleanup
-------
>>> import shutil
>>> shutil.rmtree(temp_dir)
| z3c.macro | /z3c.macro-2.3.tar.gz/z3c.macro-2.3/src/z3c/macro/README.rst | README.rst |
=================
macro directive
=================
A macro directive can be used for register macros. Take a look at the
README.txt which explains the macro TALES expression.
>>> import sys
>>> from zope.configuration import xmlconfig
>>> import z3c.template
>>> context = xmlconfig.file('meta.zcml', z3c.macro)
First define a template which defines a macro:
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
>>> file_path = os.path.join(temp_dir, 'file.pt')
>>> with open(file_path, 'w') as file:
... _ = file.write('''
... <html>
... <head>
... <metal:block define-macro="title">
... <title>Pagelet skin</title>
... </metal:block>
... </head>
... <body>
... <div>content</div>
... </body>
... </html>
... ''')
and register the macro provider within the ``z3c:macroProvider`` directive:
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:macro
... template="%s"
... name="title"
... />
... </configure>
... """ % file_path, context=context)
We need a content object...
>>> import zope.interface
>>> @zope.interface.implementer(zope.interface.Interface)
... class Content(object):
... pass
>>> content = Content()
and we need a view...
>>> import zope.interface
>>> import zope.component
>>> from zope.publisher.browser import BrowserPage
>>> class View(BrowserPage):
... def __init__(self, context, request):
... self.context = context
... self.request = request
and we need a request:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
Check if we get the macro template:
>>> from z3c.macro import interfaces
>>> view = View(content, request)
>>> macro = zope.component.queryMultiAdapter((content, view, request),
... interface=interfaces.IMacroTemplate, name='title')
>>> macro is not None
True
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
>>> test_path = os.path.join(temp_dir, 'test.pt')
>>> with open(test_path, 'w') as file:
... _ = file.write('''
... <html>
... <body>
... <metal:macro use-macro="options/macro" />
... </body>
... </html>
... ''')
>>> from zope.browserpage.viewpagetemplatefile import BoundPageTemplate
>>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
>>> template = ViewPageTemplateFile(test_path)
>>> print(BoundPageTemplate(template, view)(macro=macro))
<html>
<body>
<title>Pagelet skin</title>
</body>
</html>
Error Conditions
================
If the file is not available, the directive fails:
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:macro
... template="this_file_does_not_exist"
... name="title"
... />
... </configure>
... """, context=context)
Traceback (most recent call last):
...
zope.configuration.exceptions.ConfigurationError: ...
| z3c.macro | /z3c.macro-2.3.tar.gz/z3c.macro-2.3/src/z3c/macro/zcml.rst | zcml.rst |
"""ZCML Meta-Directives
"""
import os
import zope.interface
import zope.schema
import zope.configuration.fields
from zope.configuration.exceptions import ConfigurationError
from zope.component import zcml
from zope.publisher.interfaces.browser import IBrowserView
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from z3c.macro import interfaces
class IMacroDirective(zope.interface.Interface):
"""Parameters for the template directive."""
template = zope.configuration.fields.Path(
title=u'Template defining a named macro.',
description=u"""Refers to a file containing a page template
(should end in extension ``.pt`` or ``.html``).
""",
required=True,
)
name = zope.schema.TextLine(
title=u'Name',
description=u"""
The macro name which this macro is registered for. The macro
name can be the same defined in metal:define-macro but does
not have to be the same. If no macro attribute is given the
name is used as the name defined in metal:define-macro. If you
need to register a macro under a different name as the defined
one, you can use the macro attribute which have to reference
the metal.define-macro name. The TALES expression calls macros
by this name and returns the macro within the same name or with
the name defined in the macro attribute.
""",
required=True,
default=u'',
)
macro = zope.schema.TextLine(
title=u'Macro',
description=u"""
The name of the macro to be used. This allows us to reference
the named macro defined with metal:define-macro if we use a
different IMacroDirective name.
""",
required=False,
default=u'',
)
for_ = zope.configuration.fields.GlobalObject(
title=u'Context',
description=u'The context for which the macro should be used',
required=False,
default=zope.interface.Interface,
)
view = zope.configuration.fields.GlobalObject(
title=u'View',
description=u'The view for which the macro should be used',
required=False,
default=IBrowserView)
layer = zope.configuration.fields.GlobalObject(
title=u'Layer',
description=u'The layer for which the macro should be used',
required=False,
default=IDefaultBrowserLayer,
)
contentType = zope.schema.ASCIILine(
title=u'Content Type',
description=u'The content type identifies the type of data.',
default='text/html',
required=False,
)
class MacroFactory(object):
"""Macro factory."""
def __init__(self, path, macro, contentType):
self.path = path
self.macro = macro
self.contentType = contentType
def __call__(self, context, view, request):
template = ViewPageTemplateFile(self.path,
content_type=self.contentType)
return template.macros[self.macro]
def registerMacroFactory(_context, path, name, macro, for_, view, layer,
contentType):
"""Register a named macro factory adapter."""
factory = MacroFactory(path, macro, contentType)
# register the macro
zcml.adapter(_context, (factory,), interfaces.IMacroTemplate,
(for_, view, layer), name=name)
def macroDirective(_context, template, name, macro=u'',
for_=zope.interface.Interface, view=IBrowserView,
layer=IDefaultBrowserLayer, contentType='text/html'):
# Make sure that the template exists
path = os.path.abspath(str(_context.path(template)))
if not os.path.isfile(path):
raise ConfigurationError("No such file", template)
if not macro:
macro = name
registerMacroFactory(_context, path, name, macro, for_, view, layer,
contentType) | z3c.macro | /z3c.macro-2.3.tar.gz/z3c.macro-2.3/src/z3c/macro/zcml.py | zcml.py |
__docformat__ = "reStructuredText"
import os
from StringIO import StringIO
import zope.interface
import zope.schema
import zope.configuration.fields
from zope.configuration.exceptions import ConfigurationError
from zope.component import zcml
from zope.publisher.interfaces.browser import IBrowserView
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.tal.talinterpreter import TALInterpreter
from zope.viewlet.interfaces import IViewlet
from zope.viewlet.interfaces import IViewletManager
from zope.viewlet import viewlet
from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
class IMacroViewletDirective(zope.interface.Interface):
"""Parameters for the template directive."""
template = zope.configuration.fields.Path(
title=u'Template defining a named macro.',
description=u"""Refers to a file containing a page template
(should end in extension ``.pt`` or ``.html``).
""",
required=True,
)
macro = zope.schema.TextLine(
title=u'Macro',
description=u"""
The name of the macro to be used. This allows us to reference
the named macro defined with metal:define-macro if we use a
different IMacroDirective name.
""",
required=True,
default=u'',
)
for_ = zope.configuration.fields.GlobalObject(
title=u'Context',
description=u'The context for which the macro should be used',
required=False,
default=zope.interface.Interface,
)
view = zope.configuration.fields.GlobalObject(
title=u'View',
description=u'The view for which the macro should be used',
required=False,
default=IBrowserView)
manager = zope.configuration.fields.GlobalObject(
title=u"Manager",
description=u"The interface of the manager this provider is for.",
required=False,
default=IViewletManager)
layer = zope.configuration.fields.GlobalObject(
title=u'Layer',
description=u'The layer for which the macro should be used',
required=False,
default=IDefaultBrowserLayer,
)
contentType = zope.schema.BytesLine(
title=u'Content Type',
description=u'The content type identifies the type of data.',
default='text/html',
required=False,
)
class MacroViewlet(viewlet.ViewletBase):
"""Provides a single macro from a template for rendering."""
def __init__(self, template, macroName, view, request, contentType):
self.template = template
self.macroName = macroName
self.view = view
self.request = request
self.contentType = contentType
def render(self):
program = self.template.macros[self.macroName]
output = StringIO(u'')
namespace = self.template.pt_getContext(self.view, self.request)
context = self.template.pt_getEngineContext(namespace)
TALInterpreter(program, None,
context, output, tal=True, showtal=False,
strictinsert=0, sourceAnnotations=False)()
if not self.request.response.getHeader("Content-Type"):
self.request.response.setHeader("Content-Type",
self.contentType)
return output.getvalue()
class MacroViewletFactory(object):
def __init__(self, filename, macro, contentType):
self.filename = filename
self.macro = macro
self.contentType = contentType
def __call__(self, context, request, view, manager):
self.template= ViewPageTemplateFile(self.filename,
content_type=self.contentType)
return MacroViewlet(self.template, self.macro, view,
request, self.contentType)
def macroViewletDirective(_context, template, macro,
for_=zope.interface.Interface, view=IBrowserView,
layer=IDefaultBrowserLayer, manager=IViewletManager,
contentType='text/html'):
# Make sure that the template exists
path = os.path.abspath(str(_context.path(template)))
if not os.path.isfile(path):
raise ConfigurationError("No such file", template)
factory = MacroViewletFactory(path, macro, contentType)
# register the macro provider
zcml.adapter(_context, (factory,), IViewlet,
(for_, layer, view, manager), name=macro) | z3c.macroviewlet | /z3c.macroviewlet-1.1.0.tar.gz/z3c.macroviewlet-1.1.0/src/z3c/macroviewlet/zcml.py | zcml.py |
==============
Macro Provider
==============
This package provides a ZCML directive which allows you to register a macro
defined in a template as a viewlet. Such a macro based viewlet acts 100% the
same as a other viewlets. It could be very handy if you want to write a layout
template in one page template and define selective parts as viewlets without
adding any additional HTML. Let me show what this will look like:
The layout/master template can look like this::
<!DOCTYPE ...>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
i18n:domain="z3c">
<head>
<tal:block replace="structure provider:ITitle">
<metal:block define-macro="title">
<title>The title</title>
</metal:block>
</tal:block>
</head>
<body tal:define="applicationURL request/getApplicationURL">
<div id="content">
<tal:block content="structure provider:pagelet">content</tal:block>
</div>
</div>
</body>
</html>
The tempalte above defines an ITitle provider which contains the definition
for a macro within itself. You have to define a viewlet manager within the
zope.viewlet ZCMl directive which provides ITitle as a viewlet manager.
After that, you can register the template above as a layout template wthin
the z3c:layout ZCML directive like this::
<z3c:layout
for="*"
layer="z3c.skin.pagelet.IPageletBrowserSkin"
template="template.pt"
/>
Then you can register the macro viewlet for the ITitle viewlet manager
like this::
<z3c:macroViewlet
for="*"
template="template.pt"
macro="title"
manager="z3c.skin.pagelet.ITitle"
layer="z3c.skin.pagelet.IPageletBrowserSkin"
/>
As you can see, the ZCML configuration directive above uses ``title`` as the
macro attribute and uses ITitle as the viewlet manager. This will use the
following part of the template.pt::
<title>Pagelet skin</title>
and registers it as a viewlet. This viewlet gets rendered in the ITitle
provider. As you can see, you can use a complete layout tempalte and use it
as it is. And here it comes, you can offer an included viewlet manager
rendering the viewlet which can be overriden for other contexts or views etc.
You also can register more than one viewlet for the ITitle viewlet manager.
Which of course makes no sense in our special title tag example.
Let's show this in some tests. We'll start by creating a content object that
is used as a view context later::
>>> import zope.interface
>>> import zope.component
>>> from zope.publisher.interfaces.browser import IBrowserView
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> class Content(object):
... zope.interface.implements(zope.interface.Interface)
>>> content = Content()
We also create a temp dir for sample templates which will be defined later
for testing::
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
And we register a security checker for the MacroViewlet class::
>>> from zope.configuration.xmlconfig import XMLConfig
>>> import zope.app.component
>>> import z3c.macroviewlet
>>> XMLConfig('meta.zcml', zope.app.component)()
>>> XMLConfig('configure.zcml', z3c.macroviewlet)()
Layout template
---------------
We define a template including a macro definition and using a provider::
>>> path = os.path.join(temp_dir, 'template.pt')
>>> open(path, 'w').write('''
... <html>
... <body>
... <head>
... <tal:block replace="structure provider:ITitle">
... <metal:block define-macro="title">
... <title>The title</title>
... </metal:block>
... </tal:block>
... </head>
... <body tal:define="applicationURL request/getApplicationURL">
... content
... </body>
... </html>
... ''')
Let's register a view class using the view template::
>>> import zope.interface
>>> from zope.app.pagetemplate import viewpagetemplatefile
>>> from zope.publisher.interfaces.browser import IBrowserView
>>> class View(object):
... zope.interface.implements(IBrowserView)
... def __init__(self, context, request):
... self.context = context
... self.request = request
... def __call__(self):
... return viewpagetemplatefile.ViewPageTemplateFile(path)(self)
Let's prepare the view::
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> view = View(content, request)
Let's define the viewlet manager ``ITitle``::
>>> from zope.viewlet.interfaces import IViewletManager
>>> from zope.viewlet.manager import ViewletManager
>>> class ITitle(IViewletManager):
... """Viewlet manager located in the title tag."""
>>> title = ViewletManager('title', ITitle)
Let's register the viewlet manager::
>>> from zope.viewlet.interfaces import IViewletManager
>>> manager = zope.component.provideAdapter(
... title,
... (zope.interface.Interface, TestRequest, IBrowserView),
... IViewletManager,
... name='ITitle')
MacroViewlet
------------
Before we register the macro viewlet, we check the rendered page without any
registered macro viewlet::
>>> print view()
<html>
<body>
<head>
</head>
<body>
content
</body>
</body></html>
As you can see there is no title rendered. Now we can define the macro
viewlet...::
>>> from zope.app.pagetemplate import viewpagetemplatefile
>>> from z3c.macroviewlet import zcml
>>> macroViewlet = zcml.MacroViewletFactory(path, 'title', 'text/html')
and register them as adapter::
>>> from zope.viewlet.interfaces import IViewlet
>>> zope.component.provideAdapter(
... macroViewlet,
... (zope.interface.Interface, IDefaultBrowserLayer, IBrowserView,
... ITitle),
... IViewlet,
... name='title')
Now we are ready to test it again::
>>> print view()
<html>
<body>
<head>
<title>The title</title>
</head>
<body>
content
</body>
</body></html>
As you can see, the title gets rendered as a viewlet into the ITitle provider.
Cleanup
-------
>>> import shutil
>>> shutil.rmtree(temp_dir)
| z3c.macroviewlet | /z3c.macroviewlet-1.1.0.tar.gz/z3c.macroviewlet-1.1.0/src/z3c/macroviewlet/README.txt | README.txt |
===========
Simple Menu
===========
The z3c.menu.simple package provides a simple menu implementation which
allows you to implement simply menus based on content providers and viewlets.
Right now there are some ``SimpleMenuItem`` menu item implementations and
a tabbed menu with tab/tab-item and action/action-item located in this
package.
Let's see what this means.
ContextMenu
-----------
>>> from zope.viewlet.interfaces import IViewlet
>>> from zope.viewlet.interfaces import IViewletManager
Let's create a menu which means we define a viewlet manager interface:
>>> class IMenu(IViewletManager):
... """Menu viewlet manager."""
You can then create a viewlet manager using this interface now:
>>> from zope.viewlet import manager
>>> Menu = manager.ViewletManager('left', IMenu)
Now we have to define a context:
>>> import zope.interface
>>> from zope.app.container import contained
>>> from zope.app.container.interfaces import IContained
>>> class Content(contained.Contained):
... zope.interface.implements(IContained)
>>> root['content'] = Content()
>>> content = root['content']
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> from zope.publisher.interfaces.browser import IBrowserView
>>> class View(contained.Contained):
... zope.interface.implements(IBrowserView)
... def __init__(self, context, request):
... self.__parent__ = context
... self.context = context
... self.request = request
>>> view = View(content, request)
>>> menu = Menu(content, request, view)
So initially no menu get rendered:
>>> menu.update()
>>> menu.render()
u''
But now we register a context menu item for the IMenu:
>>> import zope.component
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from z3c.menu.simple.menu import ContextMenuItem
>>> class MyLocalLink(ContextMenuItem):
...
... __name__ = u'MyLocalLink'
... urlEndings = 'myLocal.html'
... viewURL = 'myLocal.html'
>>> # Create a security checker for viewlets.
>>> from zope.security.checker import NamesChecker, defineChecker
>>> viewletChecker = NamesChecker(('update', 'render'))
>>> defineChecker(MyLocalLink, viewletChecker)
>>> zope.component.provideAdapter(
... MyLocalLink,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IMenu),
... IViewlet, name='MyLocalLink')
Now see what we get if the IMenu viewlet manager get used:
>>> menu.update()
>>> print menu.render()
<a href="http://127.0.0.1/content/myLocal.html"
class="inactive-menu-item">MyLocalLink</a>
GlobalMenu
----------
>>> from z3c.menu.simple.menu import GlobalMenuItem
>>> class MyGlobalLink(GlobalMenuItem):
...
... __name__ = u'MyGlobalLink'
... urlEndings = 'myGlobal.html'
... viewURL = 'myGlobal.html'
>>> defineChecker(MyGlobalLink, viewletChecker)
>>> zope.component.provideAdapter(
... MyGlobalLink,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IMenu),
... IViewlet, name='MyGlobalLink')
Now see what we get if the IMenu viewlet manager get used:
>>> menu.update()
>>> print menu.render()
<a href="http://127.0.0.1/myGlobal.html"
class="inactive-menu-item">MyGlobalLink</a>
<a href="http://127.0.0.1/content/myLocal.html"
class="inactive-menu-item">MyLocalLink</a>
TabbedMenu
----------
Now we create a tabbed menu called MasterMenu:
>>> class IMasterMenu(IViewletManager):
... """Master menu viewlet manager."""
Let's create a viewlet manager using this interface and the TabMenu as base
class:
>>> from z3c.menu.simple.menu import TabMenu
>>> MasterMenu = manager.ViewletManager('masterMenu', IMasterMenu,
... bases=(TabMenu,))
We use the same context, request and view like before:
>>> masterMenu = MasterMenu(content, request, view)
So initially no menu get rendered:
>>> masterMenu.update()
>>> masterMenu.render()
u''
Now we register a menu tab which is also a viewlet manager:
>>> from zope.app.pagetemplate import viewpagetemplatefile
>>> from z3c.menu.simple import ITab
>>> from z3c.menu.simple.menu import Tab
>>> class MyTabs(Tab):
... template = viewpagetemplatefile.ViewPageTemplateFile('tab.pt')
>>> myTabs = MyTabs(content, request, view)
Also here, initially no tab get rendered:
>>> myTabs.update()
>>> myTabs.render()
u''
Now we register a menu action which is also a viewlet manager:
>>> from z3c.menu.simple import IAction
>>> from z3c.menu.simple.menu import Action
>>> class MyActions(Action):
... template = viewpagetemplatefile.ViewPageTemplateFile('action.pt')
>>> myActions = MyActions(content, request, view)
Also here, initially no tab get rendered:
>>> myActions.update()
>>> myActions.render()
u''
After setup the TabMenu, Tab and Action viewlet managers, we start to register
a tab menu item:
>>> from z3c.menu.simple.menu import TabItem
>>> class MyTab(TabItem):
...
... __name__ = u'MyTab'
... url = 'myTab.html'
... selectedViewNames = ['myTab.html']
>>> tabChecker = NamesChecker(('update', 'render', 'css', 'selected'))
>>> defineChecker(MyTab, tabChecker)
>>> zope.component.provideAdapter(
... MyTab,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, ITab),
... IViewlet, name='MyTab')
Now see what we get if the tab viewlet manager get rendered:
>>> myTabs.update()
>>> print myTabs.render()
<div class="tabMenu">
<span class="inactive-menu-item">
<a href="myTab.html">MyTab</a>
</span>
</div>
After showing how a tab menu item get used, we will register a menu action
item.
>>> from z3c.menu.simple.menu import ActionItem
>>> class MyAction(ActionItem):
...
... __name__ = u'MyAction'
... title = 'myAction'
>>> actionChecker = NamesChecker(('update', 'render', 'title'))
>>> defineChecker(MyAction, actionChecker)
>>> zope.component.provideAdapter(
... MyAction,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IAction),
... IViewlet, name='MyAction')
Now see what we get if the action viewlet manager get used:
>>> myActions.update()
>>> print myActions.render()
<div class="actionMenuWrapper">
<ul class="actionMenu">
<li class="inactive-menu-item">
<a href="">
<div>myAction</div>
</a>
</li>
</ul>
</div>
<div class="clearActionMenu" />
| z3c.menu | /z3c.menu-0.3.0.tar.gz/z3c.menu-0.3.0/src/z3c/menu/simple/README.txt | README.txt |
__docformat__ = 'restructuredtext'
import zope.component
import zope.interface
from zope.contentprovider.interfaces import IContentProvider
from zope.viewlet import viewlet
from zope.app.component import hooks
from zope.app.publisher.browser import menu
from zope.app.publisher.interfaces.browser import IBrowserMenu
from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
from zope.app.zapi import absoluteURL
from z3c.i18n import MessageFactory as _
from z3c.viewlet.manager import WeightOrderedViewletManager
from z3c.menu.simple.interfaces import ISimpleMenuItem
from z3c.menu.simple.interfaces import ITabMenu
from z3c.menu.simple.interfaces import ITab
from z3c.menu.simple.interfaces import IAction
# ISimpleMenuItem implementation
class SimpleMenuItem(viewlet.ViewletBase):
"""Selectable menu item."""
zope.interface.implements(ISimpleMenuItem)
template = ViewPageTemplateFile('menu_item.pt')
selectedViewNames = None
activeCSS = u'active-menu-item'
inActiveCSS = u'inactive-menu-item'
@property
def title(self):
return _(self.__name__)
@property
def url(self):
return u''
@property
def extras(self):
return {}
@property
def selected(self):
name = self.__parent__.__name__
if self.selectedViewNames is None:
if name == self.url:
return True
elif name in self.selectedViewNames:
return True
return False
@property
def css(self):
if self.selected:
return self.activeCSS
else:
return self.inActiveCSS
def render(self):
"""Return the template with the option 'menus'"""
return self.template()
class ContextMenuItem(SimpleMenuItem):
"""Menu item viewlet generating context related links."""
urlEndings = []
viewURL = u''
@property
def selected(self):
requestURL = self.request.getURL()
for urlEnding in self.urlEndings:
if requestURL.endswith(urlEnding):
return True
return False
@property
def url(self):
contextURL = absoluteURL(self.context, self.request)
return contextURL + '/' + self.viewURL
class GlobalMenuItem(SimpleMenuItem):
"""Menu item viewlet generating global/site related links."""
urlEndings = []
viewURL = u''
@property
def selected(self):
requestURL = self.request.getURL()
for urlEnding in self.urlEndings:
if requestURL.endswith(urlEnding):
return True
return False
@property
def url(self):
siteURL = absoluteURL(hooks.getSite(), self.request)
return siteURL + '/' + self.viewURL
# ITabMenu implementation
class TabMenu(object):
"""Tab menu offering tabs and actions."""
zope.interface.implements(ITabMenu)
def __init__(self, context, request, view):
self.__parent__ = view
self.context = context
self.request = request
def update(self):
"""See zope.contentprovider.interfaces.IContentProvider"""
self.tabs = zope.component.queryMultiAdapter(
(self.context, self.request, self.__parent__), IContentProvider,
'ITab')
if self.tabs is not None:
self.tabs.update()
self.actions = zope.component.queryMultiAdapter(
(self.context, self.request, self.__parent__), IContentProvider,
'IAction')
if self.actions is not None:
self.actions.update()
def render(self):
"""See zope.contentprovider.interfaces.IContentProvider"""
result = u''
if self.tabs is not None:
result += self.tabs.render()
if self.actions is not None:
result += self.actions.render()
return result
class Tab(WeightOrderedViewletManager):
"""Tab Menu"""
zope.interface.implements(ITab)
def render(self):
"""Return the template with the option 'menus'"""
if not self.viewlets:
return u''
return self.template()
class TabItem(SimpleMenuItem):
"""Base implementation for menu items."""
zope.interface.implements(ISimpleMenuItem)
template = ViewPageTemplateFile('tab_item.pt')
class Action(WeightOrderedViewletManager):
"""Action Menu"""
zope.interface.implements(IAction)
def render(self):
"""Return the template with the option 'menus'"""
if not self.viewlets:
return u''
return self.template()
class ActionItem(SimpleMenuItem):
"""Base implementation for action items."""
zope.interface.implements(ISimpleMenuItem)
template = ViewPageTemplateFile('action_item.pt')
class BrowserMenu(TabMenu):
"""Menu Action Menu Items
A special tab menu, which takes its items from a browser menu
"""
template = ViewPageTemplateFile('browser_menu_action_item.pt')
# This is the name of the menu
menuId = None
def update(self):
menu = zope.component.getUtility(IBrowserMenu, self.menuId)
self.title = menu.title
self.menuItems = menu.getMenuItems(self.context, self.request)
def render(self):
"""Return the template with the option 'menus'"""
if not self.menuItems:
return u''
return self.template() | z3c.menu | /z3c.menu-0.3.0.tar.gz/z3c.menu-0.3.0/src/z3c/menu/simple/menu.py | menu.py |
"""Menu ZCML Directives
"""
import os.path
import zope.configuration.fields
import zope.interface
import zope.security.checker
from zope.browserpage.metaconfigure import _handle_allowed_attributes
from zope.browserpage.metaconfigure import _handle_allowed_interface
from zope.browserpage.metaconfigure import _handle_for
from zope.browserpage.metaconfigure import _handle_permission
from zope.component import zcml
from zope.configuration.exceptions import ConfigurationError
from zope.publisher.interfaces.browser import IBrowserPublisher
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.interfaces.browser import IBrowserView
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.viewlet import viewlet
from zope.viewlet.metadirectives import IViewletDirective
from z3c.menu.ready2go import checker
from z3c.menu.ready2go import interfaces
from z3c.menu.ready2go import item
from z3c.menu.ready2go.i18n import MessageFactory as _
class IMenuSelectorDirective(zope.interface.Interface):
"""A directive to register a menu selector."""
factory = zope.configuration.fields.GlobalObject(
title=_("Selector factory"),
description=_("Python name of a factory which can create the"
" selector object. This must identify an"
" object in a module using the full dotted name."),
required=False,
default=checker.TrueSelectedChecker)
for_ = zope.configuration.fields.GlobalObject(
title="Context",
description="The content interface or class this selector is for.",
required=False)
view = zope.configuration.fields.GlobalObject(
title=_("The view the selector is registered for."),
description=_("The view can either be an interface or a class. By "
"default the provider is registered for all views, "
"the most common case."),
required=False,
default=IBrowserView)
layer = zope.configuration.fields.GlobalObject(
title=_("The layer the view is in."),
description=_("""
A skin is composed of layers. It is common to put skin
specific views in a layer named after the skin. If the 'layer'
attribute is not supplied, it defaults to 'default'."""),
required=False,
default=IBrowserRequest)
manager = zope.configuration.fields.GlobalObject(
title="Menu Manager",
description="The menu manager interface or class this selector is"
" for.",
required=False,
default=interfaces.IMenuManager)
menu = zope.configuration.fields.GlobalObject(
title="Menu Item",
description="The menu item interface or class this selector is for.",
required=False,
default=interfaces.IMenuItem)
class IMenuItemDirective(IViewletDirective):
"""Menu item directive."""
title = zope.configuration.fields.MessageID(
title="I18n title",
description="Translatable title for a viewlet.",
required=False)
# Arbitrary keys and values are allowed to be passed to the menu item.
IMenuItemDirective.setTaggedValue('keyword_arguments', True)
# menuItem directive
def menuItemDirective(
_context, name, permission, for_=zope.interface.Interface,
layer=IDefaultBrowserLayer, view=IBrowserView,
manager=interfaces.IMenuManager, class_=None, template=None,
attribute='render', allowed_interface=None, allowed_attributes=None,
title=None, **kwargs):
# Security map dictionary
required = {}
if title is not None:
# set i18n aware title
kwargs['i18nTitle'] = title
# Get the permission; mainly to correctly handle CheckerPublic.
permission = _handle_permission(_context, permission)
# Either the class or template must be specified.
if not (class_ or template):
raise ConfigurationError("Must specify a class or template")
# Make sure that all the non-default attribute specifications are correct.
if attribute != 'render':
if template:
raise ConfigurationError(
"Attribute and template cannot be used together.")
# Note: The previous logic forbids this condition to evere occur.
if not class_:
raise ConfigurationError(
"A class must be provided if attribute is used")
# Make sure that the template exists and that all low-level API methods
# have the right permission.
if template:
template = os.path.abspath(str(_context.path(template)))
if not os.path.isfile(template):
raise ConfigurationError("No such file", template)
required['__getitem__'] = permission
# Make sure the has the right form, if specified.
if class_:
if attribute != 'render':
if not hasattr(class_, attribute):
raise ConfigurationError(
"The provided class doesn't have the specified attribute "
)
if template:
# Create a new class for the viewlet template and class.
new_class = viewlet.SimpleViewletClass(
template, bases=(class_, ), attributes=kwargs, name=name)
else:
if not hasattr(class_, 'browserDefault'):
cdict = {'browserDefault':
lambda self, request: (getattr(self, attribute), ())}
else:
cdict = {}
cdict['__name__'] = name
cdict['__page_attribute__'] = attribute
cdict.update(kwargs)
new_class = type(class_.__name__,
(class_, viewlet.SimpleAttributeViewlet), cdict)
if hasattr(class_, '__implements__'):
zope.interface.classImplements(new_class, IBrowserPublisher)
else:
# Create a new class for the viewlet template alone.
new_class = viewlet.SimpleViewletClass(template, name=name,
attributes=kwargs)
# Set up permission mapping for various accessible attributes
_handle_allowed_interface(
_context, allowed_interface, permission, required)
_handle_allowed_attributes(
_context, allowed_attributes, permission, required)
_handle_allowed_attributes(
_context, kwargs.keys(), permission, required)
_handle_allowed_attributes(
_context,
(attribute, 'browserDefault', 'update', 'render', 'publishTraverse'),
permission, required)
# Register the interfaces.
_handle_for(_context, for_)
zcml.interface(_context, view)
# Create the security checker for the new class
zope.security.checker.defineChecker(
new_class, zope.security.checker.Checker(required))
# register viewlet
_context.action(
discriminator=('viewlet', for_, layer, view, manager, name),
callable=zcml.handler,
args=('registerAdapter',
new_class, (for_, layer, view, manager),
zope.viewlet.interfaces.IViewlet, name, _context.info),)
def addMenuItemDirective(
_context, name, permission,
for_=zope.interface.Interface, layer=IDefaultBrowserLayer,
view=IBrowserView, manager=interfaces.IMenuManager,
class_=item.AddMenuItem, template=None, attribute='render',
allowed_interface=None, allowed_attributes=None, title=None, **kwargs):
menuItemDirective(
_context, name, permission, for_, layer, view, manager,
class_, template, attribute, allowed_interface, allowed_attributes,
title, **kwargs)
def contextMenuItemDirective(
_context, name, permission,
for_=zope.interface.Interface, layer=IDefaultBrowserLayer,
view=IBrowserView, manager=interfaces.IMenuManager,
class_=item.ContextMenuItem, template=None, attribute='render',
allowed_interface=None, allowed_attributes=None, title=None, **kwargs):
menuItemDirective(
_context, name, permission, for_, layer, view, manager,
class_, template, attribute, allowed_interface, allowed_attributes,
title, **kwargs)
def globalMenuItemDirective(
_context, name, permission,
for_=zope.interface.Interface, layer=IDefaultBrowserLayer,
view=IBrowserView, manager=interfaces.IMenuManager,
class_=item.GlobalMenuItem, template=None, attribute='render',
allowed_interface=None, allowed_attributes=None, title=None, **kwargs):
menuItemDirective(
_context, name, permission, for_, layer, view, manager,
class_, template, attribute, allowed_interface, allowed_attributes,
title, **kwargs)
def siteMenuItemDirective(
_context, name, permission,
for_=zope.interface.Interface, layer=IDefaultBrowserLayer,
view=IBrowserView, manager=interfaces.IMenuManager,
class_=item.SiteMenuItem, template=None, attribute='render',
allowed_interface=None, allowed_attributes=None, title=None, **kwargs):
menuItemDirective(
_context, name, permission, for_, layer, view, manager,
class_, template, attribute, allowed_interface, allowed_attributes,
title, **kwargs)
# menu selector directive
def menuSelectorDirective(
_context, factory=checker.TrueSelectedChecker,
for_=zope.interface.Interface, layer=IBrowserRequest,
view=IBrowserView, manager=interfaces.IMenuManager,
menu=interfaces.IMenuItem):
# Security map dictionary
objs = (for_, layer, view, manager, menu)
factory = (factory,)
zcml.adapter(
_context, factory, provides=interfaces.ISelectedChecker,
for_=objs, permission=None, name='', trusted=False, locate=False) | z3c.menu.ready2go | /z3c.menu.ready2go-2.0-py3-none-any.whl/z3c/menu/ready2go/zcml.py | zcml.py |
"""Interfaces
"""
import zope.interface
import zope.schema
import zope.viewlet.interfaces
from z3c.menu.ready2go.i18n import MessageFactory as _
class IMenuManager(zope.viewlet.interfaces.IViewletManager):
"""Generic nenu manager."""
def render():
"""Represent the menu"""
class IMenuItem(zope.viewlet.interfaces.IViewlet):
"""Menu item base."""
template = zope.interface.Attribute("""Page template""")
contextInterface = zope.interface.Attribute(
"""Context discriminator interface""")
viewInterface = zope.interface.Attribute(
"""View discriminator interface""")
title = zope.schema.TextLine(
title=_('Title'),
description=_('Menu item title'),
default=''
)
viewName = zope.schema.TextLine(
title=_('View name'),
description=_('Name of the view which the menu points to.'),
default=''
)
weight = zope.schema.TextLine(
title=_('Weight'),
description=_('Weight of the menu item order.'),
default=''
)
cssActive = zope.schema.TextLine(
title=_('Active CSS class name'),
description=_('CSS class name for active menu items'),
default=''
)
cssInActive = zope.schema.TextLine(
title=_('In-Active CSS class name'),
description=_('CSS class name for inactive menu items'),
default=''
)
css = zope.schema.TextLine(
title=_('CSS class name'),
description=_('CSS class name'),
default=''
)
available = zope.schema.Bool(
title=_('Available'),
description=_('Marker for available menu item'),
default=True
)
selected = zope.schema.Bool(
title=_('Selected'),
description=_('Marker for selected menu item'),
default=False
)
url = zope.schema.TextLine(
title=_('URL'),
description=_('URL or other url like javascript function.'),
default=''
)
subMenuProviderName = zope.schema.TextLine(
title=_('Sub menu provider name'),
description=_('Name of the sub menu provider.'),
default=''
)
def getURLContext():
"""Returns the context the base url."""
def render():
"""Return the template with the option 'menus'"""
class ISelectedChecker(zope.interface.Interface):
"""Selected checker."""
selected = zope.schema.Bool(
title=_('Selected'),
description=_('Marker for selected menu item'),
default=False
)
class IGlobalMenuItem(IMenuItem):
"""Menu item with ZODB application root as url base."""
class ISiteMenuItem(IMenuItem):
"""Menu item with nearest site as url base."""
class IContextMenuItem(IMenuItem):
"""Menu item with context as url base."""
class IAddMenuItem(IMenuItem):
"""Add menu item with context as url base.""" | z3c.menu.ready2go | /z3c.menu.ready2go-2.0-py3-none-any.whl/z3c/menu/ready2go/interfaces.py | interfaces.py |
"""Menu Item
"""
import zope.interface
import zope.proxy
from z3c.template.template import getPageTemplate
from zope.component import hooks
from zope.traversing.api import getRoot
from zope.traversing.browser import absoluteURL
from zope.viewlet import viewlet
from z3c.menu.ready2go import interfaces
# base menu item mixin
class MenuItem(viewlet.ViewletBase):
"""Menu item base."""
template = getPageTemplate()
# see z3c:add/context/site/globalMenuItemDirective
i18nTitle = None
# internal approved values
approved = False
approvedURL = None
# url view name if different then ``selected`` viewName
viewName = 'index.html'
# ``selected`` discriminator values
contextInterface = zope.interface.Interface
viewInterface = zope.interface.Interface
selectedViewName = viewName
# css classes
cssActive = 'selected'
cssInActive = ''
# menu order weight
weight = 0
# sub menu provider name
subMenuProviderName = None
def __init__(self, context, request, view, manager):
super().__init__(context, request, view, manager)
self.view = view
self.setupFilter()
def setupFilter(self):
"""Catch location error and set approved attributes.
Note, this get called before update because the filter method in menu
manager needs to know that before the menu items update method get
called.
"""
try:
if self.available:
self.approvedURL = self.url
self.approved = True
except TypeError:
self.approvedURL = None
self.approved = False
# override it and use i18n msg ids
@property
def title(self):
return self.i18nTitle or self.__name__
@property
def css(self):
"""Return cssActive, cssInActive or None.
None will force not rendering a HTML attribute in the element tag.
"""
if self.selected and self.cssActive:
return self.cssActive
elif not self.selected and self.cssInActive:
return self.cssInActive
else:
return None
@property
def available(self):
"""Available checker call"""
return True
@property
def selected(self):
"""Selected checker call"""
checker = zope.component.getMultiAdapter(
(self.context, self.request, self.view, self.manager, self),
interfaces.ISelectedChecker)
return checker.selected
@property
def url(self):
return '{}/{}'.format(
absoluteURL(self.getURLContext(), self.request), self.viewName)
def getURLContext(self):
return getRoot(self.context)
def render(self):
"""Return the template with the option 'menus'"""
return self.template()
def __repr__(self):
return '<{} {!r}>'.format(self.__class__.__name__, self.__name__)
@zope.interface.implementer(interfaces.IGlobalMenuItem)
class GlobalMenuItem(MenuItem):
"""Global menu item."""
@zope.interface.implementer(interfaces.ISiteMenuItem)
class SiteMenuItem(MenuItem):
"""Site menu item."""
@property
def available(self):
"""Available checker call"""
root = zope.proxy.getProxiedObject(getRoot(self.context))
site = zope.proxy.getProxiedObject(hooks.getSite())
return site is not root
def getURLContext(self):
return hooks.getSite()
@zope.interface.implementer(interfaces.IContextMenuItem)
class ContextMenuItem(MenuItem):
"""Context menu item."""
def getURLContext(self):
return self.context
@zope.interface.implementer(interfaces.IAddMenuItem)
class AddMenuItem(MenuItem):
"""Add menu item."""
subMenuProviderName = None
@property
def selected(self):
return False
def getURLContext(self):
return self.context | z3c.menu.ready2go | /z3c.menu.ready2go-2.0-py3-none-any.whl/z3c/menu/ready2go/item.py | item.py |
===============
Ready 2 go Menu
===============
The z3c.menu.ready2go package provides a menu implementation which allows you
to implement menus based on content providers and viewlets.
First let's setup our defualt menu item template:
>>> import os
>>> import zope.component
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from zope.publisher.interfaces.browser import IBrowserView
>>> from z3c.template.interfaces import IContentTemplate
>>> from z3c.template.template import TemplateFactory
>>> import z3c.menu.ready2go
>>> baseDir = os.path.split(z3c.menu.ready2go.__file__)[0]
>>> itemTemplate = os.path.join(baseDir, 'item.pt')
>>> itemTemplateFactory = TemplateFactory(itemTemplate, 'text/html')
>>> zope.component.provideAdapter(itemTemplateFactory,
... (IBrowserView, IDefaultBrowserLayer), IContentTemplate)
Global Menu
-----------
Let's create some menu and register them as viewlet manager:
>>> from zope.viewlet.interfaces import IViewlet
>>> from zope.viewlet import manager
>>> from z3c.menu.ready2go import interfaces
>>> from z3c.menu.ready2go import IGlobalMenu
>>> from z3c.menu.ready2go import ISiteMenu
>>> from z3c.menu.ready2go import IContextMenu
>>> from z3c.menu.ready2go import IAddMenu
>>> from z3c.menu.ready2go.manager import MenuManager
And we configure our menu item as viewlet Managers. This is normaly done by the
``viewletManager`` ZCML directive:
>>> GlobalMenu = manager.ViewletManager('left', IGlobalMenu,
... bases=(MenuManager,))
>>> SiteMenu = manager.ViewletManager('left', ISiteMenu,
... bases=(MenuManager,))
>>> ContextMenu = manager.ViewletManager('left', IContextMenu,
... bases=(MenuManager,))
>>> AddMenu = manager.ViewletManager('left', IAddMenu,
... bases=(MenuManager,))
Our menu managers implement IMenuManager:
>>> interfaces.IMenuManager.implementedBy(GlobalMenu)
True
>>> interfaces.IMenuManager.implementedBy(SiteMenu)
True
>>> interfaces.IMenuManager.implementedBy(ContextMenu)
True
>>> interfaces.IMenuManager.implementedBy(AddMenu)
True
We also need our checker adapter which can check if a menu item is available
and/or selected:
>>> from z3c.menu.ready2go import checker
>>> zope.component.provideAdapter(checker.GlobalSelectedChecker)
>>> zope.component.provideAdapter(checker.SiteSelectedChecker)
>>> zope.component.provideAdapter(checker.ContextSelectedChecker)
Now we have to define a site and a context:
>>> import zope.interface
>>> from zope.container import contained, btree
>>> from zope.location.interfaces import IContained
>>> from zope.component.interfaces import IPossibleSite
>>> from zope.site.site import SiteManagerContainer
>>> from zope.site.site import LocalSiteManager
>>> @zope.interface.implementer(IPossibleSite)
... class Site(btree.BTreeContainer, SiteManagerContainer):
... def __init__(self):
... super(Site, self).__init__()
... self.setSiteManager(LocalSiteManager(self))
>>> @zope.interface.implementer(IContained)
... class Content(contained.Contained):
... pass
>>> root['site'] = Site()
>>> site = root['site']
Now we have to set the site object as site. This is normaly done by the
traverser but we do this here with the hooks helper because we do not really
traaverse to the site within the publisher/traverser:
>>> from zope.component import hooks
>>> hooks.setSite(site)
>>> site['content'] = Content()
>>> content = site['content']
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
And we need a view which knows about it's parent:
>>> @zope.interface.implementer(IBrowserView)
... class View(contained.Contained):
...
... def __init__(self, context, request):
... self.__parent__ = context
... self.context = context
... self.request = request
>>> view = View(content, request)
Our menus can adapt the context, request and view. See IViewletManager in
zope.viewlet for more infos about this pattern. If we render them, there is an
empty string returned. This means the menus don't find menu items for rendering:
>>> globalMenu = GlobalMenu(content, request, view)
>>> globalMenu.update()
>>> globalMenu.render()
''
>>> siteMenu = SiteMenu(content, request, view)
>>> siteMenu.update()
>>> siteMenu.render()
''
>>> contextMenu = ContextMenu(content, request, view)
>>> contextMenu.update()
>>> contextMenu.render()
''
>>> addMenu = AddMenu(content, request, view)
>>> addMenu.update()
>>> addMenu.render()
''
Global Menu Item
----------------
Now we register a context menu item for our IGlobalMenu:
>>> from z3c.menu.ready2go.item import GlobalMenuItem
>>> class MyGlobalMenuItem(GlobalMenuItem):
...
... viewName = 'root.html'
Now we need a security checker for our menu item
>>> from zope.security.checker import NamesChecker, defineChecker
>>> viewletChecker = NamesChecker(('update', 'render'))
>>> defineChecker(MyGlobalMenuItem, viewletChecker)
And we configure our menu item for IGlobalMenu. This is normaly done by the
``viewlet`` ZCML directive:
>>> zope.component.provideAdapter(
... MyGlobalMenuItem,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IGlobalMenu),
... IViewlet, name='My Global')
Now let's update the menu manager and see that this manager now contains
the menu item:
>>> globalMenu.update()
>>> myGlobalMenuItem = globalMenu.viewlets[0]
>>> myGlobalMenuItem
<MyGlobalMenuItem 'My Global'>
Now let's render the global menu manager and you can see that the menu item
get rendered:
>>> print(globalMenu.render())
<li>
<a href="http://127.0.0.1/root.html"><span>My Global</span></a>
</li>
Site Menu Item
--------------
Now we register a context menu item for our ISiteMenu:
>>> import zope.component
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from z3c.menu.ready2go.item import SiteMenuItem
>>> class MySiteMenuItem(SiteMenuItem):
...
... viewName = 'site.html'
Now we need a security checker for our menu item
>>> from zope.security.checker import NamesChecker, defineChecker
>>> viewletChecker = NamesChecker(('update', 'render'))
>>> defineChecker(MySiteMenuItem, viewletChecker)
And we configure our menu item for ISiteMenu. This is normaly done by the
``viewlet`` ZCML directive:
>>> zope.component.provideAdapter(
... MySiteMenuItem,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, ISiteMenu),
... IViewlet, name='My Site')
Now let's render the site menu again. You can see that we ve got a menu item
and the url points to our site:
>>> siteMenu.update()
>>> print(siteMenu.render())
<li>
<a href="http://127.0.0.1/site/site.html"><span>My Site</span></a>
</li>
Context Menu Item
-----------------
Now we register a context menu item for our IContextMenu:
>>> import zope.component
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from z3c.menu.ready2go.item import ContextMenuItem
>>> class MyContextMenuItem(ContextMenuItem):
... viewName = 'context.html'
... weight = 1
Now we need a security checker for our menu item
>>> from zope.security.checker import NamesChecker, defineChecker
>>> viewletChecker = NamesChecker(('update', 'render'))
>>> defineChecker(MyContextMenuItem, viewletChecker)
And we configure our menu item for IContextMenu. This is normaly done by the
``viewlet`` ZCML directive:
>>> zope.component.provideAdapter(
... MyContextMenuItem,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IContextMenu),
... IViewlet, name='My Context')
Now let's render the context menu again. You can see that we ve got a menu
item. Another important point here is, that the url of such ContextMemuItem
implementations point to the context of the view:
>>> contextMenu.update()
>>> print(contextMenu.render())
<li>
<a href="http://127.0.0.1/site/content/context.html"><span>My Context</span></a>
</li>
Let's set the view __name__ to ``context.html``. This will reflect that
the view offers the same name that our context menu needs to get rendered as
selected:
>>> view.__name__ = 'context.html'
Now try again and see if the context menu item get rendered as selected:
>>> contextMenu.update()
>>> print(contextMenu.render())
<li class="selected">
<a href="http://127.0.0.1/site/content/context.html"><span>My Context</span></a>
</li>
Also, let's check that menu item is marked selected even if we provided a viewName in
the ``@@context.html`` form:
>>> MyContextMenuItem.viewName = '@@context.html'
>>> contextMenu.update()
>>> print(contextMenu.render())
<li class="selected">
<a href="http://127.0.0.1/site/content/@@context.html"><span>My Context</span></a>
</li>
Okay, change viewName back to ``context.html`` for further tests:
>>> MyContextMenuItem.viewName = 'context.html'
Now add a second context menu item and check if we can use the cssInActive
argument which is normaly a empty string:
>>> class InActiveMenuItem(ContextMenuItem):
... viewName = 'inActive.html'
... cssInActive = 'inActive'
... weight = 2
>>> defineChecker(InActiveMenuItem, viewletChecker)
>>> zope.component.provideAdapter(
... InActiveMenuItem,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IContextMenu),
... IViewlet, name='In Active')
Now update and render again:
>>> contextMenu.update()
>>> print(contextMenu.render())
<li class="selected">
<a href="http://127.0.0.1/site/content/context.html"><span>My Context</span></a>
</li>
<li class="inActive">
<a href="http://127.0.0.1/site/content/inActive.html"><span>In Active</span></a>
</li>
AddMenu
-------
The add menu can be used for offering links to any kind of add forms per
context. This allows us to offer independent add form links doesn't matter which
form framework is used. Let's now define such a simple AddMenuItem pointing
to a add form url. Not; the add form and it's url do not exist in thsi test.
This aslo means there is no guarantee that a form exist if a add menu item
is configured.
>>> from z3c.menu.ready2go.item import AddMenuItem
>>> class MyAddMenuItem(AddMenuItem):
...
... viewName = 'addSomething.html'
Now we need a security checker for our menu item
>>> from zope.security.checker import NamesChecker, defineChecker
>>> viewletChecker = NamesChecker(('update', 'render'))
>>> defineChecker(MyAddMenuItem, viewletChecker)
And we configure our menu item for IAddMenu. This is normaly done by the
``viewlet`` ZCML directive:
>>> zope.component.provideAdapter(
... MyAddMenuItem,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IAddMenu),
... IViewlet, name='My AddMenu')
Now we can update and render our add menu:
>>> addMenu.update()
>>> print(addMenu.render())
<li>
<a href="http://127.0.0.1/site/content/addSomething.html"><span>My AddMenu</span></a>
</li>
Menu groups
-----------
The global and the site menu items are grouped menu items. This means such menu
items should get rendered as selected if a context menu item is selected. This
reflects the menu hierarchie. Let's show how we can solve this not so simple
problem. We offer a ISelectedChecker adapter which can decide if a menu get
rendered as selected or not. This is very usefull because normaly a menu get
registered and later we add views and can not change the menu item
implementation. Let's see how such an adapter can handle an existing menu,
context and view setup and change the selected rendering. We register a
selected checker for our site menu item:
>>> zope.component.provideAdapter(checker.TrueSelectedChecker,
... (IContained, IDefaultBrowserLayer, None, ISiteMenu, MySiteMenuItem),
... interfaces.ISelectedChecker)
Now we can render the site menu again. Note that our context is still the
sample content object.
>>> siteMenu.update()
>>> print(siteMenu.render())
<li class="selected">
<a href="http://127.0.0.1/site/site.html"><span>My Site</span></a>
</li>
This reflects that the site menu is a group menu which the context menu item
of the content object is selected too.
>>> contextMenu.update()
>>> print(contextMenu.render())
<li class="selected">
<a href="http://127.0.0.1/site/content/context.html"><span>My Context</span></a>
</li>
<li class="inActive">
<a href="http://127.0.0.1/site/content/inActive.html"><span>In Active</span></a>
</li>
EmptyMenuManager
----------------
There is a empty menu manager whihc could be used for override existing
menu managers.
>>> from z3c.menu.ready2go.manager import EmptyMenuManager
>>> emptyMenu = EmptyMenuManager(None, None, None)
Our empty menu manager implements ``IMenuManager``:
>>> interfaces.IMenuManager.providedBy(emptyMenu)
True
This empty menu manager returns allways an empty string if we render them:
>>> emptyMenu.update()
>>> emptyMenu.render()
''
Special use case
----------------
We have some special use case because of Zope's internals. One important part
is that our menu heavy depend on context and it's __parent__ chain to the
zope application root. This is not allways supported by Zopes default setup.
One part is the bad integrated application control part which fakes a root
object which doesn't know about the real childs of the real root from the
ZODB e.g. application root. Now we will show you that our menu by default
render no items if we get such a fake root which messes up our menu structure.
Let's define a object which does not know about any __parent__.
>>> nirvana = Content()
>>> nirvanaView = View(nirvana, request)
Now we can check what's happen to the menus if we adapt the parent less nirvana
context and update and render the menus. You can see that the global menu does
not contain any menu item. That's because the global menu items tries to find
the root by traversing from the context to the root by the __parent__ chain
and we don't support any parent for our nirvana object:
>>> globalMenu = GlobalMenu(nirvana, request, nirvanaView)
>>> globalMenu.update()
>>> globalMenu.render()
''
Also the SiteMenu doesn't contain any menu item because of the parent less
object:
>>> siteMenu = SiteMenu(nirvana, request, nirvanaView)
>>> siteMenu.update()
>>> siteMenu.render()
''
>>> contextMenu = ContextMenu(nirvana, request, nirvanaView)
>>> contextMenu.update()
>>> contextMenu.render()
''
>>> addMenu = AddMenu(nirvana, request, nirvanaView)
>>> addMenu.update()
>>> addMenu.render()
''
| z3c.menu.ready2go | /z3c.menu.ready2go-2.0-py3-none-any.whl/z3c/menu/ready2go/README.txt | README.txt |
"""Menu Item "Selected Checker"
"""
import zope.component
import zope.interface
from zope.publisher.interfaces.browser import IBrowserRequest
from z3c.menu.ready2go import interfaces
class CheckerBase:
"""Generic checker base class."""
def __init__(self, context, request, view, menu, item):
self.context = context
self.request = request
self.view = view
self.menu = menu
self.item = item
# ISelectedChecker
@zope.interface.implementer(interfaces.ISelectedChecker)
class FalseSelectedChecker(CheckerBase):
"""False selected checker can avoid selected menu item rendering."""
@property
def selected(self):
return False
@zope.interface.implementer(interfaces.ISelectedChecker)
class TrueSelectedChecker(CheckerBase):
"""True selected checker can force selected menu item rendering."""
@property
def selected(self):
return True
@zope.interface.implementer(interfaces.ISelectedChecker)
class ViewNameSelectedChecker(CheckerBase):
"""Selected by view name offers a generic checker for IContextMenuItem."""
@property
def selected(self):
"""Selected if also view name compares."""
viewName = self.item.viewName
if viewName.startswith('@@'):
viewName = viewName[2:]
if self.view.__name__ == viewName:
return True
return False
# default selected checkers
class GlobalSelectedChecker(FalseSelectedChecker):
"""Global menu item selected checker.
Note, this is a menu group which is selected on different menu items.
You need to register for each view a TrueSelectedChecker if the site menu
item should get rendered as selected.
"""
zope.component.adapts(zope.interface.Interface, IBrowserRequest,
zope.interface.Interface, interfaces.IMenuManager,
interfaces.IGlobalMenuItem)
class SiteSelectedChecker(FalseSelectedChecker):
"""Site menu item selected checker.
Note, this is a menu group which is selected on different menu items.
You need to register for each view a TrueSelectedChecker if the site menu
item should get rendered as selected.
"""
zope.component.adapts(zope.interface.Interface, IBrowserRequest,
zope.interface.Interface, interfaces.IMenuManager,
interfaces.ISiteMenuItem)
class ContextSelectedChecker(ViewNameSelectedChecker):
"""Context menu item selected checker."""
zope.component.adapts(zope.interface.Interface, IBrowserRequest,
zope.interface.Interface, interfaces.IMenuManager,
interfaces.IContextMenuItem) | z3c.menu.ready2go | /z3c.menu.ready2go-2.0-py3-none-any.whl/z3c/menu/ready2go/checker.py | checker.py |
===========
Simple Menu
===========
The ``z3c.menu.simple`` package provides a simple menu implementation which
allows you to implement simply menus based on content providers and viewlets.
Right now there are some ``SimpleMenuItem`` menu item implementations and
a tabbed menu with tab/tab-item and action/action-item located in this
package.
Let's see what this means.
ContextMenu
-----------
>>> from zope.viewlet.interfaces import IViewlet
>>> from zope.viewlet.interfaces import IViewletManager
Let's create a menu which means we define a viewlet manager interface:
>>> class IMenu(IViewletManager):
... """Menu viewlet manager."""
You can then create a viewlet manager using this interface now:
>>> from zope.viewlet import manager
>>> Menu = manager.ViewletManager('left', IMenu)
Now we have to define a context:
>>> import zope.interface
>>> from zope.app.container import contained
>>> from zope.app.container.interfaces import IContained
>>> class Content(contained.Contained):
... zope.interface.implements(IContained)
>>> root['content'] = Content()
>>> content = root['content']
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> from zope.publisher.interfaces.browser import IBrowserView
>>> class View(contained.Contained):
... zope.interface.implements(IBrowserView)
... def __init__(self, context, request):
... self.__parent__ = context
... self.context = context
... self.request = request
>>> view = View(content, request)
>>> menu = Menu(content, request, view)
So initially no menu get rendered:
>>> menu.update()
>>> menu.render()
u''
But now we register a context menu item for the `IMenu`:
>>> import zope.component
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from z3c.menu.simple.menu import ContextMenuItem
>>> class MyLocalLink(ContextMenuItem):
...
... __name__ = u'MyLocalLink'
... urlEndings = 'myLocal.html'
... viewURL = 'myLocal.html'
>>> # Create a security checker for viewlets.
>>> from zope.security.checker import NamesChecker, defineChecker
>>> viewletChecker = NamesChecker(('update', 'render'))
>>> defineChecker(MyLocalLink, viewletChecker)
>>> zope.component.provideAdapter(
... MyLocalLink,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IMenu),
... IViewlet, name='MyLocalLink')
Now see what we get if the IMenu viewlet manager get used:
>>> menu.update()
>>> print menu.render()
<a href="http://127.0.0.1/content/myLocal.html"
class="inactive-menu-item">MyLocalLink</a>
GlobalMenu
----------
>>> from z3c.menu.simple.menu import GlobalMenuItem
>>> class MyGlobalLink(GlobalMenuItem):
...
... __name__ = u'MyGlobalLink'
... urlEndings = 'myGlobal.html'
... viewURL = 'myGlobal.html'
>>> defineChecker(MyGlobalLink, viewletChecker)
>>> zope.component.provideAdapter(
... MyGlobalLink,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IMenu),
... IViewlet, name='MyGlobalLink')
Now see what we get if the IMenu viewlet manager get used:
>>> menu.update()
>>> print menu.render()
<a href="http://127.0.0.1/myGlobal.html"
class="inactive-menu-item">MyGlobalLink</a>
<a href="http://127.0.0.1/content/myLocal.html"
class="inactive-menu-item">MyLocalLink</a>
TabbedMenu
----------
Now we create a tabbed menu called MasterMenu:
>>> class IMasterMenu(IViewletManager):
... """Master menu viewlet manager."""
Let's create a viewlet manager using this interface and the TabMenu as base
class:
>>> from z3c.menu.simple.menu import TabMenu
>>> MasterMenu = manager.ViewletManager('masterMenu', IMasterMenu,
... bases=(TabMenu,))
We use the same context, request and view like before:
>>> masterMenu = MasterMenu(content, request, view)
So initially no menu get rendered:
>>> masterMenu.update()
>>> masterMenu.render()
u''
Now we register a menu tab which is also a viewlet manager:
>>> from zope.browserpage import viewpagetemplatefile
>>> from z3c.menu.simple import ITab
>>> from z3c.menu.simple.menu import Tab
>>> class MyTabs(Tab):
... template = viewpagetemplatefile.ViewPageTemplateFile('tab.pt')
>>> myTabs = MyTabs(content, request, view)
Also here, initially no tab get rendered:
>>> myTabs.update()
>>> myTabs.render()
u''
Now we register a menu action which is also a viewlet manager:
>>> from z3c.menu.simple import IAction
>>> from z3c.menu.simple.menu import Action
>>> class MyActions(Action):
... template = viewpagetemplatefile.ViewPageTemplateFile('action.pt')
>>> myActions = MyActions(content, request, view)
Also here, initially no tab get rendered:
>>> myActions.update()
>>> myActions.render()
u''
After setup the `TabMenu`, `Tab` and `Action` viewlet managers, we start to
register a tab menu item:
>>> from z3c.menu.simple.menu import TabItem
>>> class MyTab(TabItem):
...
... __name__ = u'MyTab'
... url = 'myTab.html'
... selectedViewNames = ['myTab.html']
>>> tabChecker = NamesChecker(('update', 'render', 'css', 'selected'))
>>> defineChecker(MyTab, tabChecker)
>>> zope.component.provideAdapter(
... MyTab,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, ITab),
... IViewlet, name='MyTab')
Now see what we get if the tab viewlet manager get rendered:
>>> myTabs.update()
>>> print myTabs.render()
<div class="tabMenu">
<span class="inactive-menu-item">
<a href="myTab.html">MyTab</a>
</span>
</div>
After showing how a tab menu item get used, we will register a menu action
item.
>>> from z3c.menu.simple.menu import ActionItem
>>> class MyAction(ActionItem):
...
... __name__ = u'MyAction'
... title = 'myAction'
>>> actionChecker = NamesChecker(('update', 'render', 'title'))
>>> defineChecker(MyAction, actionChecker)
>>> zope.component.provideAdapter(
... MyAction,
... (zope.interface.Interface, IDefaultBrowserLayer,
... IBrowserView, IAction),
... IViewlet, name='MyAction')
Now see what we get if the action viewlet manager get used:
>>> myActions.update()
>>> print myActions.render()
<div class="actionMenuWrapper">
<ul class="actionMenu">
<li class="inactive-menu-item">
<a href="">
<div>myAction</div>
</a>
</li>
</ul>
</div>
<div class="clearActionMenu" />
| z3c.menu.simple | /z3c.menu.simple-0.6.0.tar.gz/z3c.menu.simple-0.6.0/src/z3c/menu/simple/README.txt | README.txt |
__docformat__ = 'restructuredtext'
import zope.component
import zope.interface
from zope.contentprovider.interfaces import IContentProvider
from zope.viewlet import viewlet
from zope.viewlet import manager
from zope.app.component import hooks
from zope.app.publisher.browser import menu
from zope.app.publisher.interfaces.browser import IBrowserMenu
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from zope.traversing.browser.absoluteurl import absoluteURL
from z3c.i18n import MessageFactory as _
from z3c.menu.simple.interfaces import ISimpleMenuItem
from z3c.menu.simple.interfaces import ITabMenu
from z3c.menu.simple.interfaces import ITab
from z3c.menu.simple.interfaces import IAction
# ISimpleMenuItem implementation
class SimpleMenuItem(viewlet.ViewletBase):
"""Selectable menu item."""
zope.interface.implements(ISimpleMenuItem)
template = ViewPageTemplateFile('menu_item.pt')
selectedViewNames = None
activeCSS = u'active-menu-item'
inActiveCSS = u'inactive-menu-item'
@property
def title(self):
return _(self.__name__)
@property
def url(self):
return u''
@property
def extras(self):
return {}
@property
def selected(self):
name = self.__parent__.__name__
if self.selectedViewNames is None:
if name == self.url:
return True
elif name in self.selectedViewNames:
return True
return False
@property
def css(self):
if self.selected:
return self.activeCSS
else:
return self.inActiveCSS
def render(self):
"""Return the template with the option 'menus'"""
return self.template()
class ContextMenuItem(SimpleMenuItem):
"""Menu item viewlet generating context related links."""
urlEndings = []
viewURL = u''
@property
def selected(self):
requestURL = self.request.getURL()
for urlEnding in self.urlEndings:
if requestURL.endswith(urlEnding):
return True
return False
@property
def url(self):
contextURL = absoluteURL(self.context, self.request)
return contextURL + '/' + self.viewURL
class GlobalMenuItem(SimpleMenuItem):
"""Menu item viewlet generating global/site related links."""
urlEndings = []
viewURL = u''
@property
def selected(self):
requestURL = self.request.getURL()
for urlEnding in self.urlEndings:
if requestURL.endswith(urlEnding):
return True
return False
@property
def url(self):
siteURL = absoluteURL(hooks.getSite(), self.request)
return siteURL + '/' + self.viewURL
# ITabMenu implementation
class TabMenu(object):
"""Tab menu offering tabs and actions."""
zope.interface.implements(ITabMenu)
def __init__(self, context, request, view):
self.__parent__ = view
self.context = context
self.request = request
def update(self):
"""See zope.contentprovider.interfaces.IContentProvider"""
self.tabs = zope.component.queryMultiAdapter(
(self.context, self.request, self.__parent__), IContentProvider,
'ITab')
if self.tabs is not None:
self.tabs.update()
self.actions = zope.component.queryMultiAdapter(
(self.context, self.request, self.__parent__), IContentProvider,
'IAction')
if self.actions is not None:
self.actions.update()
def render(self):
"""See zope.contentprovider.interfaces.IContentProvider"""
result = u''
if self.tabs is not None:
result += self.tabs.render()
if self.actions is not None:
result += self.actions.render()
return result
class Tab(manager.WeightOrderedViewletManager):
"""Tab Menu"""
zope.interface.implements(ITab)
def render(self):
"""Return the template with the option 'menus'"""
if not self.viewlets:
return u''
return self.template()
class TabItem(SimpleMenuItem):
"""Base implementation for menu items."""
zope.interface.implements(ISimpleMenuItem)
template = ViewPageTemplateFile('tab_item.pt')
class Action(manager.WeightOrderedViewletManager):
"""Action Menu"""
zope.interface.implements(IAction)
def render(self):
"""Return the template with the option 'menus'"""
if not self.viewlets:
return u''
return self.template()
class ActionItem(SimpleMenuItem):
"""Base implementation for action items."""
zope.interface.implements(ISimpleMenuItem)
template = ViewPageTemplateFile('action_item.pt')
class BrowserMenu(TabMenu):
"""Menu Action Menu Items
A special tab menu, which takes its items from a browser menu
"""
template = ViewPageTemplateFile('browser_menu_action_item.pt')
# This is the name of the menu
menuId = None
def update(self):
menu = zope.component.getUtility(IBrowserMenu, self.menuId)
self.title = menu.title
self.menuItems = menu.getMenuItems(self.context, self.request)
def render(self):
"""Return the template with the option 'menus'"""
if not self.menuItems:
return u''
return self.template() | z3c.menu.simple | /z3c.menu.simple-0.6.0.tar.gz/z3c.menu.simple-0.6.0/src/z3c/menu/simple/menu.py | menu.py |
from zope import interface, schema
from zope.configuration import fields
from zope.app.event import interfaces as event_ifaces
class IMetric(interface.Interface):
"""Defines what values are to be collected for an object."""
class IAttributeMetric(IMetric):
"""Retrieves the metric value from an interface field."""
interface = fields.GlobalInterface(
title=u'The interface to adapt the object to',
required=True)
field_name = fields.PythonIdentifier(
title=u'The interface field name of the value',
required=True)
field_callable = fields.Bool(
title=u'The interface field name of the value',
required=False, default=False)
class ISelfMetric(IAttributeMetric):
"""Initializes the object score and uses attribute value."""
class IIndex(interface.Interface):
initial = interface.Attribute('Initial Score')
scale = interface.Attribute('Scale')
def __contains__(obj):
"""Returns True if the object has a score"""
def changeScoreFor(obj, amount):
"""Change the score for the object by the amount"""
def getScoreFor(obj):
"""Get the score for an object"""
def initScoreFor(obj):
"""Initialize the score for the object"""
def buildScoreFor(obj):
"""Build the score for the object from scratch"""
def changeScoreFor(obj, amount):
"""Change the score for the object by the amount"""
def removeScoreFor(obj):
"""Remove the score for the object from the index"""
class IScale(interface.Interface):
"""Translates metric values into scaled values for storage in the
index. The scale is also responsible for normalizing raw scores
into meaningful normalized scores on query time."""
def fromValue(value):
"""Return the scaled value for the metric value"""
def toValue(scaled):
"""Return the metric value for the scaled value"""
def normalize(raw, query=None):
"""Normalize the raw score acording to the scale. Some scales
may make use of a query."""
class ISubscription(interface.Interface):
"""Associates a metric with an index and any parameters needed by
the engine that are specific to the combination of metric and
index."""
def getIndex(context=None):
"""Return the index for this subscription. Some subscriptions
may accept a context argument for looking up the index."""
class IWeightedSubscription(interface.Interface):
"""A subscription that multiplies metric values by the weight."""
weight = schema.Float(title=u'Weight', required=False, default=1.0)
class IUtilitySubscription(interface.Interface):
"""The subscribed index is looked up as a utility."""
utility_interface = fields.GlobalInterface(
title=u'Index Utility Interface',
required=False, default=IIndex)
class IUtilityWeightedSubscription(IUtilitySubscription,
IWeightedSubscription):
"""ZCML directive for subscribing a metric to an index with a
weight."""
class IEngine(interface.Interface):
"""Process a values returned by a metric and update the raw score
in the index."""
metric = interface.Attribute('Metric')
subscription = interface.Attribute('Subscription')
context = interface.Attribute('Context')
def initScore():
"""Initialize the score for the context to the index"""
def addValue(value):
"""Add the value to the score for the context in the index"""
def changeValue(previous, current):
"""Add the difference in values to the score for the context
in the index"""
def removeValue(value):
"""Remove the value from the score for the context in the
index"""
def removeScore():
"""Remove the score for the context from the index"""
class IChangeScoreEvent(event_ifaces.IObjectEvent):
"""Change an object's score.
These events are used under normal operation for incrementally
updating a score in response to normal events on the object.
These events are dispatched "up" to the scored object."""
class IIndexesScoreEvent(event_ifaces.IObjectEvent):
"""If indexes is not None, the metrics will only apply the score
changes to the indexes listed."""
indexes = interface.Attribute('Indexes')
class IBuildScoreEvent(IIndexesScoreEvent):
"""Build an object's score.
These events are used for maintenance operations to build an
object's score from scratch. These events are dispatched
"down" from the scored object to the objects whose values
contribute to the score."""
class IAddValueEvent(event_ifaces.IObjectEvent):
"""Add a value from the object's score.
These events are handled by the metrics to add values to the
object's score and are independent of the direction of dispatch."""
class IInitScoreEvent(IAddValueEvent):
"""Initialize the object's score only when not building.
These events are handled by the metrics to initialize the object's
score and are independent of the direction of dispatch."""
class IRemoveValueEvent(event_ifaces.IObjectEvent):
"""Remove a value from the object's score.
These events are handled by the metrics to remove values from the
object's score and are independent of the direction of
dispatch."""
class ICreated(interface.Interface):
"""List the creators of an object."""
creators = interface.Attribute('Creators')
class ICreatorLookup(interface.Interface):
"""Lookup creators by id.""" | z3c.metrics | /z3c.metrics-0.1.tar.gz/z3c.metrics-0.1/z3c/metrics/interfaces.py | interfaces.py |
from zope import interface, component
from zope.schema import fieldproperty
import persistent
from z3c.metrics import interfaces, engine
default = object()
class Subscription(object):
@component.adapter(interfaces.IMetric,
interface.Interface,
interfaces.IChangeScoreEvent)
@interface.implementer(interfaces.IEngine)
def getChangeScoreEngine(self, metric, context, event, *args):
return self.engine_factory(metric, self, context)
@component.adapter(interfaces.IMetric,
interface.Interface,
interfaces.IIndexesScoreEvent)
@interface.implementer(interfaces.IEngine)
def getBuildScoreEngine(self, metric, context, event, *args):
if self.getIndex(context) in event.indexes:
return self.engine_factory(metric, self, context)
class WeightedSubscription(Subscription):
interface.implements(interfaces.IWeightedSubscription)
engine_factory = engine.WeightedEngine
weight = fieldproperty.FieldProperty(
interfaces.IWeightedSubscription['weight'])
class ILocalSubscription(interfaces.ISubscription):
"""The subscribed index is stored on an attribute."""
index = interface.Attribute('Index')
class LocalSubscription(persistent.Persistent):
interface.implements(ILocalSubscription)
component.adapts(interfaces.IIndex)
def __init__(self, index):
self.index = index
def getIndex(self, context=None):
return self.index
class UtilitySubscription(object):
interface.implements(interfaces.IUtilitySubscription,
interfaces.ISubscription)
utility_interface = fieldproperty.FieldProperty(
interfaces.IUtilitySubscription['utility_interface'])
def __init__(self, utility_interface=default):
if utility_interface is not default:
self.utility_interface = utility_interface
def getIndex(self, context=None):
return component.getUtility(
self.utility_interface, context=context)
class UtilityWeightedSubscription(WeightedSubscription,
UtilitySubscription):
pass
class LocalWeightedSubscription(WeightedSubscription,
LocalSubscription):
pass | z3c.metrics | /z3c.metrics-0.1.tar.gz/z3c.metrics-0.1/z3c/metrics/subscription.py | subscription.py |
.. -*-Doctest-*-
===========
z3c.metrics
===========
Create two document indexes.
>>> from z3c.metrics import testing
>>> foo_doc_index = testing.Index()
>>> bar_doc_index = testing.Index()
Create one creator index.
>>> creator_index = testing.Index()
Set the scales for the indexes. The defaults for scales is a half
life of one unit. In the case of a datetime scale, the half life is
one year.
>>> from z3c.metrics import scale
>>> one_year_scale = scale.ExponentialDatetimeScale()
>>> foo_doc_index.scale = one_year_scale
>>> creator_index.scale = one_year_scale
Specify a half life of two years for the second document index.
>>> two_year_scale = scale.ExponentialDatetimeScale(
... scale_unit=scale.one_year*2)
>>> bar_doc_index.scale = two_year_scale
Create a self metric that scores the creation dates of the object
itself.
>>> from z3c.metrics import interfaces, metric
>>> self_metric = metric.SelfMetric(
... field_name="created", interface=interfaces.ICreated)
Register the self metric event handlers so that they are run on
documents themselves for their own scores.
>>> from zope import component
>>> component.provideHandler(
... factory=self_metric.initSelfScore,
... adapts=[testing.IDocument, interfaces.IAddValueEvent])
>>> component.provideHandler(
... factory=self_metric.removeSelfScore,
... adapts=[testing.IDocument, interfaces.IRemoveValueEvent])
Create an other metric that scores creation dates of descendants.
>>> desc_metric = metric.OtherMetric(
... interface=interfaces.ICreated,
... field_name="created", field_callable=True)
Register the other metric event handlers so that they are run on
descendants of documents for document scores.
>>> component.provideHandler(
... factory=desc_metric.addOtherValue,
... adapts=[testing.IDescendant,
... interfaces.IAddValueEvent,
... testing.IDocument])
>>> component.provideHandler(
... factory=desc_metric.removeOtherValue,
... adapts=[testing.IDescendant,
... interfaces.IRemoveValueEvent,
... testing.IDocument])
Creat an init metric that initializes the score for new creators.
>>> from zope.app.security import interfaces as security_ifaces
>>> init_metric = metric.InitMetric()
Register the init metric event handlers so that they are run when
creators are added and removed.
>>> component.provideHandler(
... factory=init_metric.initSelfScore,
... adapts=[security_ifaces.IPrincipal,
... interfaces.IInitScoreEvent])
>>> component.provideHandler(
... factory=init_metric.removeSelfScore,
... adapts=[security_ifaces.IPrincipal,
... interfaces.IRemoveValueEvent])
Register the other metric event handlers so that they are run on
documents for creators' scores.
>>> other_metric = metric.OtherMetric(
... field_name="created", interface=interfaces.ICreated)
>>> from zope.app.security import interfaces as security_ifaces
>>> component.provideHandler(
... factory=other_metric.addOtherValue,
... adapts=[testing.IDocument,
... interfaces.IAddValueEvent,
... security_ifaces.IPrincipal])
>>> component.provideHandler(
... factory=other_metric.removeOtherValue,
... adapts=[testing.IDocument,
... interfaces.IRemoveValueEvent,
... security_ifaces.IPrincipal])
Register the other metric event handlers so that they are run on
descendants of documents for creators' scores.
>>> component.provideHandler(
... factory=desc_metric.addOtherValue,
... adapts=[testing.IDescendant,
... interfaces.IAddValueEvent,
... security_ifaces.IPrincipal])
>>> component.provideHandler(
... factory=desc_metric.removeOtherValue,
... adapts=[testing.IDescendant,
... interfaces.IRemoveValueEvent,
... security_ifaces.IPrincipal])
Create a principal as a creator.
>>> from z3c.metrics import testing
>>> authentication = component.getUtility(
... security_ifaces.IAuthentication)
>>> baz_creator = testing.Principal()
>>> authentication['baz_creator'] = baz_creator
Create a root container.
>>> root = testing.setUpRoot()
Create one document before any metrics are added to any indexes.
>>> foo_doc = testing.Document()
>>> foo_doc.created = scale.epoch
>>> foo_doc.creators = ('baz_creator',)
>>> root['foo_doc'] = foo_doc
Create a descendant of the document that will be included in the score
for the document.
>>> now = scale.epoch+scale.one_year*2
>>> foo_desc = testing.Descendant()
>>> foo_desc.created = now
>>> foo_desc.creators = ('baz_creator',)
>>> foo_doc['foo_desc'] = foo_desc
The indexes have no metrics yet, so they have no scores for the
documents.
>>> foo_doc_index.getScoreFor(foo_doc)
Traceback (most recent call last):
KeyError: ...
>>> bar_doc_index.getScoreFor(foo_doc)
Traceback (most recent call last):
KeyError: ...
>>> creator_index.getScoreFor(baz_creator)
Traceback (most recent call last):
KeyError: ...
Add the self metric to the first document index with the default
weight.
>>> from z3c.metrics import subscription
>>> foo_self_sub = subscription.LocalWeightedSubscription(
... foo_doc_index)
>>> component.provideSubscriptionAdapter(
... factory=foo_self_sub.getChangeScoreEngine,
... adapts=[interfaces.IMetric, testing.IDocument,
... interfaces.IChangeScoreEvent])
>>> component.provideSubscriptionAdapter(
... factory=foo_self_sub.getBuildScoreEngine,
... adapts=[interfaces.IMetric, testing.IDocument,
... interfaces.IBuildScoreEvent])
Add the self metric to the other document index but with a weight of
two.
>>> bar_self_sub = subscription.LocalWeightedSubscription(
... bar_doc_index)
>>> bar_self_sub.weight = 2.0
>>> component.provideSubscriptionAdapter(
... factory=bar_self_sub.getChangeScoreEngine,
... adapts=[interfaces.IMetric,
... testing.IDocument,
... interfaces.IChangeScoreEvent])
>>> component.provideSubscriptionAdapter(
... factory=bar_self_sub.getBuildScoreEngine,
... adapts=[interfaces.IMetric,
... testing.IDocument,
... interfaces.IBuildScoreEvent])
Also add the other metric to this index for descendants of documents.
>>> bar_desc_sub = subscription.LocalWeightedSubscription(
... bar_doc_index)
>>> component.provideSubscriptionAdapter(
... factory=bar_desc_sub.getChangeScoreEngine,
... adapts=[interfaces.IMetric,
... testing.IDocument,
... interfaces.IChangeScoreEvent,
... testing.IDescendant])
>>> component.provideSubscriptionAdapter(
... factory=bar_desc_sub.getBuildScoreEngine,
... adapts=[interfaces.IMetric,
... testing.IDocument,
... interfaces.IBuildScoreEvent,
... testing.IDescendant])
Add the init metric to the creator index for creators.
>>> creator_init_sub = subscription.LocalWeightedSubscription(
... creator_index)
>>> component.provideSubscriptionAdapter(
... factory=creator_init_sub.getChangeScoreEngine,
... adapts=[interfaces.IMetric,
... security_ifaces.IPrincipal,
... interfaces.IChangeScoreEvent])
>>> component.provideSubscriptionAdapter(
... factory=creator_init_sub.getBuildScoreEngine,
... adapts=[interfaces.IMetric,
... security_ifaces.IPrincipal,
... interfaces.IBuildScoreEvent])
Add the other metric to the creator index for document creators with a
weight of two.
>>> creator_doc_sub = subscription.LocalWeightedSubscription(
... creator_index)
>>> creator_doc_sub.weight = 2.0
>>> component.provideSubscriptionAdapter(
... factory=creator_doc_sub.getChangeScoreEngine,
... adapts=[interfaces.IMetric,
... security_ifaces.IPrincipal,
... interfaces.IChangeScoreEvent,
... testing.IDocument])
>>> component.provideSubscriptionAdapter(
... factory=creator_doc_sub.getBuildScoreEngine,
... adapts=[interfaces.IMetric, security_ifaces.IPrincipal,
... interfaces.IBuildScoreEvent, testing.IDocument])
Add the other metric to the creator index for document descendant
creators with the default weight.
>>> creator_desc_sub = subscription.LocalWeightedSubscription(
... creator_index)
>>> component.provideSubscriptionAdapter(
... factory=creator_desc_sub.getChangeScoreEngine,
... adapts=[interfaces.IMetric,
... security_ifaces.IPrincipal,
... interfaces.IChangeScoreEvent,
... testing.IDescendant])
>>> component.provideSubscriptionAdapter(
... factory=creator_desc_sub.getBuildScoreEngine,
... adapts=[interfaces.IMetric,
... security_ifaces.IPrincipal,
... interfaces.IBuildScoreEvent,
... testing.IDescendant])
Build scores for the document.
>>> foo_doc_index.buildScoreFor(foo_doc)
>>> bar_doc_index.buildScoreFor(foo_doc)
Now the document has different scores in both indexes.
>>> foo_doc_index.getScoreFor(foo_doc, query=now)
0.25
>>> bar_doc_index.getScoreFor(foo_doc, query=now)
2.0
Build the score for the creator.
>>> creator_index.buildScoreFor(baz_creator)
Now the creators have scores in the creator index.
>>> creator_index.getScoreFor(baz_creator, query=now)
1.5
Add a new creator.
>>> qux_creator = testing.Principal()
>>> authentication['qux_creator'] = qux_creator
The new creator now also has the correct score
>>> creator_index.getScoreFor(qux_creator, query=now)
0.0
Create a new document with two creators.
>>> bar_doc = testing.Document()
>>> bar_doc.created = now
>>> bar_doc.creators = ('baz_creator', 'qux_creator')
>>> root['bar_doc'] = bar_doc
The indexes have scores for the new document.
>>> foo_doc_index.getScoreFor(bar_doc, query=now)
1.0
>>> bar_doc_index.getScoreFor(bar_doc, query=now)
2.0
>>> creator_index.getScoreFor(baz_creator, query=now)
3.5
>>> creator_index.getScoreFor(qux_creator, query=now)
2.0
The scores are the same if rebuilt.
>>> foo_doc_index.buildScoreFor(bar_doc)
>>> bar_doc_index.buildScoreFor(bar_doc)
>>> creator_index.buildScoreFor(baz_creator)
>>> creator_index.buildScoreFor(qux_creator)
>>> foo_doc_index.getScoreFor(bar_doc, query=now)
1.0
>>> bar_doc_index.getScoreFor(bar_doc, query=now)
2.0
>>> creator_index.getScoreFor(baz_creator, query=now)
3.5
>>> creator_index.getScoreFor(qux_creator, query=now)
2.0
Later, add two descendants for this document.
>>> now = scale.epoch+scale.one_year*4
>>> bar_desc = testing.Descendant()
>>> bar_desc.created = now
>>> bar_doc['bar_desc'] = bar_desc
>>> baz_desc = testing.Descendant()
>>> baz_desc.created = now
>>> bar_doc['baz_desc'] = baz_desc
The scores reflect the addtions.
>>> foo_doc_index.getScoreFor(bar_doc, query=now)
0.25
>>> bar_doc_index.getScoreFor(bar_doc, query=now)
3.0
The scores for the other document also reflect the advance of time.
>>> foo_doc_index.getScoreFor(foo_doc, query=now)
0.0625
>>> bar_doc_index.getScoreFor(foo_doc, query=now)
1.0
>>> creator_index.getScoreFor(baz_creator, query=now)
0.875
>>> creator_index.getScoreFor(qux_creator, query=now)
0.5
The scores are the same if rebuilt.
>>> foo_doc_index.buildScoreFor(foo_doc)
>>> bar_doc_index.buildScoreFor(foo_doc)
>>> foo_doc_index.buildScoreFor(bar_doc)
>>> bar_doc_index.buildScoreFor(bar_doc)
>>> creator_index.buildScoreFor(baz_creator)
>>> creator_index.buildScoreFor(qux_creator)
>>> foo_doc_index.getScoreFor(foo_doc, query=now)
0.0625
>>> bar_doc_index.getScoreFor(foo_doc, query=now)
1.0
>>> foo_doc_index.getScoreFor(bar_doc, query=now)
0.25
>>> bar_doc_index.getScoreFor(bar_doc, query=now)
3.0
>>> creator_index.getScoreFor(baz_creator, query=now)
0.875
>>> creator_index.getScoreFor(qux_creator, query=now)
0.5
Remove one of the descendants.
>>> del bar_doc['bar_desc']
The scores reflect the deletion of the descendant.
>>> foo_doc_index.getScoreFor(bar_doc, query=now)
0.25
>>> bar_doc_index.getScoreFor(bar_doc, query=now)
2.0
The scores are the same if rebuilt.
>>> foo_doc_index.buildScoreFor(bar_doc)
>>> bar_doc_index.buildScoreFor(bar_doc)
>>> foo_doc_index.getScoreFor(bar_doc, query=now)
0.25
>>> bar_doc_index.getScoreFor(bar_doc, query=now)
2.0
Remove one of the documents.
>>> del root['bar_doc']
The document indexes no longer have scores for the document.
>>> foo_doc_index.getScoreFor(bar_doc)
Traceback (most recent call last):
KeyError: ...
>>> bar_doc_index.getScoreFor(bar_doc)
Traceback (most recent call last):
KeyError: ...
The creator indexes reflect the change.
>>> creator_index.getScoreFor(baz_creator, query=now)
0.375
>>> creator_index.getScoreFor(qux_creator, query=now)
0.0
XXX
===
For example, a metric may collect the date the object itself was
created. While another metric might collect the dates certain kinds
of descendants were created. Another yet might collect rating values
from certain kinds of descendants.
An index uses one or more metrics to provide efficient lookup of
normailized values for objects. One common use for such values is
sorting a set of objects. The score an index stores for an object is
the sum of the scores determined for each metric.
XXX Metrics
===========
Metrics define the values that constitute the score for an object in a
given metric index. Metrics update an object's score incrementally
and as such can only use values whose both previous and new values can
be retrieved on change.
For example, one value may be the creation date of a descendant. When
such a value changes, the metric can assume there was no previous
value. Likewise, when such an object is deleted, the metric must be
able to retrieve the creation date from the object before it is
deleted in order to make the incremental adjustment.
This is mostly a concern if a metric's values are mutable, then the
metric must be informed whenever that value changes in such a way that
it has access to both the preveious and new values. This should most
commonly be done using events to which the metric subscribes handlers.
A metric is a component that knows how to look up metric values for a
given object.
Note that if we don't count on event order, then building an object
score from scratch requires explicitly initializing the index and
ensuring that none of the event handlers will initialize the socre for
the build score event. Otherwise, it's possible that the initializing
event handler will be called after other add value events and negate
their effect.
| z3c.metrics | /z3c.metrics-0.1.tar.gz/z3c.metrics-0.1/z3c/metrics/README.txt | README.txt |
import math, datetime, time
from zope import interface
from zope.cachedescriptors import property
import persistent
from z3c.metrics import interfaces
inf = 1e1000000
class ExponentialScale(persistent.Persistent):
interface.implements(interfaces.IScale)
origin = 1
@property.readproperty
def default(self):
return self.start
def __init__(self, scale_unit=1, scale_ratio=2,
start=1, min_unit=None):
self.scale_unit = self._fromDelta(scale_unit)
self.scale_ratio = scale_ratio
self.start = start
if min_unit is not None:
self.min_unit = self._fromDelta(min_unit)
self.origin = getOrigin(
self.min_unit, self.scale_unit, scale_ratio)
def _fromDelta(self, delta):
return delta
def _toDelta(self, quantity):
return quantity
def fromValue(self, value):
return self.origin*self.scale_ratio**(
self._fromDelta(value-self.start)/float(self.scale_unit))
def toValue(self, scaled):
return self.start + self._toDelta(
math.log(scaled/float(self.origin),
self.scale_ratio)*self.scale_unit)
def normalize(self, raw, query=None):
if query is None:
query = self.default
return raw/float(self.fromValue(query))
def getOrigin(min_unit, scale_unit, scale_ratio):
"""
The scale ratio to the power of the proportion of the minimum
guaranteed granularity to the scale unit is the proportion of the
number after the origin to the origin.
scale_ratio**(min_unit/scale_unit) == origin+1/origin
Solve the above for origin.
scale_ratio**(min_unit/scale_unit) == 1+1/origin
scale_ratio**(min_unit/scale_unit)-1 == 1/origin
"""
return 1/(scale_ratio**(
min_unit/float(scale_unit))-1)
def getRatio(scaled, scale_units, scale_unit, min_unit=None):
"""
Return the ratio such that the number of units will result in
scaled.
scaled == origin*scale_ratio**units
scaled == scale_ratio**units/(
scale_ratio**(min_unit/scale_unit)-1)
scaled*(scale_ratio**(
min_unit/scale_unit)-1) == scale_ratio**units
scale_ratio**(min_unit/scale_unit)-1 == scale_ratio**units/scaled
----------------------------
units == math.log(scaled/origin, scale_ratio)
units == math.log(
scaled*(scale_ratio**(min_unit/scale_unit)-1), scale_ratio)
1 == math.log(
(scaled*(scale_ratio**(min_unit/scale_unit)-1))**(1/unit), scale_ratio)
scale_ratio**units == scaled*(scale_ratio**(min_unit/scale_unit)-1)
"""
raise NotImplementedError
epoch = datetime.datetime(*time.gmtime(0)[:3])
one_day = datetime.timedelta(1)
one_year = one_day*365
seconds_per_day = 24*60*60
class ExponentialDatetimeScale(ExponentialScale):
def __init__(self, scale_unit=one_year, scale_ratio=2,
start=epoch, min_unit=None):
super(ExponentialDatetimeScale, self).__init__(
scale_unit=scale_unit, scale_ratio=scale_ratio,
start=start, min_unit=min_unit)
@property.readproperty
def default(self):
return datetime.datetime.now()
def _fromDelta(self, delta):
"""Convert a time delta into a float of seconds"""
return (delta.days*seconds_per_day + delta.seconds +
delta.microseconds/float(1000000))
def _toDelta(self, quantity):
return datetime.timedelta(seconds=quantity) | z3c.metrics | /z3c.metrics-0.1.tar.gz/z3c.metrics-0.1/z3c/metrics/scale.py | scale.py |
from zope import interface
from zope.configuration import fields, config
from zope.app.component import metaconfigure
from z3c.metrics import interfaces, metric, subscription
default = object()
class IMetric(interfaces.IMetric):
"""Defines what values are to be collected for an object."""
for_ = fields.Tokens(
title=u'Interfaces of the objects the metric applied to',
required=True, value_type=fields.GlobalObject())
class IAttributeMetric(IMetric, interfaces.IAttributeMetric):
"""Retrieves the metric value from an interface field."""
class Metric(config.GroupingContextDecorator):
add_interface = interfaces.IAddValueEvent
remove_interface = interfaces.IRemoveValueEvent
def __init__(self, context, for_, **kw):
super(Metric, self).__init__(context, **kw)
self.metric = self.metric_factory(**kw)
self.object_interface = for_.pop(0)
self.for_ = for_
def before(self):
object_iface = self.handler_adapts[0]
other_ifaces = self.handler_adapts[1:]
metaconfigure.subscriber(
_context=self.context,
for_=[object_iface, self.add_interface]+other_ifaces,
handler=getattr(self.metric, self.add_handler))
metaconfigure.subscriber(
_context=self.context,
for_=[object_iface, self.remove_interface]+other_ifaces,
handler=getattr(self.metric, self.remove_handler))
@property
def handler_adapts(self):
return [self.object_interface]+self.for_
class InitMetric(Metric):
metric_factory = metric.InitMetric
add_interface = interfaces.IInitScoreEvent
add_handler = 'initSelfScore'
remove_handler = 'removeSelfScore'
class SelfMetric(Metric):
metric_factory = metric.SelfMetric
add_handler = 'initSelfScore'
remove_handler = 'removeSelfScore'
class OtherMetric(Metric):
metric_factory = metric.OtherMetric
add_handler = 'addOtherValue'
remove_handler = 'removeOtherValue'
@property
def handler_adapts(self):
return self.for_+[self.object_interface]
def weighted(_context, utility_interface, weight=default):
sub = subscription.UtilityWeightedSubscription(
utility_interface=utility_interface)
if weight is not default:
sub.weight = weight
provides, = interface.implementedBy(sub.getChangeScoreEngine)
metaconfigure.subscriber(
_context=_context, provides=provides,
for_=[interfaces.IMetric, _context.object_interface,
interfaces.IChangeScoreEvent]+_context.for_,
factory=sub.getChangeScoreEngine)
provides, = interface.implementedBy(sub.getBuildScoreEngine)
metaconfigure.subscriber(
_context=_context, provides=provides,
for_=[interfaces.IMetric, _context.object_interface,
interfaces.IIndexesScoreEvent]+_context.for_,
factory=sub.getBuildScoreEngine) | z3c.metrics | /z3c.metrics-0.1.tar.gz/z3c.metrics-0.1/z3c/metrics/meta.py | meta.py |
from zope import interface, component
from zope.app.component import hooks
from zope.app.location import interfaces as location_ifaces
from zope.app.container import interfaces as container_ifaces
from zope.app.security import interfaces as security_ifaces
from z3c.metrics import interfaces
class IAncestors(interface.Interface):
"""Iterate over the ancestors of a contained object."""
@component.adapter(container_ifaces.IContained)
@interface.implementer(IAncestors)
def getAncestors(contained):
ancestor = contained
while ancestor is not None:
yield ancestor
ancestor = ancestor.__parent__
@component.adapter(container_ifaces.IContained,
interfaces.IChangeScoreEvent)
def dispatchToAncestors(obj, event):
new_ancestors = []
if event.newParent is not None:
new_ancestors = list(IAncestors(event.newParent))
old_ancestors = []
if event.oldParent is not None:
old_ancestors = list(IAncestors(event.oldParent))
for new_idx in xrange(len(new_ancestors)):
new_ancestor = new_ancestors[new_idx]
if new_ancestor in old_ancestors:
old_idx = old_ancestors.index(new_ancestor)
new_ancestors = new_ancestors[:new_idx]
old_ancestors = old_ancestors[:old_idx]
break
event.newAncestors = new_ancestors
event.oldAncestors = old_ancestors
for ancestor in new_ancestors + old_ancestors:
for _ in component.subscribers(
[obj, event, ancestor], None):
pass # Just make sure the handlers run
@component.adapter(container_ifaces.IContainer,
interfaces.IBuildScoreEvent,
container_ifaces.IContainer)
def dispatchToDescendants(descendant, event, obj=None):
if obj is None:
obj = descendant
subs = location_ifaces.ISublocations(descendant, None)
if subs is not None:
for sub in subs.sublocations():
for ignored in component.subscribers(
(sub, event, obj), None):
pass # They do work in the adapter fetch
class CreatorLookup(object):
interface.implements(interfaces.ICreatorLookup)
component.adapts(interfaces.ICreated)
def __init__(self, context):
self.authentication = component.getUtility(
security_ifaces.IAuthentication, context=context)
def __call__(self, creator_id):
return self.authentication.getPrincipal(creator_id)
@component.adapter(interfaces.ICreated,
interfaces.IChangeScoreEvent)
def dispatchToCreators(obj, event):
creator_lookup = component.getAdapter(
obj, interfaces.ICreatorLookup)
for creator_id in interfaces.ICreated(obj).creators:
for _ in component.subscribers(
[obj, event, creator_lookup(creator_id)], None):
pass # Just make sure the handlers run
class ICreatedDispatchEvent(interface.Interface):
"""Dispatched to subloacations for matching on creators."""
event = interface.Attribute('Event')
creators = interface.Attribute('Creators')
class CreatedDispatchEvent(object):
interface.implements(ICreatedDispatchEvent)
def __init__(self, creators):
self.creators = creators
@component.adapter(security_ifaces.IPrincipal,
interfaces.IBuildScoreEvent)
def dispatchToSiteCreated(creator, event):
dispatched = CreatedDispatchEvent(set([creator.id]))
for _ in component.subscribers(
[hooks.getSite(), event, dispatched], None):
pass # Just make sure the handlers run
@component.adapter(interfaces.ICreated,
interfaces.IBuildScoreEvent,
ICreatedDispatchEvent)
def dispatchToCreated(obj, event, dispatched):
creator_lookup = component.getAdapter(
obj, interfaces.ICreatorLookup)
for creator_id in dispatched.creators.intersection(
interfaces.ICreated(obj).creators):
for _ in component.subscribers(
[obj, event, creator_lookup(creator_id)], None):
pass # Just make sure the handlers run | z3c.metrics | /z3c.metrics-0.1.tar.gz/z3c.metrics-0.1/z3c/metrics/dispatch.py | dispatch.py |
from zope import interface, component
from z3c.metrics import interfaces
class InitMetric(object):
interface.implements(interfaces.IMetric)
@component.adapter(interface.Interface,
interfaces.IInitScoreEvent)
def initSelfScore(self, obj, event):
for engine in component.subscribers(
[self, obj, event], interfaces.IEngine):
engine.initScore()
@component.adapter(interface.Interface,
interfaces.IRemoveValueEvent)
def removeSelfScore(self, obj, event):
for engine in component.subscribers(
[self, obj, event], interfaces.IEngine):
engine.removeScore()
class AttributeMetric(object):
interface.implements(interfaces.IAttributeMetric)
default_interface = None
default_field_name = None
def __init__(self, interface=None, field_name=None,
field_callable=False):
if interface is None and self.default_interface is None:
raise ValueError("Must pass an interface")
if interface is None:
self.interface = self.default_interface
else:
self.interface = interface
if field_name is None and self.default_field_name is None:
raise ValueError("Must pass a field_name")
if field_name is None:
self.field_name = self.default_field_name
else:
self.field_name = field_name
self.field_callable = field_callable
def getValueFor(self, obj):
obj = self.interface(obj)
value = getattr(obj, self.field_name)
if self.field_callable:
value = value()
return value
class SelfMetric(InitMetric, AttributeMetric):
@component.adapter(interface.Interface,
interfaces.IAddValueEvent)
def initSelfScore(self, obj, event):
value = self.getValueFor(obj)
init = interfaces.IInitScoreEvent.providedBy(event)
for engine in component.subscribers(
[self, obj, event], interfaces.IEngine):
if init:
engine.initScore()
engine.addValue(value)
class OtherMetric(AttributeMetric):
@component.adapter(interface.Interface,
interfaces.IAddValueEvent,
interface.Interface)
def addOtherValue(self, other, event, obj):
value = self.getValueFor(other)
for engine in component.subscribers(
[self, obj, event, other], interfaces.IEngine):
engine.addValue(value)
@component.adapter(interface.Interface,
interfaces.IRemoveValueEvent,
interface.Interface)
def removeOtherValue(self, other, event, obj):
value = self.getValueFor(other)
for engine in component.subscribers(
[self, obj, event, other], interfaces.IEngine):
engine.removeValue(value) | z3c.metrics | /z3c.metrics-0.1.tar.gz/z3c.metrics-0.1/z3c/metrics/metric.py | metric.py |
import persistent
from BTrees import family64, Length
from zope import interface
import zope.event
from zope.app.event import objectevent
from z3c.metrics import interfaces, scale
class ScoreError(Exception):
pass
class IndexesScoreEvent(objectevent.ObjectEvent):
interface.implements(interfaces.IIndexesScoreEvent)
def __init__(self, obj, indexes=()):
self.object = obj
self.indexes = indexes
class BuildScoreEvent(IndexesScoreEvent):
interface.implements(interfaces.IBuildScoreEvent,
interfaces.IAddValueEvent)
class Index(persistent.Persistent):
interface.implements(interfaces.IIndex)
family = family64.IF
def __init__(self, initial=0,
scale=scale.ExponentialDatetimeScale()):
self.initial = initial
self.scale = scale
self.clear()
def __contains__(self, obj):
docid = self._getKeyFor(obj)
return docid in self._scores
def _getKeyFor(self, obj):
raise NotImplementedError()
def clear(self):
self._scores = self.family.BTree()
self._num_docs = Length.Length(0)
def getScoreFor(self, obj, query=None):
docid = self._getKeyFor(obj)
raw = self._scores[docid]
return self.scale.normalize(raw, query)
def initScoreFor(self, obj):
docid = self._getKeyFor(obj)
self._num_docs.change(1)
self._scores[docid] = self.initial
def buildScoreFor(self, obj):
docid = self._getKeyFor(obj)
if docid not in self._scores:
self._num_docs.change(1)
self._scores[docid] = self.initial
zope.event.notify(
BuildScoreEvent(obj, [self]))
def changeScoreFor(self, obj, amount):
docid = self._getKeyFor(obj)
old = self._scores[docid]
self._scores[docid] = old + amount
if self._scores[docid] == scale.inf:
self._scores[docid] = old
raise ScoreError('Adding %s to %s for %s is too large' % (
amount, old, obj))
def removeScoreFor(self, obj):
docid = self._getKeyFor(obj)
del self._scores[docid]
self._num_docs.change(-1) | z3c.metrics | /z3c.metrics-0.1.tar.gz/z3c.metrics-0.1/z3c/metrics/index.py | index.py |
from zope import interface, component
from zope.testing import cleanup
import zope.event
from zope.app.container import contained
import Acquisition
from Products.CMFCore import interfaces as cmf_ifaces
from Products.CMFCore import utils as cmf_utils
from Products.CMFDefault import DiscussionItem
from z3c.metrics import interfaces
class ReplyCreatedEvent(contained.ObjectAddedEvent):
interface.implementsOnly(interfaces.IChangeScoreEvent,
interfaces.IAddValueEvent)
class ReplyDeletedEvent(contained.ObjectRemovedEvent):
interface.implementsOnly(interfaces.IChangeScoreEvent,
interfaces.IRemoveValueEvent)
def createReply(self, *args, **kw):
reply_id = createReply.orig(
self, *args, **kw)
zope.event.notify(ReplyCreatedEvent(
object=self.getReply(reply_id), newParent=self,
newName=reply_id))
return reply_id
createReply.orig = DiscussionItem.DiscussionItemContainer.createReply
def deleteReply(self, reply_id, *args, **kw):
reply = self.getReply(reply_id)
reply_id = deleteReply.orig(self, reply_id, *args, **kw)
zope.event.notify(ReplyDeletedEvent(
object=reply, oldParent=self, oldName=reply_id))
return reply_id
deleteReply.orig = DiscussionItem.DiscussionItemContainer.deleteReply
def patch():
DiscussionItem.DiscussionItemContainer.createReply = createReply
DiscussionItem.DiscussionItemContainer.deleteReply = deleteReply
def unpatch():
DiscussionItem.DiscussionItemContainer.createReply = (
createReply.orig)
DiscussionItem.DiscussionItemContainer.deleteReply = (
deleteReply.orig)
patch()
cleanup.addCleanUp(unpatch)
@component.adapter(cmf_ifaces.IDiscussionResponse,
interfaces.IChangeScoreEvent)
def dispatchToDiscussed(obj, event):
parent = event.newParent
if parent is None:
parent = event.oldParent
discussed = Acquisition.aq_parent(Acquisition.aq_inner(parent))
for _ in component.subscribers(
[obj, event, discussed], None):
pass # Just make sure the handlers run
@component.adapter(cmf_ifaces.IDiscussable,
interfaces.IBuildScoreEvent)
def dispatchToReplies(obj, event, dispatched=None):
portal_discussion = cmf_utils.getToolByName(
obj, 'portal_discussion')
if dispatched is None:
# For creator dispatch
dispatched = obj
for reply in portal_discussion.getDiscussionFor(obj).getReplies():
for _ in component.subscribers(
[reply, event, dispatched], None):
pass # Just make sure the handlers run | z3c.metrics | /z3c.metrics-0.1.tar.gz/z3c.metrics-0.1/z3c/metrics/zope2/discussion.py | discussion.py |
from zope import interface, component
from zope.dottedname import resolve
import DateTime
import Acquisition
from OFS import SimpleItem
from Products.ZCatalog import interfaces as zcatalog_ifaces
from Products.PluginIndexes import interfaces as plugidx_ifaces
from Products.PluginIndexes.TextIndex import Vocabulary
from Products.GenericSetup import interfaces as gs_ifaces
from Products.GenericSetup.PluginIndexes import exportimport
from z3c.metrics import interfaces, index
from z3c.metrics.zope2 import scale
class IRemoveScoreEvent(interfaces.IRemoveValueEvent):
"""Remove the object score from the index."""
class IAddSelfValueEvent(interfaces.IAddValueEvent):
"""Add self value with special handling for the index."""
# This is necessary because for the OFS/CMF/ZCatalog mess we need
# the self add handlers to trigger for initial indexing and
# rebuilding scores but not on object add
class InitIndexScoreEvent(index.IndexesScoreEvent):
interface.implements(interfaces.IInitScoreEvent,
IAddSelfValueEvent)
class RemoveIndexScoreEvent(index.IndexesScoreEvent):
interface.implements(IRemoveScoreEvent)
class IMetricsIndex(interfaces.IIndex,
plugidx_ifaces.IPluggableIndex):
"""sro"""
class MetricsIndex(index.Index, SimpleItem.SimpleItem):
"""A Metrics Index in a ZCatalog"""
interface.implements(IMetricsIndex)
def __init__(self, id, extra=None, caller=None):
self.id = id
self.__catalog_path = caller.getPhysicalPath()
if extra is None:
extra = Vocabulary._extra()
# TODO: the utility registration should be moved to an INode
# GS handler to be run after the index is added
utility_interface = extra.__dict__.pop(
'utility_interface', interfaces.IIndex)
utility_name = extra.__dict__.pop('utility_name', '')
scale_kw = {}
if 'start' in extra.__dict__:
scale_kw['start'] = DateTime.DateTime(
extra.__dict__.pop('start'))
if 'scale_unit' in extra.__dict__:
scale_kw['scale_unit'] = float(
extra.__dict__.pop('scale_unit'))
index_scale = scale.ExponentialDateTimeScale(**scale_kw)
super(MetricsIndex, self).__init__(
scale=index_scale, **extra.__dict__)
if isinstance(utility_interface, (str, unicode)):
utility_interface = resolve.resolve(utility_interface)
if not utility_interface.providedBy(self):
interface.alsoProvides(self, utility_interface)
sm = component.getSiteManager(context=caller)
reg = getattr(sm, 'registerUtility', None)
if reg is None:
reg = sm.provideUtility
reg(component=self, provided=utility_interface,
name=utility_name)
def _getCatalog(self):
zcatalog = Acquisition.aq_parent(Acquisition.aq_inner(
Acquisition.aq_parent(Acquisition.aq_inner(self))))
if not zcatalog_ifaces.IZCatalog.providedBy(zcatalog):
return self.restrictedTraverse(self.__catalog_path)
return zcatalog
def _getKeyFor(self, obj):
"""Get the key from the ZCatalog so that the index may be used
to score or sort ZCatalog results."""
return self._getCatalog().getrid(
'/'.join(obj.getPhysicalPath()))
def index_object(self, documentId, obj, threshold=None):
"""Run the initialize score metrics for this index only if
this is the first time the object is indexed."""
if documentId not in self._scores:
obj = self._getCatalog().getobject(documentId)
event = InitIndexScoreEvent(obj, [self])
component.subscribers([obj, event], None)
return True
return False
def unindex_object(self, documentId):
"""Run the remove value metrics for this index only when the
object is unindexed."""
obj = self._getCatalog().getobject(documentId)
event = RemoveIndexScoreEvent(obj, [self])
component.subscribers([obj, event], None)
class MetricsIndexNodeAdapter(exportimport.PluggableIndexNodeAdapter):
component.adapts(IMetricsIndex, gs_ifaces.ISetupEnviron)
__used_for__ = interfaces.IIndex
def _exportNode(self):
"""Export the object as a DOM node.
"""
node = self._getObjectNode('index')
return node
def _importNode(self, node):
"""Prevent the index from being cleared.
"""
pass
node = property(_exportNode, _importNode) | z3c.metrics | /z3c.metrics-0.1.tar.gz/z3c.metrics-0.1/z3c/metrics/zope2/index.py | index.py |
import os, shutil, sys, tempfile, urllib2
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
is_jython = sys.platform.startswith('java')
# parsing arguments
parser = OptionParser()
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="distribute", default=False,
help="Use Disribute rather than Setuptools.")
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.version is not None:
VERSION = '==%s' % options.version
else:
VERSION = ''
USE_DISTRIBUTE = options.distribute
args = args + ['bootstrap']
try:
import pkg_resources
import setuptools
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez = {}
if USE_DISTRIBUTE:
exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True)
else:
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
reload(sys.modules['pkg_resources'])
import pkg_resources
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
def quote (c):
return c
cmd = 'from setuptools.command.easy_install import main; main()'
ws = pkg_resources.working_set
if USE_DISTRIBUTE:
requirement = 'distribute'
else:
requirement = 'setuptools'
if is_jython:
import subprocess
assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd',
quote(tmpeggs), 'zc.buildout' + VERSION],
env=dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
).wait() == 0
else:
assert os.spawnle(
os.P_WAIT, sys.executable, quote (sys.executable),
'-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION,
dict(os.environ,
PYTHONPATH=
ws.find(pkg_resources.Requirement.parse(requirement)).location
),
) == 0
ws.add_entry(tmpeggs)
ws.require('zc.buildout' + VERSION)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | z3c.mountpoint | /z3c.mountpoint-0.1.tar.gz/z3c.mountpoint-0.1/bootstrap.py | bootstrap.py |
================
ZODB Mount Point
================
This package provides a very simple implementation of a mount point for an
object in another ZODB connection. If you have multiple connections defined in
your ``zope.conf`` configuration file or multiple databases defined in your
Python code, you can use this package to mount any object from any database at
any location of another database.
Let's start by creating two databases in the typical Zope 3 application layout:
>>> from ZODB.tests.test_storage import MinimalMemoryStorage
>>> from ZODB import DB
>>> from zope.site.folder import rootFolder, Folder
>>> import transaction
>>> dbmap = {}
>>> db1 = DB(MinimalMemoryStorage(), database_name='db1', databases=dbmap)
>>> conn1 = db1.open()
>>> conn1.root()['Application'] = rootFolder()
>>> db2 = DB(MinimalMemoryStorage(), database_name='db2', databases=dbmap)
>>> conn2 = db2.open()
>>> conn2.root()['Application'] = rootFolder()
>>> transaction.commit()
Let's now add a sub-folder to the second database, which will serve as the
object which we wish to mount:
>>> conn2.root()['Application']['Folder2-1'] = Folder()
>>> transaction.commit()
We can now create a mount point:
>>> from z3c.mountpoint import mountpoint
>>> mountPoint = mountpoint.MountPoint(
... 'db2', objectPath=u'/Folder2-1', objectName=u'F2-1')
The first argument to the constructor is the connection name of the database,
the second argument is the path to the mounted object within the mounted DB
and the object name is the name under which the object is mounted.
Now we can add the mount point to the first database:
>>> conn1.root()['Application']['mp'] = mountPoint
>>> transaction.commit()
We can now access the mounted object as follows:
>>> conn1.root()['Application']['mp'].object
<zope.site.folder.Folder object at ...>
Note that the object name is not yet used; it is for traversal only.
Traversal
---------
So let's have a look at the traversal next. Before being able to traverse, we
need to register the special mount point traverser:
>>> import zope.component
>>> zope.component.provideAdapter(mountpoint.MountPointTraverser)
We should now be able to traverse to the mounted object now:
>>> from zope.publisher.browser import TestRequest
>>> req = TestRequest()
>>> from zope.traversing.publicationtraverse import PublicationTraverser
>>> traverser = PublicationTraverser()
>>> traverser.traversePath(req, conn1.root()['Application'], 'mp/F2-1')
<zope.site.folder.Folder object at ...>
When we add a new object remotely, it available via the mount point as well:
>>> conn2.root()['Application']['Folder2-1']['Folder2-1.1'] = Folder()
>>> transaction.commit()
>>> tuple(traverser.traversePath(
... req, conn1.root()['Application'], 'mp/F2-1').keys())
(u'Folder2-1.1',)
Now, by default the objects refer to their original path:
>>> f211 = traverser.traversePath(
... req, conn1.root()['Application'], 'mp/F2-1/Folder2-1.1')
>>> from zope.traversing.browser import absoluteurl
>>> absoluteurl.absoluteURL(f211, req)
'http://127.0.0.1/Folder2-1/Folder2-1.1'
This package solves that problem by wrapping all object by a special remote
location proxy and providing a special wrapping traverser for those proxies:
>>> from z3c.mountpoint import remoteproxy
>>> zope.component.provideAdapter(remoteproxy.RemoteLocationProxyTraverser)
>>> f211 = traverser.traversePath(
... req, conn1.root()['Application'], 'mp/F2-1/Folder2-1.1')
>>> absoluteurl.absoluteURL(f211, req)
'http://127.0.0.1/mp/F2-1/Folder2-1.1'
Updating the Mount Point
------------------------
Whenever any attribute on the mount point is modified, the mount object is
updated. For example, when the object path is changed, the object is adjusted
as well. This is done with an event subscriber:
>>> mountPoint.objectPath = u'/Folder2-1/Folder2-1.1'
>>> modifiedEvent = object()
>>> mountpoint.updateMountedObject(mountPoint, modifiedEvent)
>>> f211 == mountPoint.object
True
| z3c.mountpoint | /z3c.mountpoint-0.1.tar.gz/z3c.mountpoint-0.1/src/z3c/mountpoint/README.txt | README.txt |
__docformat__ = "reStructuredText"
import zope.interface
from zope.interface import declarations
from zope.proxy import getProxiedObject, removeAllProxies
from zope.proxy.decorator import DecoratorSpecificationDescriptor
from zope.publisher.interfaces.browser import IBrowserPublisher, IBrowserRequest
from z3c.mountpoint import interfaces
class RemoteLocationProxyDecoratorSpecificationDescriptor(
DecoratorSpecificationDescriptor):
def __get__(self, inst, cls=None):
if inst is None:
return declarations.getObjectSpecification(cls)
else:
provided = zope.interface.providedBy(getProxiedObject(inst))
# Use type rather than __class__ because inst is a proxy and
# will return the proxied object's class.
cls = type(inst)
# Create a special version of Provides, which forces the remote
# location proxy to the front, so that a special traverser can be
# enforced.
return declarations.Provides(
cls, interfaces.IRemoteLocationProxy, provided)
class RemoteLocationProxy(zope.location.LocationProxy):
"""A location proxy for remote objects."""
__providedBy__ = RemoteLocationProxyDecoratorSpecificationDescriptor()
class RemoteLocationProxyTraverser(object):
zope.component.adapts(interfaces.IRemoteLocationProxy, IBrowserRequest)
zope.interface.implements(IBrowserPublisher)
def __init__(self, context, request):
self.context = context
self.request = request
def browserDefault(self, request):
ob = self.context
view_name = zapi.getDefaultViewName(ob, request)
return ob, (view_name,)
def publishTraverse(self, request, name):
pureContext = removeAllProxies(self.context)
traverser = zope.component.getMultiAdapter(
(pureContext, self.request), IBrowserPublisher)
result = traverser.publishTraverse(request, name)
# Only remove the security proxy from the context.
return RemoteLocationProxy(result, getProxiedObject(self.context), name) | z3c.mountpoint | /z3c.mountpoint-0.1.tar.gz/z3c.mountpoint-0.1/src/z3c/mountpoint/remoteproxy.py | remoteproxy.py |
__docformat__ = "reStructuredText"
import persistent
import zope.component
import zope.interface
import zope.lifecycleevent
import zope.location
from zope.app.container import contained
from zope.app.publication import traversers
from zope.publisher.interfaces.browser import IBrowserRequest, IBrowserPublisher
from zope.security.proxy import removeSecurityProxy
from zope.traversing import api
from z3c.mountpoint import interfaces, remoteproxy
class MountPoint(persistent.Persistent, contained.Contained):
"""A simple mount point."""
zope.interface.implements(interfaces.IMountPoint)
def __init__(self, connectionName=None, objectPath=u'/', objectName=u'object'):
self.connectionName = connectionName
self.objectPath = objectPath
self.objectName = objectName
self.object = None
def update(self):
parent = self.__parent__
if parent is not None:
# Get the connection by name
conn = parent._p_jar.get_connection(self.connectionName)
obj = conn.root()['Application']
obj = api.traverse(obj, self.objectPath)
self.object = obj
else:
self.object = None
@apply
def __parent__():
def get(self):
return self and self.__dict__.get('__parent__', None)
def set(self, parent):
self.__dict__['__parent__'] = parent
self.update()
return property(get, set)
class MountPointTraverser(traversers.SimpleComponentTraverser):
zope.component.adapts(interfaces.IMountPoint, IBrowserRequest)
zope.interface.implementsOnly(IBrowserPublisher)
def publishTraverse(self, request, name):
if name == self.context.objectName:
# Remove the security proxy, because we need a bare object to wrap
# the location proxy around.
context = removeSecurityProxy(self.context)
return remoteproxy.RemoteLocationProxy(
context.object, context, self.context.objectName)
return super(MountPointTraverser, self).publishTraverse(
request, name)
@zope.component.adapter(
interfaces.IMountPoint, zope.lifecycleevent.IObjectModifiedEvent)
def updateMountedObject(mountPoint, event):
mountPoint.update() | z3c.mountpoint | /z3c.mountpoint-0.1.tar.gz/z3c.mountpoint-0.1/src/z3c/mountpoint/mountpoint.py | mountpoint.py |
===================
z3c.multifieldindex
===================
This package provides an index for zope catalog that can index multiple fields.
It is useful in cases when field set are dynamic (for example with customizable
persistent fields).
Actually, this package provides a base class for custom multi-field indexes and
to make it work, you need to override some methods in it. But first, let's
create a content schema and interface we will use:
>>> from zope.interface import Interface, implements
>>> from zope.schema import Text, Int, List, TextLine
>>> class IPerson(Interface):
...
... age = Int()
... info = Text()
... skills = List(value_type=TextLine())
>>> class Person(object):
...
... implements(IPerson)
...
... def __init__(self, age, info, skills):
... self.age = age
... self.info = info
... self.skills = skills
Let's create a set of person objects:
>>> dataset = [
... (1, Person(20, u'Sweet and cute', ['dancing', 'singing'])),
... (2, Person(33, u'Smart and sweet', ['math', 'dancing'])),
... (3, Person(6, u'Young and cute', ['singing', 'painting'])),
... ]
We have choose exactly those different types of fields to illustrate that the
index is smart enough to know how to index each type of value. We'll return
back to this topic later in this document.
Now, we need to create an multi-field index class that will be used to index our
person objects. We'll override two methods in it to make it functional:
>>> from z3c.multifieldindex.index import MultiFieldIndexBase
>>> from zope.schema import getFields
>>> class PersonIndex(MultiFieldIndexBase):
...
... def _fields(self):
... return getFields(IPerson).items()
...
... def _getData(self, object):
... return {
... 'age': object.age,
... 'info': object.info,
... 'skills': object.skills,
... }
The "_fields" method should return an iterable of (name, field) pairs of fields
that should be indexed. The sub-indexes will be created for those fields.
The "_getData" method returns a dictionary of data to be indexed using given
object. The keys of the dictionary should match field names.
Sub-indexes are created automatically by looking up an index factory for each
field. Three most-used factories are provided by this package. Let's register
them to continue (it's also done in this package's configure.zcml file):
>>> from z3c.multifieldindex.subindex import DefaultIndexFactory
>>> from z3c.multifieldindex.subindex import CollectionIndexFactory
>>> from z3c.multifieldindex.subindex import TextIndexFactory
>>> from zope.component import provideAdapter
>>> provideAdapter(DefaultIndexFactory)
>>> provideAdapter(CollectionIndexFactory)
>>> provideAdapter(TextIndexFactory)
The default index factory creates zc.catalog's ValueIndex, the collection index
factory creates zc.catalog's SetIndex and the text index factory creates
zope.index's TextIndex. This is needed to know when you'll be doing queries.
Okay, now let's create an instance of index and prepare it to be used.
>>> index = PersonIndex()
>>> index.recreateIndexes()
The "recreateIndexes" does re-creation of sub-indexes. It is normally called
by a subscriber to IObjectAddedEvent, provided by this package, but we simply
call it by hand for this test.
Now, let's finally index our person objects:
>>> for docid, person in dataset:
... index.index_doc(docid, person)
Let's do a query now. The query format is quite simple. It is a dictionary, where
keys are names of fields and values are queries for sub-indexes.
>>> results = index.apply({
... 'skills': {'any_of': ('singing', 'painting')},
... })
>>> list(results)
[1, 3]
>>> results = index.apply({
... 'info': 'sweet',
... })
>>> list(results)
[1, 2]
>>> results = index.apply({
... 'age': {'between': (1, 30)},
... })
>>> list(results)
[1, 3]
>>> results = index.apply({
... 'age': {'between': (1, 30)},
... 'skills': {'any_of': ('dancing', )},
... })
>>> list(results)
[1]
| z3c.multifieldindex | /z3c.multifieldindex-3.4.0.tar.gz/z3c.multifieldindex-3.4.0/src/z3c/multifieldindex/README.txt | README.txt |
from BTrees.IFBTree import weightedIntersection
from zope.app.container.btree import BTreeContainer
from zope.app.container.interfaces import IObjectAddedEvent
from zope.component import adapter
from zope.interface import implements
from z3c.multifieldindex.interfaces import IMultiFieldIndex
from z3c.multifieldindex.interfaces import ISubIndexFactory
class MultiFieldIndexBase(BTreeContainer):
implements(IMultiFieldIndex)
def _fields(self):
"""To be overriden. Should return an iterable of (name, field) pairs."""
raise NotImplemented('_fields method should be provided by subclass.')
def _getData(self, object):
"""To be overriden. Should return a dictionary of data for given object.
Dictionary keys are the same as field/index names and values are actual
values to be indexed by according index.
"""
raise NotImplemented('_getData method should be provided by subclass.')
def recreateIndexes(self):
# 1. Remove all indexes
for name in list(self.keys()):
del self[name]
# 2. Create new indexes for fields that want to be indexed
for name, field in self._fields():
factory = ISubIndexFactory(field)
self[name] = factory()
def index_doc(self, docid, value):
data = self._getData(value)
for name in self:
value = data.get(name)
if value is not None:
self[name].index_doc(docid, value)
def unindex_doc(self, docid):
for index in self.values():
index.unindex_doc(docid)
def clear(self):
for index in self.values():
index.clear()
def apply(self, query):
results = []
for name, subquery in query.items():
if name not in self:
continue
r = self[name].apply(subquery)
if r is None:
continue
if not r:
return r
results.append((len(r), r))
if not results:
return None
results.sort()
_, result = results.pop(0)
for _, r in results:
_, result = weightedIntersection(result, r)
return result
@adapter(IMultiFieldIndex, IObjectAddedEvent)
def multiFieldIndexAdded(index, event):
index.recreateIndexes() | z3c.multifieldindex | /z3c.multifieldindex-3.4.0.tar.gz/z3c.multifieldindex-3.4.0/src/z3c/multifieldindex/index.py | index.py |
========
z3c.noop
========
z3c.noop provides traverser that simply skips a path element,
so /foo/++noop++qux/bar is equivalent to /foo/bar.
This is useful for example to generate varying URLs to work around browser
caches[#test-setup]_.
>>> dummy = object()
>>> root['foo'] = dummy
>>> traverse('/foo') == dummy
True
>>> traverse('/++noop++12345/foo') == dummy
True
.. [#test-setup]
>>> import zope.traversing.api
>>> import zope.publisher.browser
>>> root = getRootFolder()
>>> request = zope.publisher.browser.TestRequest()
>>> def traverse(path):
... return zope.traversing.api.traverse(root, path, request=request)
| z3c.noop | /z3c.noop-1.0.tar.gz/z3c.noop-1.0/src/z3c/noop/README.txt | README.txt |
from zope.interface import Interface
class IObjectPolicyMarker(Interface):
"""Marker interface to mark objects wanting their own security policy"""
class IObjectPolicy(Interface):
""" """
def getPrincipalPermission(self, manager, permissionid, principalid, default):
"""Return whether security policy allows permission
on the context object to the principal.
Arguments:
manager -- The default Z3 AnnotationPrincipalPermissionManager
which gets the permission from the annotations
permissionid -- A permission ID
principalid -- A principal ID (participation.principal.id)
default -- The default value proposed by AnnotationPrincipalPermissionManager
return:
one of zope.app.securitypolicy.interfaces.[Allow, Deny, Unset]
"""
def getRolePermission(self, manager, permissionid, roleid):
"""Return whether security policy allows permission
on the context object to the role.
Arguments:
manager -- The default Z3 AnnotationRolePermissionManager
which gets the permission from the annotations
permissionid -- A permission ID
roleid -- A role ID (determined by ZopeSecurityPolicy)
return:
one of zope.app.securitypolicy.interfaces.[Allow, Deny, Unset]
"""
def checkPermission(manager, permissionid):
"""Return whether security policy allows permission
on the context object.
manager -- The default Z3 ZopePolicy,
which can be used to get default permissions
permissionid -- A permission ID
The method should go through manager.participations.principal's
to check permissions, see checkPermissionForParticipation
return:
True -- access granted
False -- no access
"""
def checkPermissionForParticipation(manager, permissionid):
"""Go thrugh manager.participations.principal's
call self.checkPermissionForParticipant for each one
convinience method
return:
True -- access granted
False -- no access
"""
def checkPermissionForParticipant(self, manager, principal, permissionid):
"""Called by checkPermissionForParticipation for each principal
manager -- The default Z3 ZopePolicy,
which can be used to get default permissions
principal -- A principal
permissionid -- A permission ID
return:
True -- access granted
False -- no access
""" | z3c.objectpolicy | /z3c.objectpolicy-0.1.tar.gz/z3c.objectpolicy-0.1/src/z3c/objectpolicy/interfaces.py | interfaces.py |
The objectpolicy package makes it easy to override the default
zope.securitypolicy.zopepolicy on an object by object basis.
By default all objects use the zopepolicy. Objects that want to have
their own policy should have a marker interface `IObjectPolicyMarker`
and have an adapter to `IObjectPolicy`.
------
Levels
------
There are two levels supported.
- The low level is the SecurityMap.getCell level.
Here are the permissions stored by principal or role.
This works also with ZopePolicy as the security policy.
Uses Allow, Deny, Unset values.
Permissions descend (with ZopePolicy) to child objects or views.
See:
- IObjectPolicy.getPrincipalPermission
- IObjectPolicy.getRolePermission
- lowlevel.txt
Installation:
Drop the z3c.objectpolicy-configure.zcml in the instance/etc folder.
- The high level is the ISecurityPolicy.checkPermission level.
Here the permission is usually `summarized` for the principal by it's
roles, groups and object parent/child relations.
ZopePolicy has to be overridden by the ObjectsPolicy security policy.
Permissions do not decend to child objects or views.
Uses True -- access, False -- no access values.
See:
- IObjectPolicy.checkPermission
- highlevel.txt
Installation:
Override ZopePolicy in the instance/etc/securitypolicy.zcml
| z3c.objectpolicy | /z3c.objectpolicy-0.1.tar.gz/z3c.objectpolicy-0.1/src/z3c/objectpolicy/README.txt | README.txt |
import zope.interface
import zope.component
from zope.securitypolicy.zopepolicy import ZopeSecurityPolicy
from zope.security.checker import CheckerPublic
from zope.security.proxy import removeSecurityProxy
from zope.security.management import system_user
from z3c.objectpolicy.interfaces import IObjectPolicyMarker
from z3c.objectpolicy.interfaces import IObjectPolicy
from zope.securitypolicy.interfaces import Allow, Deny, Unset
from zope.securitypolicy.interfaces import IPrincipalPermissionManager
from zope.securitypolicy.principalpermission import AnnotationPrincipalPermissionManager
from zope.securitypolicy.interfaces import IRolePermissionManager
from zope.securitypolicy.rolepermission import AnnotationRolePermissionManager
class ObjectPolicy(ZopeSecurityPolicy):
def checkZopePermission(self, permission, object):
return ZopeSecurityPolicy.checkPermission(self, permission, object)
def checkPermission(self, permission, object):
if permission is CheckerPublic:
return True
object = removeSecurityProxy(object)
if IObjectPolicyMarker.providedBy(object):
try:
adapted = IObjectPolicy(object)
except TypeError:
return self.checkZopePermission(permission, object)
return adapted.checkPermission(self, permission)
else:
return self.checkZopePermission(permission, object)
class ObjectPrincipalPermissionManager(AnnotationPrincipalPermissionManager):
zope.component.adapts(IObjectPolicyMarker)
zope.interface.implements(IPrincipalPermissionManager)
def __init__(self, context):
super(ObjectPrincipalPermissionManager, self).__init__(context)
try:
self._adapted = IObjectPolicy(context)
except TypeError:
self.getSetting = self.getZopePrincipalSetting
def getPrincipalsForPermission(self, permission_id):
"""Get the principas that have a permission.
Return the list of (principal_id, setting) tuples that describe
security assertions for this permission.
If no principals have been set for this permission, then the empty
list is returned.
"""
raise NotImplementedError("Seemed like nobody calls getPrincipalsForPermission")
return super(ObjectPrincipalPermissionManager, self).getPrincipalsForPermission(
permission_id)
def getPermissionsForPrincipal(self, principal_id):
"""Get the permissions granted to a principal.
Return the list of (permission, setting) tuples that describe
security assertions for this principal.
If no permissions have been set for this principal, then the empty
list is returned.
"""
raise NotImplementedError("Seemed like nobody calls getPermissionsForPrincipal")
return super(ObjectPrincipalPermissionManager, self).getPermissionsForPrincipal(
principal_id)
def getZopePrincipalSetting(self, permission_id, principal_id, default=Unset):
return super(ObjectPrincipalPermissionManager, self).getSetting(
permission_id, principal_id, default)
def getSetting(self, permission_id, principal_id, default=Unset):
"""Get the setting for a permission and principal.
Get the setting (Allow/Deny/Unset) for a given permission and
principal.
"""
return self._adapted.getPrincipalPermission(
self, permission_id, principal_id, default)
def getPrincipalsAndPermissions(self):
"""Get all principal permission settings.
Get the principal security assertions here in the form
of a list of three tuple containing
(permission id, principal id, setting)
"""
raise NotImplementedError("Seemed like nobody calls getPrincipalsAndPermissions")
return super(ObjectPrincipalPermissionManager, self).getPrincipalsAndPermissions()
#def grantPermissionToPrincipal(self, permission_id, principal_id):
# """Assert that the permission is allowed for the principal.
# """
#
#def denyPermissionToPrincipal(self, permission_id, principal_id):
# """Assert that the permission is denied to the principal.
# """
#
#def unsetPermissionForPrincipal(self, permission_id, principal_id):
# """Remove the permission (either denied or allowed) from the
# principal.
# """
class ObjectRolePermissionManager(AnnotationRolePermissionManager):
zope.component.adapts(IObjectPolicyMarker)
zope.interface.implements(IRolePermissionManager)
def __init__(self, context):
super(ObjectRolePermissionManager, self).__init__(context)
try:
self._adapted = IObjectPolicy(context)
except TypeError:
self.getSetting = self.getZopeRoleSetting
def getPermissionsForRole(self, role_id):
"""Get the premissions granted to a role.
Return a sequence of (permission id, setting) tuples for the given
role.
If no permissions have been granted to this
role, then the empty list is returned.
"""
print "ROLE:getPermissionsForRole"
return super(ObjectRolePermissionManager, self).getPermissionsForRole(
role_id)
def getRolesForPermission(permission_id):
"""Get the roles that have a permission.
Return a sequence of (role id, setting) tuples for the given
permission.
If no roles have been granted this permission, then the empty list is
returned.
"""
print "ROLE:getRolesForPermission"
return super(ObjectRolePermissionManager, self).getRolesForPermission(
permission_id)
def getZopeRoleSetting(self, permission_id, role_id):
return super(ObjectRolePermissionManager, self).getSetting(
permission_id, role_id)
def getSetting(self, permission_id, role_id):
"""Return the setting for the given permission id and role id
If there is no setting, Unset is returned
"""
return self._adapted.getRolePermission(
self, permission_id, role_id)
def getRolesAndPermissions():
"""Return a sequence of (permission_id, role_id, setting) here.
The settings are returned as a sequence of permission, role,
setting tuples.
If no principal/role assertions have been made here, then the empty
list is returned.
"""
print "ROLE:getRolesAndPermissions"
return super(ObjectRolePermissionManager, self).getRolesAndPermissions()
#def grantPermissionToRole(permission_id, role_id):
# """Bind the permission to the role.
# """
#
#def denyPermissionToRole(permission_id, role_id):
# """Deny the permission to the role
# """
#
#def unsetPermissionFromRole(permission_id, role_id):
# """Clear the setting of the permission to the role.
# """
class DefaultObjectPolicyAdapter(object):
zope.interface.implements(IObjectPolicy)
def __init__(self, context):
self.context = context
def getPrincipalPermission(self, manager, permissionid, principalid, default):
#return the Z3 default permissions
return manager.getZopePrincipalSetting(
permissionid, principalid, default)
def getRolePermission(self, manager, permissionid, roleid):
#return the Z3 default permissions
return manager.getZopeRoleSetting(
permissionid, roleid)
def checkPermission(self, manager, permissionid):
#print permissionid, str(self.context)
return manager.checkZopePermission(permissionid, self.context)
def checkPermissionForParticipation(self, manager, permissionid):
object = self.context
seen = {}
for participation in manager.participations:
principal = participation.principal
if principal is system_user:
continue # always allow system_user
if principal.id in seen:
continue
if not self.checkPermissionForParticipant(
manager, principal, permissionid,
):
return False
seen[principal.id] = 1
return True
def checkPermissionForParticipant(self, manager, principal, permissionid):
return manager.cached_decision(
self.context, principal.id,
manager._groupsFor(principal), permissionid,
) | z3c.objectpolicy | /z3c.objectpolicy-0.1.tar.gz/z3c.objectpolicy-0.1/src/z3c/objectpolicy/objectpolicy.py | objectpolicy.py |
Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| z3c.objpath | /z3c.objpath-2.0-py3-none-any.whl/z3c.objpath-2.0.dist-info/LICENSE.rst | LICENSE.rst |
ObjectPath
**********
This package contains two things:
* the ``z3c.objpath.interfaces.IObjectPath`` interface.
* some helper functions to construct (relative) object paths, in
``z3c.objpath.path``.
The idea is that a particular application can implement a utility that
fulfills the ``IObjectPath`` interface, so that it is possible to
construct paths to objects in a uniform way. The implementation may be
done with ``zope.traversing``, but in some cases you want
application-specific object paths. In this case, the functions in
``z3c.objpath.path`` might be useful.
We'll have a simple item::
>>> class Item(object):
... __name__ = None
... __parent__ = None
... def __repr__(self):
... return '<Item %s>' % self.__name__
Let's create a simple container-like object::
>>> class Container(Item):
... def __init__(self):
... self._d = {}
... def __setitem__(self, name, obj):
... self._d[name] = obj
... obj.__name__ = name
... obj.__parent__ = self
... def __getitem__(self, name):
... return self._d[name]
... def __repr__(self):
... return '<Container %s>' % self.__name__
Now let's create a structure::
>>> root = Container()
>>> root.__name__ = 'root'
>>> data = root['data'] = Container()
>>> a = data['a'] = Container()
>>> b = data['b'] = Container()
>>> c = data['c'] = Item()
>>> d = a['d'] = Item()
>>> e = a['e'] = Container()
>>> f = e['f'] = Item()
>>> g = b['g'] = Item()
We will now exercise two functions, ``path`` and ``resolve``, which
are inverses of each other::
>>> from z3c.objpath import path, resolve
We can create a path to ``a`` from ``root``::
>>> path(root, a)
'/root/data/a'
We can also resolve it again::
>>> resolve(root, '/root/data/a')
<Container a>
We can also create a path to ``a`` from ``data``::
>>> path(data, a)
'/data/a'
And resolve it again::
>>> resolve(data, '/data/a')
<Container a>
We can make a deeper path::
>>> path(root, f)
'/root/data/a/e/f'
And resolve it::
>>> resolve(root, '/root/data/a/e/f')
<Item f>
The path `'/'` leads to the root object::
>>> resolve(root, '/')
<Container root>
We get an error if we cannot construct a path::
>>> path(e, a)
Traceback (most recent call last):
...
ValueError: Cannot create path for <Container a>
We also get an error if we cannot resolve a path::
>>> resolve(root, '/root/data/a/f/e')
Traceback (most recent call last):
...
ValueError: Cannot resolve path /root/data/a/f/e
| z3c.objpath | /z3c.objpath-2.0-py3-none-any.whl/z3c/objpath/README.rst | README.rst |
==================
Pack ZODBs Offline
==================
Pack a ZODB storage without running any part of the Zope application
server. Only an appropriate version of ZODB3 for the ZODB storage is
required. Apply only to copies of ZODB storages, not ZODB storages
currently in use.
Install the distribution::
$ python setup.py install
Then use the offlinepack script to pack a copy of your ZODB::
$ offlinepack /path/to/Data-copy.fs
Use the --help option for more details::
$ offlinepack --help
usage: offlinepack [options] PATH...
Pack ZODB storages without running Zope or ZEO
options:
-h, --help show this help message and exit
-d DAYS, --days=DAYS remove revisions more than DAYS old [default: 0]
-s DOTTED, --storage=DOTTED
use the storage constructor at DOTTED [default:
ZODB.FileStorage.FileStorage]
zc.buildout
-----------
A buildout.cfg is included that will install the offlinepack script
to the buildout. The buildout makes it possible to quickly use the
offlinepack script without modifying the system python installation::
$ git clone https://github.com/rpatterson/z3c.offlinepack.git
$ cd z3c.offlinepack
$ python bootstrap.py -v
$ bin/buildout -v
$ bin/offlinepack /path/to/Data-copy.fs
The buildout.cfg file can also be modified to use a specific version
of ZODB3. This is uesful if you need to use offlinepack without
migrating the ZODB to a newer version of ZODB3. Add the version
specifier to the offlinepack section of buildout.cfg. For example, to
use offlinepack with Zope 2.9, use the following offlinepack section::
[offlinepack]
recipe = zc.recipe.egg:scripts
eggs = z3c.offlinepack
ZODB3<3.7-dev
| z3c.offlinepack | /z3c.offlinepack-0.3.tar.gz/z3c.offlinepack-0.3/README.rst | README.rst |
import os, shutil, sys, tempfile, urllib, urllib2, subprocess
from optparse import OptionParser
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
quote = str
# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
stdout, stderr = subprocess.Popen(
[sys.executable, '-Sc',
'try:\n'
' import ConfigParser\n'
'except ImportError:\n'
' print 1\n'
'else:\n'
' print 0\n'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
has_broken_dash_S = bool(int(stdout.strip()))
# In order to be more robust in the face of system Pythons, we want to
# run without site-packages loaded. This is somewhat tricky, in
# particular because Python 2.6's distutils imports site, so starting
# with the -S flag is not sufficient. However, we'll start with that:
if not has_broken_dash_S and 'site' in sys.modules:
# We will restart with python -S.
args = sys.argv[:]
args[0:0] = [sys.executable, '-S']
args = map(quote, args)
os.execv(sys.executable, args)
# Now we are running with -S. We'll get the clean sys.path, import site
# because distutils will do it later, and then reset the path and clean
# out any namespace packages from site-packages that might have been
# loaded by .pth files.
clean_path = sys.path[:]
import site # imported because of its side effects
sys.path[:] = clean_path
for k, v in sys.modules.items():
if k in ('setuptools', 'pkg_resources') or (
hasattr(v, '__path__') and
len(v.__path__) == 1 and
not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))):
# This is a namespace package. Remove it.
sys.modules.pop(k)
is_jython = sys.platform.startswith('java')
setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
distribute_source = 'http://python-distribute.org/distribute_setup.py'
# parsing arguments
def normalize_to_url(option, opt_str, value, parser):
if value:
if '://' not in value: # It doesn't smell like a URL.
value = 'file://%s' % (
urllib.pathname2url(
os.path.abspath(os.path.expanduser(value))),)
if opt_str == '--download-base' and not value.endswith('/'):
# Download base needs a trailing slash to make the world happy.
value += '/'
else:
value = None
name = opt_str[2:].replace('-', '_')
setattr(parser.values, name, value)
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --setup-source and --download-base to point to
local resources, you can keep this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="use_distribute", default=False,
help="Use Distribute rather than Setuptools.")
parser.add_option("--setup-source", action="callback", dest="setup_source",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or file location for the setup file. "
"If you use Setuptools, this will default to " +
setuptools_source + "; if you use Distribute, this "
"will default to " + distribute_source + "."))
parser.add_option("--download-base", action="callback", dest="download_base",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or directory for downloading "
"zc.buildout and either Setuptools or Distribute. "
"Defaults to PyPI."))
parser.add_option("--eggs",
help=("Specify a directory for storing eggs. Defaults to "
"a temporary directory that is deleted when the "
"bootstrap script completes."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout's main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.eggs:
eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
else:
eggs_dir = tempfile.mkdtemp()
if options.setup_source is None:
if options.use_distribute:
options.setup_source = distribute_source
else:
options.setup_source = setuptools_source
if options.accept_buildout_test_releases:
args.append('buildout:accept-buildout-test-releases=true')
args.append('bootstrap')
try:
import pkg_resources
import setuptools # A flag. Sometimes pkg_resources is installed alone.
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez_code = urllib2.urlopen(
options.setup_source).read().replace('\r\n', '\n')
ez = {}
exec ez_code in ez
setup_args = dict(to_dir=eggs_dir, download_delay=0)
if options.download_base:
setup_args['download_base'] = options.download_base
if options.use_distribute:
setup_args['no_fake'] = True
ez['use_setuptools'](**setup_args)
if 'pkg_resources' in sys.modules:
reload(sys.modules['pkg_resources'])
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
cmd = [quote(sys.executable),
'-c',
quote('from setuptools.command.easy_install import main; main()'),
'-mqNxd',
quote(eggs_dir)]
if not has_broken_dash_S:
cmd.insert(1, '-S')
find_links = options.download_base
if not find_links:
find_links = os.environ.get('bootstrap-testing-find-links')
if find_links:
cmd.extend(['-f', quote(find_links)])
if options.use_distribute:
setup_requirement = 'distribute'
else:
setup_requirement = 'setuptools'
ws = pkg_resources.working_set
setup_requirement_path = ws.find(
pkg_resources.Requirement.parse(setup_requirement)).location
env = dict(
os.environ,
PYTHONPATH=setup_requirement_path)
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setup_requirement_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
if is_jython:
import subprocess
exitcode = subprocess.Popen(cmd, env=env).wait()
else: # Windows prefers this, apparently; otherwise we would prefer subprocess
exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
if exitcode != 0:
sys.stdout.flush()
sys.stderr.flush()
print ("An error occurred when trying to install zc.buildout. "
"Look above this message for any errors that "
"were output by easy_install.")
sys.exit(exitcode)
ws.add_entry(eggs_dir)
ws.require(requirement)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
if not options.eggs: # clean up temporary egg directory
shutil.rmtree(eggs_dir) | z3c.offlinepack | /z3c.offlinepack-0.3.tar.gz/z3c.offlinepack-0.3/bootstrap.py | bootstrap.py |
;-*- Doctest -*-
==================
Pack ZODBs Offline
==================
Pack a ZODB storage without running any part of the Zope application
server. Only an appropriate version of ZODB3 for the ZODB storage is
required. Apply only to copies of ZODB storages, not ZODB storages
currently in use.
Start with a FileStorage that has versions that would be removed on
pack.
>>> import ZODB, ZODB.FileStorage, transaction
>>> db = ZODB.DB(ZODB.FileStorage.FileStorage(data_fs))
>>> conn = db.open()
>>> conn.root()['foo'] = 'foo'
>>> transaction.commit()
>>> conn.root()['foo'] = 'bar'
>>> transaction.commit()
>>> conn.close()
>>> db.close()
The size after packing will be smaller than the size after packing.
>>> import os
>>> initial_size = os.path.getsize(data_fs)
>>> import z3c.offlinepack
>>> z3c.offlinepack.pack_paths([data_fs])
>>> os.path.getsize(data_fs) < initial_size
True
| z3c.offlinepack | /z3c.offlinepack-0.3.tar.gz/z3c.offlinepack-0.3/z3c/offlinepack/README.txt | README.txt |
from zope.schema.interfaces import IVocabularyTokenized
from zope.schema.vocabulary import SimpleTerm
from zope.interface import implements
from zope.security.management import getInteraction
from zope.i18n.negotiator import negotiator
from z3c.optionstorage.interfaces import IOptionStorageVocabulary
from z3c.optionstorage import queryOptionStorage
class OptionStorageVocabulary(object):
# Order matters here. We want our multi-view adapter to be chosen
# before the IVocabulary default one.
implements(IOptionStorageVocabulary, IVocabularyTokenized)
def __init__(self, context, name):
self.dict = queryOptionStorage(context, name)
if self.dict:
# Workaround. Hopefully, in the future titles will be
# computed as a view.
interaction = getInteraction()
request = interaction.participations[0]
self.language = negotiator.getLanguage(self.dict.getLanguages(),
request)
self.defaultlanguage = self.dict.getDefaultLanguage()
def __contains__(self, key):
if self.dict:
try:
self.dict.getValue(key, self.language)
return True
except KeyError:
try:
self.dict.getValue(key, self.defaultlanguage)
return True
except KeyError:
pass
return False
def getTerm(self, key):
if self.dict:
try:
value = self.dict.getValue(key, self.language)
return SimpleTerm(key, title=value)
except KeyError:
try:
value = self.dict.getValue(key, self.defaultlanguage)
return SimpleTerm(key, title=value)
except KeyError:
pass
raise LookupError
def getTermByToken(self, token):
return self.getTerm(token)
def __iter__(self):
if self.dict:
for key in self.dict.getKeys():
try:
yield self.getTerm(key)
except LookupError:
pass
def __len__(self):
count = 0
if self.dict:
marker = object()
for key in self.dict.getKeys():
if (self.dict.queryValue(key, self.language,
marker) is not marker
or self.dict.queryValue(key, self.defaultlanguage,
marker) is not marker):
count += 1
return count
def getDefaultKey(self):
if self.dict:
return self.dict.getDefaultKey() | z3c.optionstorage | /z3c.optionstorage-1.0.7.tar.gz/z3c.optionstorage-1.0.7/src/z3c/optionstorage/vocabulary.py | vocabulary.py |
from zope.annotation.interfaces import IAnnotatable, IAnnotations
from zope.proxy import removeAllProxies
from zope.interface import implements
from zope.traversing.api import getParents
from persistent.dict import PersistentDict
from persistent import Persistent
from interfaces import IOptionStorage, IOptionDict
from UserDict import IterableUserDict
# This key should in theory be z3c.optionstorage, anyone wanting to change it
# can write the generation script.
OptionStorageKey = "optionstorage"
class Table(object):
# Based on zope's SecurityMap.
def __init__(self):
self._byrow = {}
self._bycol = {}
def __nonzero__(self):
return bool(self._byrow)
def _changed(self):
pass
def clear(self):
self._byrow.clear()
self._bycol.clear()
self._changed()
def addCell(self, rowkey, colkey, value):
row = self._byrow.get(rowkey)
if row:
if row.get(colkey) is value:
return False
else:
row = self._byrow[rowkey] = {}
col = self._bycol.get(colkey)
if not col:
col = self._bycol[colkey] = {}
row[colkey] = value
col[rowkey] = value
self._changed()
return True
def delCell(self, rowkey, colkey):
row = self._byrow.get(rowkey)
if row and (colkey in row):
del row[colkey]
if not row:
del self._byrow[rowkey]
col = self._bycol[colkey]
del col[rowkey]
if not col:
del self._bycol[colkey]
return True
self._changed()
return False
def queryCell(self, rowkey, colkey, default=None):
row = self._byrow.get(rowkey)
if row:
return row.get(colkey, default)
else:
return default
def getCell(self, rowkey, colkey):
marker = object()
cell = self.queryCell(rowkey, colkey, marker)
if cell is marker:
raise KeyError("Invalid row/column pair")
return cell
def getRow(self, rowkey):
row = self._byrow.get(rowkey)
if row:
return row.items()
else:
return []
def getCol(self, colkey):
col = self._bycol.get(colkey)
if col:
return col.items()
else:
return []
def getRowKeys(self):
return self._byrow.keys()
def getColKeys(self):
return self._bycol.keys()
def getAllCells(self):
res = []
for r in self._byrow.keys():
for c in self._byrow[r].items():
res.append((r,) + c)
return res
class PersistentTable(Table, Persistent):
def _changed(self):
self._p_changed = 1
class OptionDict(Persistent):
"""An option dict.
Test that OptionDict does actually provide it's interfaces:
>>> o = OptionDict()
>>> from zope.interface.verify import verifyObject
>>> verifyObject(IOptionDict, o)
True
"""
implements(IOptionDict)
def __init__(self):
self._defaultkey = None
self._defaultlanguage = None
self._table = PersistentTable()
def getLanguages(self):
return self._table.getColKeys()
def getDefaultLanguage(self):
return self._defaultlanguage
def setDefaultLanguage(self, language):
self._defaultlanguage = language
def getDefaultKey(self):
return self._defaultkey
def setDefaultKey(self, key):
self._defaultkey = key
def getKeys(self):
return self._table.getRowKeys()
def queryValue(self, key, language, default=None):
return self._table.queryCell(key, language, default)
def getValue(self, key, language):
return self._table.getCell(key, language)
def addValue(self, key, language, value):
self._table.addCell(key, language, value)
def delValue(self, key, language):
self._table.delCell(key, language)
def delAllValues(self):
self._table.clear()
self._defaultkey = None
class OptionStorage(IterableUserDict, object):
implements(IOptionStorage)
def __init__(self, context):
annotations = IAnnotations(removeAllProxies(context))
if OptionStorageKey in annotations:
self.data = annotations[OptionStorageKey]
else:
self.data = annotations[OptionStorageKey] = PersistentDict()
def queryOptionStorage(context, name):
lookuplist = getParents(context)
lookuplist.insert(0, context)
for object in lookuplist:
object = removeAllProxies(object)
if IAnnotatable.providedBy(object):
annotations = IAnnotations(object)
if OptionStorageKey in annotations:
storage = IOptionStorage(object)
if name in storage:
return storage[name]
return None
class OptionStorageProperty(object):
def __init__(self, name, dictname, islist=False, readonly=False):
self._name = name
self._dictname = dictname
self._islist = islist
self._readonly = readonly
def __get__(self, object, type_=None):
dict = queryOptionStorage(object, self._dictname)
if dict:
default = dict.getDefaultKey()
return getattr(object, self._name, default)
def __set__(self, object, value):
if self._readonly:
raise AttributeError("Attribute '%s' is read-only" % self._name)
if type(value) is not list:
values = [value]
else:
values = value
dict = queryOptionStorage(object, self._dictname)
if dict:
keys = dict.getKeys()
invalid = [x for x in values if x not in keys]
if invalid:
raise ValueError("Invalid values: %s" % ", ".join(
map(repr, invalid)))
if self._islist:
value = values
setattr(object, self._name, value) | z3c.optionstorage | /z3c.optionstorage-1.0.7.tar.gz/z3c.optionstorage-1.0.7/src/z3c/optionstorage/__init__.py | __init__.py |
from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile
from z3c.optionstorage.interfaces import IOptionStorage
from z3c.optionstorage import OptionDict
def checkFields(request, *fields):
for field in fields:
if field not in request:
return False
return True
class StorageNameNotFoundError(LookupError):
pass
class OptionStorageView(object):
storagetemplate = ViewPageTemplateFile("optionstorage.pt")
dicttemplate = ViewPageTemplateFile("optiondict.pt")
dictlist = [] # (name, topic)
def __init__(self, context, request):
self.context = context
self.request = request
self.name = None
self.topic = None
self.dict = None
def getNameTopicList(self):
storage = IOptionStorage(self.context)
for name, topic in self.dictlist:
yield {"name": name, "topic": topic}
def __call__(self, name=None):
if name is None:
return self.storagetemplate()
storage = IOptionStorage(self.context)
for _name, topic in self.dictlist:
if name == _name:
if name not in storage:
storage[name] = OptionDict()
self.dict = storage[name]
self.name = name
self.topic = topic
break
else:
raise StorageNameNotFoundError
form = self.request.form
if "SAVE" not in form:
return self.dicttemplate()
language = {}
key = {}
value = {}
for entry in form:
entryvalue = form[entry].strip()
if not entryvalue:
pass
elif entry.startswith("lang-"):
language[int(entry[5:])] = entryvalue
elif entry.startswith("key-"):
key[int(entry[4:])] = entryvalue
elif entry.startswith("value-"):
tok = entry.split("-")
value[int(tok[1]), int(tok[2])] = entryvalue
try:
defaultkey = int(form["default-key"])
except KeyError:
defaultkey = None
try:
defaultlanguage = int(form["default-lang"])
except KeyError:
defaultlanguage = None
self.dict.delAllValues()
for keynum, languagenum in value:
if keynum in key and languagenum in language:
self.dict.addValue(key[keynum], language[languagenum],
value[keynum, languagenum])
if defaultkey in key:
self.dict.setDefaultKey(key[defaultkey])
if defaultlanguage in language:
self.dict.setDefaultLanguage(language[defaultlanguage])
return self.dicttemplate() | z3c.optionstorage | /z3c.optionstorage-1.0.7.tar.gz/z3c.optionstorage-1.0.7/src/z3c/optionstorage/browser/__init__.py | __init__.py |
========
Pagelets
========
.. contents::
This package provides a very flexible base implementation that can be used
to write view components which can be higly customized later in custom projects.
This is needed if you have to write reusable components like those needed
in a framework. Pagelets are BrowserPages made differently and can be used
to replace them.
What does this mean?
We separate the python view code from the template implementation. And we also
separate the template in at least two different templates - the content
template and the layout template.
This package uses z3c.template and offers an implementaton for this
template pattern. Additionaly this package offers a ``pagelet`` directive
wich can be used to register pagelets.
Pagelets are views which can be called and support the update and render
pattern.
How do they work
----------------
A pagelet returns the rendered content without layout in the render method and
returns the layout code if we call it. See also z3c.template which shows
how the template works. These samples will only show how the base implementation
located in the z3c.pagelet.browser module get used.
BrowserPagelet
--------------
The base implementation called BrowserPagelet offers builtin __call__ and
render methods which provide the different template lookups. Take a look at the
BrowserPagelet class located in z3c.pagelet.browser and you can see that the render
method returns a IContentTemplate and the __call__ method a ILayoutTemplate
defined in the z3c.layout package.
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
>>> import zope.interface
>>> import zope.component
>>> from z3c.pagelet import interfaces
>>> from z3c.pagelet import browser
We start by defining a page template rendering the pagelet content.
>>> contentTemplate = os.path.join(temp_dir, 'contentTemplate.pt')
>>> with open(contentTemplate, 'w') as file:
... _ = file.write('''
... <div class="content">
... my template content
... </div>
... ''')
And we also define a layout template rendering the layout for a pagelet.
This template will call the render method from a pagelet:
>>> layoutTemplate = os.path.join(temp_dir, 'layoutTemplate.pt')
>>> with open(layoutTemplate, 'w') as file:
... _ = file.write('''
... <html>
... <body>
... <div class="layout" tal:content="structure view/render">
... here comes the content
... </div>
... </body>
... </html>
... ''')
Let's now register the template for the view and the request. We use the
TemplateFactory directly from the z3c.template package. This is commonly done
using the ZCML directive called ``z3c:template``. Note that we do use the
generic Interface as the view base interface to register the template. This
allows us to register a more specific template in the next sample:
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from z3c.template.interfaces import IContentTemplate
>>> from z3c.template.template import TemplateFactory
>>> factory = TemplateFactory(contentTemplate, 'text/html')
>>> zope.component.provideAdapter(
... factory, (zope.interface.Interface, IDefaultBrowserLayer),
... IContentTemplate)
And register the layout template using the ``Interface`` as registration base:
>>> from z3c.template.interfaces import ILayoutTemplate
>>> factory = TemplateFactory(layoutTemplate, 'text/html')
>>> zope.component.provideAdapter(factory,
... (zope.interface.Interface, IDefaultBrowserLayer), ILayoutTemplate)
Now define a view marker interface. Such a marker interface is used to let
us register our templates:
>>> class IMyView(zope.interface.Interface):
... pass
And we define a view class inherited from BrowserPagelet and implementing the
view marker interface:
>>> @zope.interface.implementer(IMyView)
... class MyView(browser.BrowserPagelet):
... pass
Now test the view class providing the view and check the output:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> myView = MyView(root, request)
>>> print(myView())
<html>
<body>
<div class="layout">
<div class="content">
my template content
</div>
</div>
</body>
</html>
You can see the render method generates only the content:
>>> print(myView.render())
<div class="content">
my template content
</div>
Redirection
-----------
The pagelet doesn't bother rendering itself and its layout when request is a
redirection as the rendering doesn't make any sense with browser requests in
that case. Let's create a view that does a redirection in its update method.
>>> class RedirectingView(MyView):
... def update(self):
... self.request.response.redirect('.')
It will return an empty string when called as a browser page.
>>> redirectRequest = TestRequest()
>>> redirectView = RedirectingView(root, redirectRequest)
>>> redirectView() == ''
True
However, the ``render`` method will render pagelet's template as usual:
>>> print(redirectView.render())
<div class="content">
my template content
</div>
PageletRenderer
---------------
There is also a standard pattern for calling the render method on pagelet.
Using the pagelet renderer which is a IContentProvider makes it possible to
reuse existing layout template without the pagelet. If you want to reuse a
layout template without a pagelet you simply have to provide another content
provider. It's flexible isn't it? As next let's show a sample using the
pagelet renderer.
We define a new layout template using the content provider called ```pagelet``
>>> providerLayout = os.path.join(temp_dir, 'providerLayout.pt')
>>> with open(providerLayout, 'w') as file:
... _ = file.write('''
... <html>
... <body>
... <div class="layout" tal:content="structure provider:pagelet">
... here comes the content
... </div>
... </body>
... </html>
... ''')
and register them. Now we use the specific interface defined in the view:
>>> factory = TemplateFactory(providerLayout, 'text/html')
>>> zope.component.provideAdapter(factory,
... (zope.interface.Interface, IDefaultBrowserLayer), ILayoutTemplate)
Now let's call the view:
>>> try:
... myView()
... except Exception as e:
... print(repr(e))
ContentProviderLookupError('pagelet'...)
That's right, we need to register the content provider ``pagelet`` before we
can use it.
>>> from zope.contentprovider.interfaces import IContentProvider
>>> from z3c.pagelet import provider
>>> zope.component.provideAdapter(provider.PageletRenderer,
... provides=IContentProvider, name='pagelet')
Now let's call the view again:
>>> print(myView())
<html>
<body>
<div class="layout">
<div class="content">
my template content
</div>
</div>
</body>
</html>
Context-specific templates
--------------------------
Pagelets are also able to lookup templates using their context object
as an additional discriminator, via (self, self.request, self.context)
lookup. It's useful when you want to provide a custom template for
some specific content objects. Let's check that out.
First, let's define a custom content type and make an object to work with:
>>> class IContent(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(IContent)
... class Content(object):
... pass
>>> content = Content()
Let's use our view class we defined earlier. Currently, it will use
the layout and content templates we defined for (view, request) before:
>>> myView = MyView(content, request)
>>> print(myView())
<html>
<body>
<div class="layout">
<div class="content">
my template content
</div>
</div>
</body>
</html>
Let's create context-specific layout and content templates and register
them for our IContent interface:
>>> contextLayoutTemplate = os.path.join(temp_dir, 'contextLayoutTemplate.pt')
>>> with open(contextLayoutTemplate, 'w') as file:
... _ = file.write('''
... <html>
... <body>
... <div class="context-layout" tal:content="structure provider:pagelet">
... here comes the context-specific content
... </div>
... </body>
... </html>
... ''')
>>> factory = TemplateFactory(contextLayoutTemplate, 'text/html')
>>> zope.component.provideAdapter(
... factory, (zope.interface.Interface, IDefaultBrowserLayer, IContent),
... ILayoutTemplate)
>>> contextContentTemplate = os.path.join(temp_dir, 'contextContentTemplate.pt')
>>> with open(contextContentTemplate, 'w') as file:
... _ = file.write('''
... <div class="context-content">
... my context-specific template content
... </div>
... ''')
>>> factory = TemplateFactory(contextContentTemplate, 'text/html')
>>> zope.component.provideAdapter(
... factory, (zope.interface.Interface, IDefaultBrowserLayer, IContent),
... IContentTemplate)
Now, our view should use context-specific templates for rendering:
>>> print(myView())
<html>
<body>
<div class="context-layout">
<div class="context-content">
my context-specific template content
</div>
</div>
</body>
</html>
Add, Edit and Display forms (formlib)
-------------------------------------
What would the pagelet be without any formlib based implementations?
We offer base implementations for add, edit and display forms based on
the formlib. **Note:** To make sure these classes get defined, you
should have ``zope.formlib`` already installed, as ``z3c.pagelet``
does not directly depend on ``zope.formlib`` because there are other
form libraries.
For the next tests we provide a generic form template
like those used in formlib. This template is registered within this package
as a default for the formlib based mixin classes:
>>> from z3c import pagelet
>>> baseDir = os.path.split(pagelet.__file__)[0]
>>> formTemplate = os.path.join(baseDir, 'form.pt')
>>> factory = TemplateFactory(formTemplate, 'text/html')
>>> zope.component.provideAdapter(
... factory,
... (interfaces.IPageletForm, IDefaultBrowserLayer), IContentTemplate)
And we define a new interface including a text attribute:
>>> import zope.schema
>>> class IDocument(zope.interface.Interface):
... """A document."""
... text = zope.schema.TextLine(title=u'Text', description=u'Text attr.')
Also define a content object which implements the interface:
>>> @zope.interface.implementer(IDocument)
... class Document(object):
... text = None
>>> document = Document()
PageletAddForm
~~~~~~~~~~~~~~
Now let's define an add from based on the PageletAddForm class:
>>> from zope.formlib import form
>>> class MyAddForm(browser.PageletAddForm):
... form_fields = form.Fields(IDocument)
... def createAndAdd(self, data):
... title = data.get('title', u'')
... doc = Document()
... doc.title = title
... root['document'] = doc
... return doc
Now render the form:
>>> addForm = MyAddForm(root, request)
>>> print(addForm())
<html>
<body>
<div class="layout">
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="zc.page.browser_form">
<table class="form-fields">
<tr>
<td class="label">
<label for="form.text">
<span class="required">*</span><span>Text</span>
</label>
</td>
<td class="field">
<div class="form-fields-help"
id="field-help-for-form.text">Text attr.</div>
<div class="widget"><input class="textType" id="form.text"
name="form.text" size="20" type="text" value="" /></div>
</td>
</tr>
</table>
<div class="form-controls">
<input type="submit" id="form.actions.add" name="form.actions.add"
value="Add" class="button" />
</div>
</form>
</div>
</body>
</html>
PageletEditForm
~~~~~~~~~~~~~~~
Now let's define an edit form based on the PageletEditForm class:
>>> class MyEditForm(browser.PageletEditForm):
... form_fields = form.Fields(IDocument)
and render the form:
>>> document.text = u'foo'
>>> editForm = MyEditForm(document, request)
>>> print(editForm())
<html>
<body>
<div class="layout">
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="zc.page.browser_form">
<table class="form-fields">
<tr>
<td class="label">
<label for="form.text">
<span class="required">*</span><span>Text</span>
</label>
</td>
<td class="field">
<div class="form-fields-help"
id="field-help-for-form.text">Text attr.</div>
<div class="widget"><input class="textType" id="form.text"
name="form.text" size="20" type="text" value="foo"
/></div>
</td>
</tr>
</table>
<div class="form-controls">
<input type="submit" id="form.actions.apply"
name="form.actions.apply" value="Apply" class="button" />
</div>
</form>
</div>
</body>
</html>
PageletDisplayForm
~~~~~~~~~~~~~~~~~~
Now let's define a display form based on the PageletDisplayForm class...
>>> class MyDisplayForm(browser.PageletDisplayForm):
... form_fields = form.Fields(IDocument)
and render the form:
>>> document.text = u'foo'
>>> displayForm = MyDisplayForm(document, request)
>>> print(displayForm())
<html>
<body>
<div class="layout">
<form action="http://127.0.0.1" method="post"
enctype="multipart/form-data" class="edit-form"
id="zc.page.browser_form">
<table class="form-fields">
<tr>
<td class="label">
<label for="form.text">
<span>Text</span>
</label>
</td>
<td class="field">
<div class="form-fields-help"
id="field-help-for-form.text">Text attr.</div>
<div class="widget">foo</div>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
Cleanup
-------
>>> import shutil
>>> shutil.rmtree(temp_dir)
| z3c.pagelet | /z3c.pagelet-3.0-py3-none-any.whl/z3c/pagelet/README.rst | README.rst |
=================
Pagelet directive
=================
Show how we can use the pagelet directive. Register the meta configuration for
the directive.
>>> import sys
>>> from zope.configuration import xmlconfig
>>> import z3c.pagelet
>>> context = xmlconfig.file('meta.zcml', z3c.pagelet)
We need also a custom pagelet class:
>>> from z3c.pagelet.browser import BrowserPagelet
>>> class MyPagelet(BrowserPagelet):
... """Custom pagelet"""
Make them available under the fake package ``custom``:
>>> sys.modules['custom'] = type(
... 'Module', (),
... {'MyPagelet': MyPagelet})()
To register a pagelet we need a class:
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:pagelet
... name="index.html"
... permission="zope.Public"
... />
... </configure>
... """, context)
Traceback (most recent call last):
...
ConfigurationError: Missing parameter: 'class'
File "<string>", line 4.2-7.8
And we also need an interface implementing zope.interface.intefaces.IInterface:
>>> class NonInterface(object):
... """Non compliant interface."""
>>> sys.modules['custom'].NonInterface = NonInterface
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:pagelet
... name="index.html"
... class="custom.MyPagelet"
... permission="zope.Public"
... provides="custom.NonInterface"
... />
... </configure>
... """, context)
Traceback (most recent call last):
...
ConfigurationError: Invalid value for 'provides'
File "<string>", line 4.2-9.8
zope.schema._bootstrapinterfaces.NotAnInterface:
Register a pagelet within the directive with minimal attributes:
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:pagelet
... name="index.html"
... class="custom.MyPagelet"
... permission="zope.Public"
... />
... </configure>
... """, context)
Let's get the pagelet
>>> import zope.component
>>> from zope.publisher.browser import TestRequest
>>> pagelet = zope.component.queryMultiAdapter((object(), TestRequest()),
... name='index.html')
and check them:
>>> pagelet
<z3c.pagelet.zcml.MyPagelet object at ...>
>>> pagelet.context
<object object at ...>
Register the pagelet with a different name and more attributes provided from
the directive. We also use a custom attribute called label here. Let's define
some more components...
>>> class SecondPagelet(BrowserPagelet):
... label = ''
>>> import zope.interface
>>> class IContent(zope.interface.Interface):
... """Content interface."""
>>> @zope.interface.implementer(IContent)
... class Content(object):
... pass
register the new classes in the custom module...
>>> sys.modules['custom'].IContent = IContent
>>> sys.modules['custom'].Content = Content
>>> sys.modules['custom'].SecondPagelet = SecondPagelet
and use them in the directive:
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:pagelet
... name="custom.html"
... class="custom.SecondPagelet"
... for="custom.IContent"
... permission="zope.Public"
... label="my Label"
... />
... </configure>
... """, context)
Get the pagelet for the new content object
>>> import zope.component
>>> pagelet = zope.component.queryMultiAdapter((Content(), TestRequest()),
... name='custom.html')
and check them:
>>> pagelet
<z3c.pagelet.zcml.SecondPagelet object at ...>
>>> pagelet.label
'my Label'
We also can provide another interface then the IPagelet within the directive.
Such a interface must be inherited from IPagelet.
>>> class NewPagelet(BrowserPagelet):
... """New pagelet"""
>>> sys.modules['custom'] = type(
... 'Module', (),
... {'NewPagelet': NewPagelet})()
Now register the pagelet within a interface which isn't inherited from IPagelet.
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:pagelet
... name="new.html"
... class="custom.NewPagelet"
... permission="zope.Public"
... provides="zope.interface.Interface"
... />
... </configure>
... """, context)
Traceback (most recent call last):
...
ConfigurationError: Provides interface must inherit IPagelet.
File "<string>", line 4.2-9.8
If we use a correct interface, we can register the pagelet:
>>> from z3c.pagelet import interfaces
>>> class INewPagelet(interfaces.IPagelet):
... """New pagelet interface."""
>>> sys.modules['custom'] = type(
... 'Module', (),
... {'INewPagelet': INewPagelet, 'NewPagelet': NewPagelet})()
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:pagelet
... name="new.html"
... class="custom.NewPagelet"
... permission="zope.Public"
... provides="custom.INewPagelet"
... />
... </configure>
... """, context)
And if we get the pagelet, we can see that the object provides the new
pagelet interface:
>>> pagelet = zope.component.queryMultiAdapter((object(), TestRequest()),
... name='new.html')
>>> pagelet
<z3c.pagelet.zcml.NewPagelet object at ...>
>>> INewPagelet.providedBy(pagelet)
True
Register a pagelet for a layer:
>>> class SkinnedPagelet(BrowserPagelet):
... """Custom pagelet"""
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> class IMyPageletLayer(IDefaultBrowserLayer):
... """Custom layer"""
>>> sys.modules['custom'] = type(
... 'Module', (),
... {'SkinnedPagelet': SkinnedPagelet,
... 'IMyPageletLayer': IMyPageletLayer})()
>>> context = xmlconfig.string("""
... <configure
... xmlns:z3c="http://namespaces.zope.org/z3c">
... <z3c:pagelet
... name="skinned.html"
... layer="custom.IMyPageletLayer"
... class="custom.SkinnedPagelet"
... permission="zope.Public"
... />
... </configure>
... """, context)
>>> from zope.publisher.skinnable import applySkin
>>> req = TestRequest()
>>> applySkin(req, IMyPageletLayer)
>>> pagelet = zope.component.queryMultiAdapter((object(), req),
... name='skinned.html')
and check them:
>>> pagelet
<z3c.pagelet.zcml.SkinnedPagelet object at ...>
>>> pagelet.context
<object object at ...>
Cleanup
--------
Now we need to clean up the custom module.
>>> del sys.modules['custom']
| z3c.pagelet | /z3c.pagelet-3.0-py3-none-any.whl/z3c/pagelet/zcml.rst | zcml.rst |
"""Custom Output Checker
"""
import doctest as pythondoctest
import re
import lxml.doctestcompare
import lxml.etree
from lxml.doctestcompare import LHTMLOutputChecker
from zope.testing.renormalizing import RENormalizing
class OutputChecker(LHTMLOutputChecker, RENormalizing):
"""Doctest output checker which is better equippied to identify
HTML markup than the checker from the ``lxml.doctestcompare``
module. It also uses the text comparison function from the
built-in ``doctest`` module to allow the use of ellipsis.
Also, we need to support RENormalizing.
"""
_repr_re = re.compile(
r'^<([A-Z]|[^>]+ (at|object) |[a-z]+ \'[A-Za-z0-9_.]+\'>)')
def __init__(self, doctest=pythondoctest, patterns=()):
RENormalizing.__init__(self, patterns)
self.doctest = doctest
# make sure these optionflags are registered
doctest.register_optionflag('PARSE_HTML')
doctest.register_optionflag('PARSE_XML')
doctest.register_optionflag('NOPARSE_MARKUP')
def _looks_like_markup(self, s):
s = s.replace('<BLANKLINE>', '\n').strip()
return (s.startswith('<')
and not self._repr_re.search(s))
def text_compare(self, want, got, strip):
if want is None:
want = ""
if got is None:
got = ""
checker = self.doctest.OutputChecker()
return checker.check_output(
want, got,
self.doctest.ELLIPSIS | self.doctest.NORMALIZE_WHITESPACE)
def check_output(self, want, got, optionflags):
if got == want:
return True
for transformer in self.transformers:
want = transformer(want)
got = transformer(got)
return LHTMLOutputChecker.check_output(self, want, got, optionflags)
def output_difference(self, example, got, optionflags):
want = example.want
if not want.strip():
return LHTMLOutputChecker.output_difference(
self, example, got, optionflags)
# Dang, this isn't as easy to override as we might wish
original = want
for transformer in self.transformers:
want = transformer(want)
got = transformer(got)
# temporarily hack example with normalized want:
example.want = want
result = LHTMLOutputChecker.output_difference(
self, example, got, optionflags)
example.want = original
return result
def get_parser(self, want, got, optionflags):
NOPARSE_MARKUP = self.doctest.OPTIONFLAGS_BY_NAME.get(
"NOPARSE_MARKUP", 0)
PARSE_HTML = self.doctest.OPTIONFLAGS_BY_NAME.get(
"PARSE_HTML", 0)
PARSE_XML = self.doctest.OPTIONFLAGS_BY_NAME.get(
"PARSE_XML", 0)
parser = None
if NOPARSE_MARKUP & optionflags:
return None
if PARSE_HTML & optionflags:
parser = lxml.doctestcompare.html_fromstring
elif PARSE_XML & optionflags:
parser = lxml.etree.XML
elif (want.strip().lower().startswith('<html')
and got.strip().startswith('<html')):
parser = lxml.doctestcompare.html_fromstring
elif (self._looks_like_markup(want)
and self._looks_like_markup(got)):
parser = self.get_default_parser()
return parser | z3c.pagelet | /z3c.pagelet-3.0-py3-none-any.whl/z3c/pagelet/outputchecker.py | outputchecker.py |
"""ZCML Directives
"""
import zope.component
import zope.component.zcml
import zope.configuration.fields
import zope.interface
import zope.schema
import zope.security.checker
import zope.security.zcml
from zope.browserpage import metaconfigure as viewmeta
from zope.configuration.exceptions import ConfigurationError
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from z3c.pagelet import browser
from z3c.pagelet import interfaces
class IPageletDirective(zope.component.zcml.IBasicViewInformation):
"""A directive to register a new pagelet.
The pagelet directive also supports an undefined set of keyword arguments
that are set as attributes on the pagelet after creation.
"""
name = zope.schema.TextLine(
title="The name of the pagelet.",
description="The name shows up in URLs/paths. For example 'foo'.",
required=True)
class_ = zope.configuration.fields.GlobalObject(
title="Class",
description="A class that provides attributes used by the pagelet.",
required=True,
)
permission = zope.security.zcml.Permission(
title="Permission",
description="The permission needed to use the pagelet.",
required=True
)
layer = zope.configuration.fields.GlobalObject(
title="The request interface or class this pagelet is for.",
description=(
"Defaults to"
" zope.publisher.interfaces.browser.IDefaultBrowserLayer."),
required=False
)
for_ = zope.configuration.fields.GlobalObject(
title="Context",
description="The content interface or class this pagelet is for.",
required=False
)
provides = zope.configuration.fields.GlobalInterface(
title="The interface this pagelets provides.",
description="""
A pagelet can provide an interface. This would be used for
views that support other views.""",
required=False,
default=interfaces.IPagelet,
)
# Arbitrary keys and values are allowed to be passed to the pagelet.
IPageletDirective.setTaggedValue('keyword_arguments', True)
# pagelet directive
def pageletDirective(
_context, class_, name, permission, for_=zope.interface.Interface,
layer=IDefaultBrowserLayer, provides=interfaces.IPagelet,
allowed_interface=None, allowed_attributes=None, **kwargs):
# Security map dictionary
required = {}
# Get the permission; mainly to correctly handle CheckerPublic.
permission = viewmeta._handle_permission(_context, permission)
ifaces = list(zope.interface.Declaration(provides).flattened())
if interfaces.IPagelet not in ifaces:
raise ConfigurationError("Provides interface must inherit IPagelet.")
# Build a new class that we can use different permission settings if we
# use the class more then once.
cdict = {}
cdict['__name__'] = name
cdict.update(kwargs)
new_class = type(class_.__name__, (class_, browser.BrowserPagelet), cdict)
# Set up permission mapping for various accessible attributes
viewmeta._handle_allowed_interface(
_context, allowed_interface, permission, required)
viewmeta._handle_allowed_attributes(
_context, allowed_attributes, permission, required)
viewmeta._handle_allowed_attributes(
_context, kwargs.keys(), permission, required)
viewmeta._handle_allowed_attributes(
_context, ('__call__', 'browserDefault', 'update', 'render',
'publishTraverse'), permission, required)
# Register the interfaces.
viewmeta._handle_for(_context, for_)
# provide the custom provides interface if not allready provided
if not provides.implementedBy(new_class):
zope.interface.classImplements(new_class, provides)
# Create the security checker for the new class
zope.security.checker.defineChecker(
new_class,
zope.security.checker.Checker(required))
# register pagelet
_context.action(
discriminator=('pagelet', for_, layer, name),
callable=zope.component.zcml.handler,
args=('registerAdapter',
new_class, (for_, layer), provides, name, _context.info),) | z3c.pagelet | /z3c.pagelet-3.0-py3-none-any.whl/z3c/pagelet/zcml.py | zcml.py |
"""Pagelet mixin classes
"""
import zope.component
import zope.interface
from z3c.template.interfaces import IContentTemplate
from z3c.template.interfaces import ILayoutTemplate
from zope.publisher import browser
from z3c.pagelet import interfaces
REDIRECT_STATUS_CODES = (301, 302, 303)
# default pagelet base implementation
@zope.interface.implementer(interfaces.IPagelet)
class BrowserPagelet(browser.BrowserPage):
"""Content generating pagelet with layout template support."""
template = None
layout = None
def update(self):
pass
def render(self):
# render content template
if self.template is None:
template = zope.component.queryMultiAdapter(
(self, self.request, self.context), IContentTemplate)
if template is None:
template = zope.component.getMultiAdapter(
(self, self.request), IContentTemplate)
return template(self)
return self.template()
def __call__(self):
"""Call update and returns the layout template which calls render."""
self.update()
if self.request.response.getStatus() in REDIRECT_STATUS_CODES:
# don't bother rendering when redirecting
return ''
if self.layout is None:
layout = zope.component.queryMultiAdapter(
(self, self.request, self.context), ILayoutTemplate)
if layout is None:
layout = zope.component.getMultiAdapter(
(self, self.request), ILayoutTemplate)
return layout(self)
return self.layout()
try:
from zope.formlib import form
except ImportError:
pass
else:
# formlib based pagelet mixin classes
@zope.interface.implementer(interfaces.IPageletForm)
class PageletForm(form.FormBase, BrowserPagelet):
"""Form mixin for pagelet implementations."""
template = None
layout = None
__init__ = BrowserPagelet.__init__
__call__ = BrowserPagelet.__call__
def render(self):
# if the form has been updated, it will already have a result
if self.form_result is None:
if self.form_reset:
# we reset, in case data has changed in a way that
# causes the widgets to have different data
self.resetForm()
self.form_reset = False
if self.template is None:
template = zope.component.queryMultiAdapter(
(self, self.request, self.context), IContentTemplate)
if template is None:
template = zope.component.getMultiAdapter(
(self, self.request), IContentTemplate)
self.form_result = template(self)
else:
self.form_result = self.template()
return self.form_result
@zope.interface.implementer(interfaces.IPageletAddForm)
class PageletAddForm(PageletForm, form.AddFormBase):
"""Add form mixin for pagelet implementations."""
def render(self):
if self._finished_add:
self.request.response.redirect(self.nextURL())
return ""
# render content template
if self.template is None:
template = zope.component.queryMultiAdapter(
(self, self.request, self.context), IContentTemplate)
if template is None:
template = zope.component.getMultiAdapter(
(self, self.request), IContentTemplate)
return template(self)
return self.template()
@zope.interface.implementer(interfaces.IPageletEditForm)
class PageletEditForm(PageletForm, form.EditFormBase):
"""Edit form mixin for pagelet implementations."""
@zope.interface.implementer(interfaces.IPageletDisplayForm)
class PageletDisplayForm(PageletForm, form.DisplayFormBase):
"""Display form mixin for pagelet implementations.""" | z3c.pagelet | /z3c.pagelet-3.0-py3-none-any.whl/z3c/pagelet/browser.py | browser.py |
Zope Public License (ZPL) Version 2.1
A copyright notice accompanies this license document that identifies the
copyright holders.
This license has been certified as open source. It has also been designated as
GPL compatible by the Free Software Foundation (FSF).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions in source code must retain the accompanying copyright
notice, this list of conditions, and the following disclaimer.
2. Redistributions in binary form must reproduce the accompanying copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Names of the copyright holders must not be used to endorse or promote
products derived from this software without prior written permission from the
copyright holders.
4. The right to distribute this software or to use it for any purpose does not
give you the right to use Servicemarks (sm) or Trademarks (tm) of the
copyright
holders. Use of them is covered by separate agreement with the copyright
holders.
5. If any files are modified, you must cause the modified files to carry
prominent notices stating that you changed the files and the date of any
change.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| z3c.pagelet | /z3c.pagelet-3.0-py3-none-any.whl/z3c.pagelet-3.0.dist-info/LICENSE.rst | LICENSE.rst |
=======
CHANGES
=======
1.1.0 (2021-12-14)
------------------
- Add support for Python 3.8, 3.9 and 3.10.
- Drop support for Python 3.4.
1.0.0 (2018-11-14)
------------------
- Add support for Python 3.6 and 3.7. Drop support for Python 3.5 and
below. Drop Python 2.6 support.
- Drop support for ``None`` passwords, since they are not supported in the
underlying APIs anymore.
1.0.0a1 (2013-02-28)
--------------------
- Add support for Python 3.3.
- Drop dependency on ``zope.app.testing`` and ``zope.app.authentication``.
- Replace deprecated ``zope.interface.implements`` usage with equivalent
``zope.interface.implementer`` decorator.
- Drop support for Python 2.4 and 2.5.
0.11.1 (2012-09-19)
-------------------
- ``TooSimilarPassword``: do not round ``maxSimilarity`` up, because we
sometimes use 0.999 to avoid the same password set.
0.999 would be displayed as 100% (100% vs. 100%)
0.11.0 (2012-08-09)
-------------------
- Better error messages for invalid password exceptions (when you reject the
user's password for being too short or too long, it's only polite to tell
them what the minimum/maximum password length is).
This introduces new translatable strings which haven't been translated yet.
0.10.1 (2011-03-28)
-------------------
- Minor changes:
* Password field: added ignoreEmpty=False parameter
* previousPasswords: always set the property, not just append
* some caching of IPasswordOptionsUtility property usage
0.10.0 (2010-03-24)
-------------------
- Check for relevancy of the request when counting failed login attempts as
early as possible. This prevents account locked errors raised for things like
resources.
0.9.0 (2010-02-18)
------------------
- Added Dutch translations (janwijbrand)
0.8.0 (2009-01-29)
------------------
- Feature: ``failedAttemptCheck``:
* increment failedAttempts on all/any request (this is the default)
* increment failedAttempts only on non-resource requests
* increment failedAttempts only on POST requests
- Feature: more specific exceptions on new password verification.
0.7.4 (2009-12-22)
------------------
- Fix: ``PrincipalMixIn.passwordSetOn`` happens to be ``None`` in case the
class is mixed in after the user was created, that caused a bug.
0.7.3 (2009-12-08)
------------------
- Fix: ``disallowPasswordReuse`` must not check ``None`` passwords.
0.7.2 (2009-08-07)
------------------
- German translations
0.7.1 (2009-07-02)
------------------
- Feature: ``passwordOptionsUtilityName`` property on the ``PrincipalMixIn``.
This allows to set different options for a set of users instead of storing
the direct values on the principal.
0.7.0 (2009-06-22)
------------------
- Feature: Even harder password settings:
* ``minLowerLetter``
* ``minUpperLetter``
* ``minDigits``
* ``minSpecials``
* ``minOthers``
* ``minUniqueCharacters``
* ``minUniqueLetters``: count and do not allow less then specified number
- Feature:
* ``disallowPasswordReuse``: do not allow to set a previously used password
- 100% test coverage
0.6.0 (2009-06-17)
------------------
- Features:
``PrincipalMixIn`` got some new properties:
* ``passwordExpired``: to force the expiry of the password
* ``lockOutPeriod``: to enable automatic lock and unlock on too many bad tries
``IPasswordOptionsUtility`` to have global password options:
* ``changePasswordOnNextLogin``: not implemented here, use
PrincipalMixIn.passwordExpired
* ``lockOutPeriod``: global counterpart of the PrincipalMixIn property
* ``passwordExpiresAfter``: global counterpart of the PrincipalMixIn property
* ``maxFailedAttempts``: global counterpart of the PrincipalMixIn property
Password checking goes like this (on the high level):
1. raise AccountLocked if too many bad tries and account should be locked
2. raise PasswordExpired if expired AND password matches
3. raise TooManyLoginFailures if too many bad tries
4. return whether password matches
More details in ``principal.txt``
- Added Russian translation
- Refactor PrincipalMixIn now() into a separate method to facilitate
override and testing
- Changed the order the password is checked:
1. check password against stored
2. check maxFailedAttempts, raise TooManyLoginFailures if over
3. if password is OK, check expirationDate, raise PasswordExpired if over
4. return whether password matches
This is because I need to be sure that PasswordExpired is raised only if the
password *IS* valid. Entering an invalid password *MUST NOT* raise
PasswordExpired, because I want to use PasswordExpired to allow the user
to change it's password. This should not happen if the user did not enter a
valid password.
0.5.0 (2008-10-21)
------------------
- Initial Release
| z3c.password | /z3c.password-1.1.0.tar.gz/z3c.password-1.1.0/CHANGES.rst | CHANGES.rst |
============
z3c.password
============
.. image:: https://github.com/zopefoundation/z3c.password/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/z3c.password/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/z3c.password/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/z3c.password?branch=master
.. image:: https://img.shields.io/pypi/v/z3c.password.svg
:target: https://pypi.python.org/pypi/z3c.password
.. image:: https://img.shields.io/pypi/pyversions/z3c.password.svg
:target: https://pypi.python.org/pypi/z3c.password/
This package provides an API and implementation of a password generation and
verification utility. A high-security implementation is provided that is
suitable for banks and other high-security institutions. The package also
offers a field and a property for those fields.
| z3c.password | /z3c.password-1.1.0.tar.gz/z3c.password-1.1.0/README.rst | README.rst |
"""Password Utility Interfaces
"""
import zope.interface
import zope.schema
from zope.i18n import translate
from z3c.password import MessageFactory as _
class InvalidPassword(zope.schema.ValidationError):
"""Invalid Password"""
i18n_message = None
def __str__(self):
if self.i18n_message:
return translate(self.i18n_message)
return super(InvalidPassword, self).__str__()
def doc(self):
if self.i18n_message:
return self.i18n_message
return self.__class__.__doc__
class NoPassword(InvalidPassword):
__doc__ = _('''No new password specified.''')
class TooShortPassword(InvalidPassword):
__doc__ = _('''Password is too short.''')
def __init__(self, minLength=None):
super(TooShortPassword, self).__init__()
self.minLength = minLength
if minLength is not None:
self.i18n_message = _(
'Password is too short (minimum length: ${minLength}).',
mapping=dict(minLength=minLength))
class TooLongPassword(InvalidPassword):
__doc__ = _('''Password is too long.''')
def __init__(self, maxLength=None):
super(TooLongPassword, self).__init__()
self.maxLength = maxLength
if maxLength is not None:
self.i18n_message = _(
'Password is too long (maximum length: ${maxLength}).',
mapping=dict(maxLength=maxLength))
class TooSimilarPassword(InvalidPassword):
__doc__ = _('''Password is too similar to old one.''')
def __init__(self, similarity=None, maxSimilarity=None):
super(TooSimilarPassword, self).__init__()
self.similarity = similarity
self.maxSimilarity = maxSimilarity
if similarity is not None and maxSimilarity is not None:
self.i18n_message = _(
'Password is too similar to old one'
' (similarity ${similarity}%, should be at most'
' ${maxSimilarity}%).',
mapping=dict(similarity=int(round(similarity * 100)),
maxSimilarity=int(maxSimilarity * 100)))
class TooManyGroupCharacters(InvalidPassword):
__doc__ = _('''Password contains too many characters of one group.''')
def __init__(self, groupMax=None):
super(TooManyGroupCharacters, self).__init__()
self.groupMax = groupMax
if groupMax is not None:
self.i18n_message = _(
'Password contains too many characters of one group'
' (should have at most ${groupMax}).',
mapping=dict(groupMax=groupMax))
class TooFewGroupCharacters(InvalidPassword):
__doc__ = _(
'''Password does not contain enough characters of one group.''')
class TooFewGroupCharactersLowerLetter(TooFewGroupCharacters):
__doc__ = _(
'Password does not contain enough characters of lowercase letters.')
def __init__(self, minLowerLetter=None):
super(TooFewGroupCharactersLowerLetter, self).__init__()
self.minLowerLetter = minLowerLetter
if minLowerLetter is not None:
self.i18n_message = _(
'Password does not contain enough characters of lowercase'
' letters (should have at least ${minLowerLetter}).',
mapping=dict(minLowerLetter=minLowerLetter))
class TooFewGroupCharactersUpperLetter(TooFewGroupCharacters):
__doc__ = _(
'Password does not contain enough characters of uppercase letters.')
def __init__(self, minUpperLetter=None):
super(TooFewGroupCharactersUpperLetter, self).__init__()
self.minUpperLetter = minUpperLetter
if minUpperLetter is not None:
self.i18n_message = _(
'Password does not contain enough characters of uppercase'
' letters (should have at least ${minUpperLetter}).',
mapping=dict(minUpperLetter=minUpperLetter))
class TooFewGroupCharactersDigits(TooFewGroupCharacters):
__doc__ = _('''Password does not contain enough characters of digits.''')
def __init__(self, minDigits=None):
super(TooFewGroupCharactersDigits, self).__init__()
self.minDigits = minDigits
if minDigits is not None:
self.i18n_message = _(
'Password does not contain enough characters of digits'
' (should have at least ${minDigits}).',
mapping=dict(minDigits=minDigits))
class TooFewGroupCharactersSpecials(TooFewGroupCharacters):
__doc__ = _(
'Password does not contain enough characters of special characters.')
def __init__(self, minSpecials=None):
super(TooFewGroupCharactersSpecials, self).__init__()
self.minSpecials = minSpecials
if minSpecials is not None:
self.i18n_message = _(
'Password does not contain enough characters of special'
' characters (should have at least ${minSpecials}).',
mapping=dict(minSpecials=minSpecials))
class TooFewGroupCharactersOthers(TooFewGroupCharacters):
__doc__ = _(
'''Password does not contain enough characters of other characters.''')
def __init__(self, minOthers=None):
super(TooFewGroupCharactersOthers, self).__init__()
self.minOthers = minOthers
if minOthers is not None:
self.i18n_message = _(
'Password does not contain enough characters of other'
' characters (should have at least ${minOthers}).',
mapping=dict(minOthers=minOthers))
class TooFewUniqueCharacters(InvalidPassword):
__doc__ = _('''Password does not contain enough unique characters.''')
def __init__(self, minUniqueCharacters=None):
super(TooFewUniqueCharacters, self).__init__()
self.minUniqueCharacters = minUniqueCharacters
if minUniqueCharacters is not None:
self.i18n_message = _(
'Password does not contain enough unique characters'
' (should have at least ${minUniqueCharacters}).',
mapping=dict(minUniqueCharacters=minUniqueCharacters))
class TooFewUniqueLetters(InvalidPassword):
__doc__ = _('''Password does not contain enough unique letters.''')
def __init__(self, minUniqueLetters=None):
super(TooFewUniqueLetters, self).__init__()
self.minUniqueLetters = minUniqueLetters
if minUniqueLetters is not None:
self.i18n_message = _(
'Password does not contain enough unique letters'
' (should have at least ${minUniqueLetters}).',
mapping=dict(minUniqueLetters=minUniqueLetters))
class PasswordExpired(Exception):
__doc__ = _('''The password has expired.''')
def __init__(self, principal):
self.principal = principal
Exception.__init__(self, self.__doc__)
class PreviousPasswordNotAllowed(InvalidPassword):
__doc__ = _('''The password set was already used before.''')
def __init__(self, principal):
self.principal = principal
Exception.__init__(self, self.__doc__)
class TooManyLoginFailures(Exception):
__doc__ = _('''The password was entered incorrectly too often.''')
def __init__(self, principal):
self.principal = principal
Exception.__init__(self, self.__doc__)
TML_CHECK_ALL = None
TML_CHECK_NONRESOURCE = 'nonres'
TML_CHECK_POSTONLY = 'post'
class AccountLocked(Exception):
__doc__ = _('The account is locked, because the password was '
'entered incorrectly too often.')
def __init__(self, principal):
self.principal = principal
Exception.__init__(self, self.__doc__)
class IPasswordUtility(zope.interface.Interface):
"""Component to verify and generate passwords.
The purpose of this utility is to make common password-related tasks, such
as verification and creation simple. However, only the collection of those
utilites provide an overall net worth.
"""
description = zope.schema.Text(
title=_(u'Description'),
description=_(u'A description of the password utility.'),
required=False)
def verify(new, ref=None):
"""Check whether the new password is valid.
When a passward is good, the method simply returns, otherwise an
``InvalidPassword`` exception is raised.
It is up to the implementation to define the semantics of a valid
password. The sematics should ideally be described in the description.
The ``ref`` argument is a reference password. In many scenarios it
will be the old password, so that the method can ensure sufficient
dissimilarity between the new and old password.
"""
def generate(ref=None):
"""Generate a valid password.
The ``ref`` argument is a reference password. In many scenarios it
will be the old password, so that the method can ensure sufficient
dissimilarity between the new and old password.
"""
class IHighSecurityPasswordUtility(IPasswordUtility):
"""A password utility for very secure passwords."""
minLength = zope.schema.Int(
title=_(u'Minimum Length'),
description=_(u'The minimum length of the password.'),
required=False,
default=None)
maxLength = zope.schema.Int(
title=_(u'Maximum Length'),
description=_(u'The maximum length of the password.'),
required=False,
default=None)
@zope.interface.invariant
def minMaxLength(task):
if task.minLength is not None and task.maxLength is not None:
if task.minLength > task.maxLength:
raise zope.interface.Invalid(
u"Minimum length must not be greater than the maximum"
u" length.")
groupMax = zope.schema.Int(
title=_(u'Maximum Characters of Group'),
description=_(u'The maximum amount of characters that a password can '
u'have from one group. The groups are: digits, letters, '
u'punctuation.'),
required=False,
default=None)
maxSimilarity = zope.schema.Float(
title=_(u'Old/New Similarity'),
description=(
u'The similarity ratio between the new and old password.'),
required=False,
default=None)
minLowerLetter = zope.schema.Int(
title=_(u'Minimum Number of Lowercase letters'),
description=_(u'The minimum amount of lowercase letters that a '
u'password must have.'),
required=False,
default=None)
minUpperLetter = zope.schema.Int(
title=_(u'Minimum Number of Uppercase letters'),
description=_(u'The minimum amount of uppercase letters that a '
u'password must have.'),
required=False,
default=None)
minDigits = zope.schema.Int(
title=_(u'Minimum Number of Numeric digits'),
description=_(u'The minimum amount of numeric digits that a '
u'password must have.'),
required=False,
default=None)
minSpecials = zope.schema.Int(
title=_(u'Minimum Number of Special characters'),
description=_(u'The minimum amount of special characters that a '
u'password must have.'),
required=False,
default=None)
# WARNING! generating a password with Others is not yet supported
minOthers = zope.schema.Int(
title=_(u'Minimum Number of Other characters'),
description=_(u'The minimum amount of other characters that a '
u'password must have.'),
required=False,
default=None)
@zope.interface.invariant
def saneMinimums(task):
minl = 0
if task.minLowerLetter:
if task.minLowerLetter > task.groupMax:
raise zope.interface.Invalid(
u"Any group minimum length must NOT be greater than "
u"the maximum group length.")
minl += task.minLowerLetter
if task.minUpperLetter:
if task.minUpperLetter > task.groupMax:
raise zope.interface.Invalid(
u"Any group minimum length must NOT be greater than "
u"the maximum group length.")
minl += task.minUpperLetter
if task.minDigits:
if task.minDigits > task.groupMax:
raise zope.interface.Invalid(
u"Any group minimum length must NOT be greater than "
u"the maximum group length.")
minl += task.minDigits
if task.minSpecials:
if task.minSpecials > task.groupMax:
raise zope.interface.Invalid(
u"Any group minimum length must NOT be greater than "
u"the maximum group length.")
minl += task.minSpecials
if task.minOthers:
if task.minOthers > task.groupMax:
raise zope.interface.Invalid(
u"Any group minimum length must NOT be greater than "
u"the maximum group length.")
minl += task.minOthers
if task.maxLength is not None:
if minl > task.maxLength:
raise zope.interface.Invalid(
u"Sum of group minimum lengths must NOT be greater than "
u"the maximum password length.")
minUniqueLetters = zope.schema.Int(
title=_(u'Minimum Number of Unique letters'),
description=_(u'The minimum amount of unique letters that a '
u'password must have. This is against passwords '
u'like `aAaA0000`. All characters taken lowercase.'),
required=False,
default=None)
@zope.interface.invariant
def minUniqueLettersLength(task):
if (task.minUniqueLetters is not None
and task.minUniqueLetters is not None):
if task.minUniqueLetters > task.maxLength:
raise zope.interface.Invalid(
u"Minimum unique letters number must not be greater than "
u"the maximum length.")
minUniqueCharacters = zope.schema.Int(
title=_(u'Minimum Number of Unique characters'),
description=_(u'The minimum amount of unique characters that a '
u'password must have. This is against passwords '
u'like `aAaA0000`. All characters taken lowercase.'),
required=False,
default=None)
@zope.interface.invariant
def minUniqueCharactersLength(task):
if (task.minUniqueCharacters is not None
and task.minUniqueCharacters is not None):
if task.minUniqueCharacters > task.maxLength:
raise zope.interface.Invalid(
u"Minimum unique characters length must not be greater"
u" than the maximum length.")
class IPasswordOptionsUtility(zope.interface.Interface):
"""Different general security options.
The purpose of this utility is to make common password-related options
available
"""
changePasswordOnNextLogin = zope.schema.Bool(
title=_(u'Password must be changed on next login'),
description=_(u'Password must be changed on next login'),
required=False,
default=False)
passwordExpiresAfter = zope.schema.Int(
title=_(u'Password expires after (days)'),
description=_(u'Password expires after (days)'),
required=False,
default=None)
lockOutPeriod = zope.schema.Int(
title=_(u'Lockout period (minutes)'),
description=_(
u'Lockout the user after too many failed password entries'
u'for this many minutes. The user can try again after.'),
required=False,
default=None)
maxFailedAttempts = zope.schema.Int(
title=_(u'Max. number of failed password entries before account is'
u' locked'),
description=_(
u'Specifies the amount of failed attempts allowed to check '
u'the password before the password is locked and no new '
u'password can be provided.'),
required=False,
default=None)
failedAttemptCheck = zope.schema.Choice(
title=_(u'Failed password check method'),
description=_(u'Failed password check method. '
'All requests, non-reqource requests, POST requests.'),
required=False,
values=[TML_CHECK_ALL, TML_CHECK_NONRESOURCE, TML_CHECK_POSTONLY],
default=TML_CHECK_ALL)
disallowPasswordReuse = zope.schema.Bool(
title=_(u'Disallow Password Reuse'),
description=_(u'Do not allow to set a previously set password again.'),
required=False,
default=False) | z3c.password | /z3c.password-1.1.0.tar.gz/z3c.password-1.1.0/src/z3c/password/interfaces.py | interfaces.py |
"""Principal MixIn for Advanced Password Management
"""
import datetime
import persistent.list
import zope.component
from zope.security.management import getInteraction
from z3c.password import interfaces
class PrincipalMixIn(object):
"""A Principal Mixin class for ``zope.app.principalfolder``'s internal
principal."""
passwordExpiresAfter = None
passwordSetOn = None
# force PasswordExpired, e.g. for changePasswordOnNextLogin
passwordExpired = False
failedAttempts = 0
failedAttemptCheck = interfaces.TML_CHECK_ALL
maxFailedAttempts = None
lastFailedAttempt = None
lockOutPeriod = None
disallowPasswordReuse = None
previousPasswords = None
passwordOptionsUtilityName = None
def _checkDisallowedPreviousPassword(self, password):
if self._disallowPasswordReuse():
if self.previousPasswords is not None and password is not None:
# hack, but this should work with zope.app.authentication and
# z3c.authenticator
passwordManager = self._getPasswordManager()
for pwd in self.previousPasswords:
if passwordManager.checkPassword(pwd, password):
raise interfaces.PreviousPasswordNotAllowed(self)
def getPassword(self):
return super(PrincipalMixIn, self).getPassword()
def setPassword(self, password, passwordManagerName=None):
self._checkDisallowedPreviousPassword(password)
super(PrincipalMixIn, self).setPassword(password, passwordManagerName)
if self._disallowPasswordReuse():
if self.previousPasswords is None:
self.previousPasswords = persistent.list.PersistentList()
if self.password is not None:
# storm/custom property does not like a simple append
ppwd = self.previousPasswords
ppwd.append(self.password)
self.previousPasswords = ppwd
self.passwordSetOn = self.now()
self.failedAttempts = 0
self.lastFailedAttempt = None
self.passwordExpired = False
password = property(getPassword, setPassword)
def now(self):
# hook to facilitate testing and easier override
return datetime.datetime.now()
def _isRelevantRequest(self):
fac = self._failedAttemptCheck()
if fac is None:
return True
if fac == interfaces.TML_CHECK_ALL:
return True
interaction = getInteraction()
try:
request = interaction.participations[0]
except IndexError:
return True # no request, we regard that as relevant.
if fac == interfaces.TML_CHECK_NONRESOURCE:
if '/@@/' in request.getURL():
return False
return True
if fac == interfaces.TML_CHECK_POSTONLY:
if request.method == 'POST':
return True
return False
def checkPassword(self, pwd, ignoreExpiration=False, ignoreFailures=False):
# keep this as fast as possible, because it will be called (usually)
# for EACH request
# Check the password
same = super(PrincipalMixIn, self).checkPassword(pwd)
# Do not try to record failed attempts or raise account locked
# errors for requests that are irrelevant in this regard.
if not self._isRelevantRequest():
return same
if not ignoreFailures and self.lastFailedAttempt is not None:
if self.tooManyLoginFailures():
locked = self.accountLocked()
if locked is None:
# no lockPeriod
pass
elif locked:
# account locked by tooManyLoginFailures and within
# lockPeriod
if not same:
self.lastFailedAttempt = self.now()
raise interfaces.AccountLocked(self)
else:
# account locked by tooManyLoginFailures and out of
# lockPeriod
self.failedAttempts = 0
self.lastFailedAttempt = None
if same:
# successful attempt
if not ignoreExpiration:
if self.passwordExpired:
raise interfaces.PasswordExpired(self)
# Make sure the password has not been expired
expiresOn = self.passwordExpiresOn()
if expiresOn is not None:
if expiresOn < self.now():
raise interfaces.PasswordExpired(self)
add = 0
else:
# failed attempt, record it, increase counter
self.failedAttempts += 1
self.lastFailedAttempt = self.now()
add = 1
# If the maximum amount of failures has been reached notify the
# system by raising an error.
if not ignoreFailures:
if self.tooManyLoginFailures(add):
raise interfaces.TooManyLoginFailures(self)
if same and self.failedAttempts != 0:
# if all nice and good clear failure counter
self.failedAttempts = 0
self.lastFailedAttempt = None
return same
def tooManyLoginFailures(self, add=0):
attempts = self._maxFailedAttempts()
# this one needs to be >=, because... data just does not
# get saved on an exception when running under of a full Zope env.
# the dance around ``add`` has the same roots
# we need to be able to increase the failedAttempts count and not raise
# at the same time
if attempts is not None:
attempts += add
if self.failedAttempts >= attempts:
return True
return False
def accountLocked(self):
lockPeriod = self._lockOutPeriod()
if lockPeriod is not None:
# check if the user locked himself
if (self.lastFailedAttempt is not None
and self.lastFailedAttempt + lockPeriod > self.now()):
return True
else:
return False
return None
def passwordExpiresOn(self):
expires = self._passwordExpiresAfter()
if expires is None:
return None
if self.passwordSetOn is None:
return None
return self.passwordSetOn + expires
def _optionsUtility(self):
if self.passwordOptionsUtilityName:
# if we have a utility name, then it must be there
return zope.component.getUtility(
interfaces.IPasswordOptionsUtility,
name=self.passwordOptionsUtilityName)
return zope.component.queryUtility(
interfaces.IPasswordOptionsUtility, default=None)
def _passwordExpiresAfter(self):
if self.passwordExpiresAfter is not None:
return self.passwordExpiresAfter
options = self._optionsUtility()
if options is None:
return self.passwordExpiresAfter
else:
days = options.passwordExpiresAfter
if days is not None:
return datetime.timedelta(days=days)
else:
return self.passwordExpiresAfter
def _lockOutPeriod(self):
if self.lockOutPeriod is not None:
return self.lockOutPeriod
options = self._optionsUtility()
if options is None:
return self.lockOutPeriod
else:
minutes = options.lockOutPeriod
if minutes is not None:
return datetime.timedelta(minutes=minutes)
else:
return self.lockOutPeriod
def _failedAttemptCheck(self):
if self.failedAttemptCheck is not None:
return self.failedAttemptCheck
options = self._optionsUtility()
if options is None:
return self.failedAttemptCheck
else:
fac = options.failedAttemptCheck
if fac is not None:
return fac
else:
return self.failedAttemptCheck
def _maxFailedAttempts(self):
if self.maxFailedAttempts is not None:
return self.maxFailedAttempts
options = self._optionsUtility()
if options is None:
return self.maxFailedAttempts
else:
count = options.maxFailedAttempts
if count is not None:
return count
else:
return self.maxFailedAttempts
def _disallowPasswordReuse(self):
if self.disallowPasswordReuse is not None:
return self.disallowPasswordReuse
options = self._optionsUtility()
if options is None:
return self.disallowPasswordReuse
else:
dpr = options.disallowPasswordReuse
if dpr is not None:
return dpr
else:
return self.disallowPasswordReuse | z3c.password | /z3c.password-1.1.0.tar.gz/z3c.password-1.1.0/src/z3c/password/principal.py | principal.py |
============================
Advnaced Password Management
============================
This package provides an API and implementation of a password generation and
verification utility. A high-security implementation is provided that is
suitable for banks and other high-security institutions. The package also
offers a field and a property for those fields.
The Password Utility
--------------------
The password utilities are located in the ``password`` module.
>>> from z3c.password import password
The module provides a trivial sample and a high-security implementation of the
utility. The password utility provides two methods.
>>> pwd = password.TrivialPasswordUtility()
The first is to verify the password. The first argument is the new password
and the second, optional argument a reference password, usually the old
one. When the verification fails an ``InvalidPassword`` exception is raised,
otherwise the method simply returns. In the case of the trivial password
utility, this method always returns:
>>> pwd.verify('foo')
>>> pwd.verify('foobar', 'foo')
The second method generates a password conform to the security constraints of
the password utility. The trivial password utility always returns the password
"trivial".
>>> pwd.generate()
'trivial'
>>> pwd.generate('foo')
'trivial'
The ``generate()`` method also accepts the optional reference
password. Finally, each password utility must provide a description explaining
its security constraints:
>>> print(pwd.description)
All passwords are accepted and always the "trivial" password is generated.
Let's now look at the high-security password utility. In its constructor you
can specify several constraints; the minimum and maximum length of the
password, the maximum of characters of one group (lower letters, upper
letters, digits, punctuation, other), and the maximum similarity score.
>>> pwd = password.HighSecurityPasswordUtility()
>>> pwd.minLength
8
>>> pwd.maxLength
12
>>> pwd.groupMax
6
>>> print(pwd.maxSimilarity)
0.6
- When the password is empty, then the password is invalid:
>>> pwd.verify(None)
Traceback (most recent call last):
...
NoPassword
>>> pwd.verify('')
Traceback (most recent call last):
...
NoPassword
>>> pwd.verify('', 'other')
Traceback (most recent call last):
...
NoPassword
- Next, it is verified that the password has the correct length:
>>> pwd.verify('foo')
Traceback (most recent call last):
...
TooShortPassword: Password is too short (minimum length: 8).
>>> pwd.verify('foobar-foobar')
Traceback (most recent call last):
...
TooLongPassword: Password is too long (maximum length: 12).
>>> pwd.verify('fooBar12')
- Once the length is verified, the password is checked for similarity. If no
reference password is provided, then this check always passes:
>>> pwd.verify('fooBar12')
>>> pwd.verify('fooBar12', 'fooBAR--')
>>> pwd.verify('fooBar12', 'foobar12')
Traceback (most recent call last):
...
TooSimilarPassword: Password is too similar to old one (similarity 88%, should be at most 60%).
>>> pwd2 = password.HighSecurityPasswordUtility()
>>> pwd2.maxSimilarity = 0.999
>>> pwd2.verify('fooBar12', 'fooBar12')
Traceback (most recent call last):
...
TooSimilarPassword: Password is too similar to old one (similarity 100%, should be at most 99%).
- The final check ensures that the password does not have too many characters
of one group. The groups are: lower letters, upper letters, digits,
punctuation, and others.
>>> pwd.verify('fooBarBlah')
Traceback (most recent call last):
...
TooManyGroupCharacters: Password contains too many characters of one group (should have at most 6).
>>> pwd.verify('FOOBARBlah')
Traceback (most recent call last):
...
TooManyGroupCharacters: Password contains too many characters of one group (should have at most 6).
>>> pwd.verify('12345678')
Traceback (most recent call last):
...
TooManyGroupCharacters: Password contains too many characters of one group (should have at most 6).
>>> pwd.verify('........')
Traceback (most recent call last):
...
TooManyGroupCharacters: Password contains too many characters of one group (should have at most 6).
>>> from z3c.password._compat import unichr
>>> pwd.verify(unichr(0x0e1)*8)
Traceback (most recent call last):
...
TooManyGroupCharacters: Password contains too many characters of one group (should have at most 6).
Let's now verify a list of password that were provided by a bank:
>>> for new in ('K7PzX2JZ', 'DznMLIww', 'ks59Ursq', 'YUcsuIrQ', 'bPEUFGSa',
... 'lUmtG0TP', 'ISfUKoTe', 'NKGY0aIJ', 'XyUuSHX4', 'CaFE1R5p'):
... pwd.verify(new)
Let's now generate some passwords. To make them predictable, we specify a seed
when initializing the utility:
>>> pwd = password.HighSecurityPasswordUtility(seed=8)
>>> res = pwd.generate()
>>> res in ['{l%ix~t8R', 'VWqy{fkrF'] # Py 2/3 diff in random.
True
Force a LOT to make coverage happy:
>>> for x in range(256):
... _ =pwd.generate()
Even higher security settings
-----------------------------
We can specify how many of a selected character group we want to have in the
password.
We want to have at least 5 lowercase letters in the password:
>>> pwd = password.HighSecurityPasswordUtility(seed=8)
>>> pwd.minLowerLetter = 5
>>> pwd.verify('FOOBAR123')
Traceback (most recent call last):
...
TooFewGroupCharactersLowerLetter: Password does not contain enough characters of lowercase letters (should have at least 5).
>>> pwd.verify('foobAR123')
Traceback (most recent call last):
...
TooFewGroupCharactersLowerLetter: Password does not contain enough characters of lowercase letters (should have at least 5).
>>> pwd.verify('foobaR123')
>>> res = pwd.generate()
>>> res in ['Us;iwbzM[J', 'VWqy{fkrF']
True
We want to have at least 5 uppercase letters in the password:
>>> pwd = password.HighSecurityPasswordUtility(seed=8)
>>> pwd.minUpperLetter = 5
>>> pwd.verify('foobar123')
Traceback (most recent call last):
...
TooFewGroupCharactersUpperLetter: Password does not contain enough characters of uppercase letters (should have at least 5).
>>> pwd.verify('FOOBar123')
Traceback (most recent call last):
...
TooFewGroupCharactersUpperLetter: Password does not contain enough characters of uppercase letters (should have at least 5).
>>> pwd.verify('fOOBAR123')
>>> res = pwd.generate()
>>> res in ['OvMPN3Bi', '[j#`(CSFbLRC']
True
We want to have at least 5 digits in the password:
>>> pwd = password.HighSecurityPasswordUtility(seed=8)
>>> pwd.minDigits = 5
>>> pwd.verify('foobar123')
Traceback (most recent call last):
...
TooFewGroupCharactersDigits: Password does not contain enough characters of digits (should have at least 5).
>>> pwd.verify('FOOBa1234')
Traceback (most recent call last):
...
TooFewGroupCharactersDigits: Password does not contain enough characters of digits (should have at least 5).
>>> pwd.verify('fOBA12345')
>>> res = pwd.generate()
>>> res in ['(526vK(>Z42v', 'Rv+3Dr0+501']
True
We want to have at least 5 specials in the password:
>>> pwd = password.HighSecurityPasswordUtility(seed=8)
>>> pwd.minSpecials = 5
>>> pwd.verify('foo(bar)')
Traceback (most recent call last):
...
TooFewGroupCharactersSpecials: Password does not contain enough characters of special characters (should have at least 5).
>>> pwd.verify('FO.#(Ba1)')
Traceback (most recent call last):
...
TooFewGroupCharactersSpecials: Password does not contain enough characters of special characters (should have at least 5).
>>> pwd.verify('fO.,;()5')
>>> res = pwd.generate()
>>> res in ['?d{*~2q|P', 's:i(e!`ys-6~']
True
We want to have at least 5 others in the password:
>>> pwd = password.HighSecurityPasswordUtility(seed=8)
>>> pwd.minOthers = 5
>>> pwd.verify('foobar'+unichr(0x0c3)+unichr(0x0c4))
Traceback (most recent call last):
...
TooFewGroupCharactersOthers: Password does not contain enough characters of other characters (should have at least 5).
>>> pwd.verify('foobar'+unichr(0x0c3)+unichr(0x0c4)+unichr(0x0e1))
Traceback (most recent call last):
...
TooFewGroupCharactersOthers: Password does not contain enough characters of other characters (should have at least 5).
>>> pwd.verify('fOO'+unichr(0x0e1)*5)
Generating passwords with others not yet supported
#>>> pwd.generate()
#'?d{*~2q|P'
#
#>>> pwd.generate()
#'(8a5\\(^}vB'
We want to have at least 5 different characters in the password:
>>> pwd = password.HighSecurityPasswordUtility(seed=8)
>>> pwd.minUniqueCharacters = 5
>>> pwd.verify('foofoo1212')
Traceback (most recent call last):
...
TooFewUniqueCharacters: Password does not contain enough unique characters (should have at least 5).
>>> pwd.verify('FOOfoo2323')
Traceback (most recent call last):
...
TooFewUniqueCharacters: Password does not contain enough unique characters (should have at least 5).
>>> pwd.verify('fOOBAR123')
>>> res = pwd.generate()
>>> res in ['{l%ix~t8R', 'VWqy{fkrF']
True
We want to have at least 5 different letters in the password:
>>> pwd = password.HighSecurityPasswordUtility(seed=8)
>>> pwd.minUniqueLetters = 5
>>> pwd.verify('foofoo1212')
Traceback (most recent call last):
...
TooFewUniqueLetters: Password does not contain enough unique letters (should have at least 5).
>>> pwd.verify('FOOBfoob2323')
Traceback (most recent call last):
...
TooFewUniqueLetters: Password does not contain enough unique letters (should have at least 5).
>>> pwd.verify('fOOBAR123')
>>> res = pwd.generate()
>>> res in ['{l%ix~t8R', 'VWqy{fkrF']
True
The Password Field
------------------
The password field can be used to specify an advanced password. It extends the
standard ``zope.schema`` password field with the ``checker`` attribute. The
checker is either a password utility (as specified above) or the name of such a
a utility. The checker is used to verify whether a password is acceptable or
not.
Let's now create the field:
>>> import datetime
>>> from zope.password.password import PlainTextPasswordManager
>>> from z3c.password import field
>>> pwd = password.HighSecurityPasswordUtility(seed=8)
>>> pwdField = field.Password(
... __name__='password',
... title=u'Password',
... checker=pwd)
Let's validate a value:
>>> pwdField.validate(u'fooBar12')
>>> pwdField.validate(u'fooBar')
Traceback (most recent call last):
...
TooShortPassword: Password is too short (minimum length: 8).
Validation must work on bound fields too:
Let's now create a principal:
>>> from zope.pluggableauth.plugins import principalfolder
>>> from z3c.password import principal
>>> class MyPrincipal(principal.PrincipalMixIn,
... principalfolder.InternalPrincipal):
... pass
>>> user = MyPrincipal('srichter', '123123', u'Stephan Richter')
Bind the field:
>>> bound = pwdField.bind(user)
>>> bound.validate(u'fooBar12')
>>> bound.validate(u'fooBar')
Traceback (most recent call last):
...
TooShortPassword: Password is too short (minimum length: 8).
Let's create a principal without the PrincipalMixIn:
>>> user = principalfolder.InternalPrincipal('srichter', '123123',
... u'Stephan Richter')
Bind the field:
>>> bound = pwdField.bind(user)
>>> bound.validate(u'fooBar12')
>>> bound.validate(u'fooBar')
Traceback (most recent call last):
...
TooShortPassword: Password is too short (minimum length: 8).
Other common usecase is to do a utility and specify it's name as checker.
>>> import zope.component
>>> zope.component.provideUtility(pwd, name='my password checker')
Recreate the field:
>>> pwdField = field.Password(
... __name__='password',
... title=u'Password',
... checker='my password checker')
Let's validate a value:
>>> pwdField.validate(u'fooBar12')
>>> pwdField.validate(u'fooBar')
Traceback (most recent call last):
...
TooShortPassword: Password is too short (minimum length: 8).
Edge cases.
No checker specified.
>>> pwdField = field.Password(
... __name__='password',
... title=u'Password')
Validation silently succeeds with a checker:
>>> pwdField.validate(u'fooBar12')
>>> pwdField.validate(u'fooBar')
Bad utility name.
>>> pwdField = field.Password(
... __name__='password',
... title=u'Password',
... checker='foobar password checker')
Burps on the utility lookup as expected:
>>> pwdField.validate(u'fooBar12')
Traceback (most recent call last):
...
ComponentLookupError:...
Bound object does not have the property:
>>> pwdField = field.Password(
... __name__='foobar',
... title=u'Password',
... checker=pwd)
>>> bound = pwdField.bind(user)
Validation silently succeeds:
>>> bound.validate(u'fooBar12')
| z3c.password | /z3c.password-1.1.0.tar.gz/z3c.password-1.1.0/src/z3c/password/README.txt | README.txt |
=====================================
Using ReportLab to generate PDF Views
=====================================
This package,
>>> import z3c.pdftemplate
provides the functionality of creating browser views that generate PDFs
instead of HTML using reportlab's PDF writer technology. There are several
ways to use the features in this package, which are demonstrated in the text
below.
But first we have to load the directives' meta configuration:
>>> import zope.component
>>> from zope.publisher.browser import TestRequest
>>> from zope.configuration import xmlconfig
>>> context = xmlconfig.file('meta.zcml', package=z3c.pdftemplate)
Using ``z3c.rml`` and ReportLab to generate PDF Views
-----------------------------------------------------
See DEPENDENCIES.cfg, this lib depends on some 3rd party libraries.
Purpose: PDF-Generration with the help of ``z3c.rml`` (an open source
implementation of RML) and Reportlab. The ``z3c.rml`` is really a dialect of
the official RML and supports many more features, such as charting while still
remaining compatible with the commercial version of RML as much as possible.
This package provides the functionality of creating browser views that
generate PDFs instead of HTML using reportlab's PDF writer technology.
But first we have to load the directives' meta configuration:
>>> from zope.configuration import xmlconfig
>>> context = xmlconfig.file('meta.zcml', package=z3c.pdftemplate)
RML, an XML-dialect developed by Reportlab.org, is much like HTML in that it
lets you define the structure of a PDF document. The RML is dynamically
generated using page templates and then used to generate a PDF file.
Let's say we want to create a PDF that shows the contents of a folder. The
first step is to create a rml-document that contains the structure of the
PDF. The following folder contents document template is available in
``rml_contents.pt``
::
<?xml version="1.0" encoding="iso-8859-1" standalone="no" ?>
<!DOCTYPE document SYSTEM "rml_1_0.dtd">
<document
xmlns:tal="http://xml.zope.org/namespaces/tal"
xmlns:metal="http://xml.zope.org/namespaces/metal"
filename="contents.pdf">
<content>
<para style="FolderName">
Folder Name:
<tal:block
condition="context/__name__"
replace="context/__name__|default" />
<tal:block condition="not:context/__name__"><no name></tal:block>
</para>
<spacer height="30" />
<table splitbyrow="1" repeatrows="0" repeatcols="0" style="ContentTable">
<tr>
<td>Name</td>
<td>Title</td>
<td>Size</td>
<td>Created</td>
<td>Modified</td>
</tr>
<tr tal:repeat="item view/listContentInfo">
<td tal:content="item/id">me.png</td>
<td tal:content="item/title|default"><no title></td>
<td tal:content="item/size/sizeForDisplay|nothing">34.5 kB</td>
<td tal:content="item/created|default"></td>
<td tal:content="item/modified|default"></td>
</tr>
</table>
<action name="frameEnd" />
</content>
</document>
Pretty easy isn't it? Fortunately, we can simply reuse the ``Contents`` view
class for the HTML contents view.
Now that we have the template and the document, we can simply register the
view:
>>> context = xmlconfig.string("""
... <configure xmlns:browser="http://namespaces.zope.org/browser">
... <browser:rml2pdf
... name="rmlsample.pdf"
... for="zope.app.folder.interfaces.IFolder"
... template="sample/rml_contents.pt"
... class="zope.app.container.browser.contents.Contents"
... permission="zope.Public"
... />
... </configure>
... """, context)
Once we have created a folder instance:
>>> from zope.app.folder.folder import Folder
>>> folder = Folder()
>>> folder.__name__ = 'my folder'
>>> folder['subFolder'] = Folder()
we can can look up the view
>>> class Principal:
... id = 'bob'
>>> request = TestRequest()
>>> request.setPrincipal(Principal())
>>> contents = zope.component.getMultiAdapter((folder, request),
... name="rmlsample.pdf")
and create the PDF:
>>> contents() #doctest: +ELLIPSIS
'%PDF-1.4...'
| z3c.pdftemplate | /z3c.pdftemplate-0.2.0.tar.gz/z3c.pdftemplate-0.2.0/src/z3c/pdftemplate/README.txt | README.txt |
Introduction
============
z3c.persistentfactory provides a Persistentfactory class that wraps a
method in a persistent wrapper. It also provides a function decorator
for use on class method definitions such that a persistent factory
will be used when the method is accessed on instance of the class.
See z3c/persistentfactory/README.txt for more details.
Also see z3c/persistentfactory/declarartions.txt for details about a
mixin Declarer class for classes implementing callable instances whose
declarations should pickle and persist correctly.
| z3c.persistentfactory | /z3c.persistentfactory-0.3.tar.gz/z3c.persistentfactory-0.3/README.txt | README.txt |
;-*-Doctest-*-
=====================
z3c.persistentfactory
=====================
The ZCA and the ZODB are a good combination where components require
persistent state. ZCA factories or handlers typically retrieve any
persistent state required from the persistent objects being adapted.
If the persistent state required is not specific to the objects being
adapted, a common solution is to register a persistent utility which
is then looked up in the factory or handler. The persistent utility
approach requires, however, that the one appropriate utility is looked
up which requires support in the ZCA registrations either in the
interface provided or the utility name.
In some cases, however, it is more consistent with the object oriented
semantics of Python and the ZCA to think of the factory or handler as
an instance method of a persistent object. With this approach the
non-context specific persistent state can be accessed on self.
Instance Method Event Handler
=============================
One example where this may be useful is where some non-context
persistent state is tightly coupled to some event handlers in such a
way where instance methods are better semantics.
The Baz class uses the decorator in the python code. Note that the
factory decorator must come before the declaration decorators so that
it will be run last and will reflect the declarations.
>>> from z3c.persistentfactory import testing
>>> baz = testing.Baz()
Register the persistent factory wrapped instance method as a handler.
>>> from zope import component
>>> component.provideHandler(factory=baz.factory)
The method adapts IFoo, so create an object providing IFoo to be used
as the event.
>>> component.adaptedBy(baz.factory)
(<InterfaceClass z3c.persistentfactory.testing.IFoo>,)
>>> from zope import interface
>>> foo = testing.Foo()
>>> interface.alsoProvides(foo, testing.IFoo)
When the event is notified, the method is called with the event as an
argument.
>>> import zope.event
>>> zope.event.notify(foo)
Called <bound method Baz.factory of
<z3c.persistentfactory.testing.Baz object at ...>>
args: (<z3c.persistentfactory.testing.Foo object at ...>,)
kwargs: {}
Instance Method Adapter Factory
===============================
Another example is where an adapter factory needs to look up
persistent state specific to the objects being adapted but where that
state can't be stored on the adapted objects them selves. The
component storing the shared persistent state can register one of it's
instance methods as the adapter factory which will look up the
necessary persistent state on self.
Register the persistent factory wrapped instance method as an adapter
factory.
>>> component.provideAdapter(factory=baz.factory)
The method implements IBar.
>>> tuple(interface.implementedBy(baz.factory))
(<InterfaceClass z3c.persistentfactory.testing.IBar>,)
When the adapter is looked up, the metod is called with the object to
be adapted as an argument.
>>> result = component.getAdapter(foo, testing.IBar)
Called <bound method Baz.factory of
<z3c.persistentfactory.testing.Baz object at ...>>
args: (<z3c.persistentfactory.testing.Foo object at ...>,)
kwargs: {}
>>> result
(<bound method Baz.factory of
<z3c.persistentfactory.testing.Baz object at ...>>,
(<z3c.persistentfactory.testing.Foo object at ...>,), {})
| z3c.persistentfactory | /z3c.persistentfactory-0.3.tar.gz/z3c.persistentfactory-0.3/z3c/persistentfactory/README.txt | README.txt |
__docformat__ = "reStructuredText"
import os
from zope import interface
from zope import schema
from zope.component import zcml
from zope.configuration.exceptions import ConfigurationError
import zope.configuration.fields
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.pagetemplate.interfaces import IPageTemplate
from zope.configuration.fields import GlobalObject
from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
from zope.i18nmessageid import MessageFactory
_ = MessageFactory( 'zope' )
class IPluggableTemplatesDirective( interface.Interface ):
"""Parameters for the template directive."""
for_ = GlobalObject(
title = _( u'View' ),
description = _( u'The view for which the template should be used' ),
required = False,
default=interface.Interface,
)
layer = GlobalObject(
title = _( u'Layer' ),
description = _( u'The layer for which the template should be used' ),
required = False,
default=IDefaultBrowserLayer,
)
class IPluggableTemplate( interface.Interface ):
file = zope.configuration.fields.Path(
title=_( "Content-generating template." ),
description=_( "Refers to a file containing a page template (should "
"end in extension ``.pt`` or ``.html``)." ),
required=False,
)
name = schema.TextLine(
title = _( u'Name' ),
description = _( u"""
The name to be used.
Allows named adapter lookups so multiple templates can be assigned to one view.
""" ),
required = False,
default = u'',
)
contentType = schema.BytesLine(
title = _( u'Content Type' ),
description=_( u'The content type identifies the type of data.' ),
default='text/html',
required=False,
)
layer = GlobalObject(
title = _( u'Layer' ),
description = _( u'The layer for which the template should be used' ),
required = False,
default=IDefaultBrowserLayer,
)
class TemplateFactory( object ):
def __init__( self, filename, contentType ):
self.filename = filename
self.contentType = contentType
def __call__( self, view, request ):
template = ViewPageTemplateFile( self.filename,
content_type=self.contentType )
return template
def templateDirective( _context,
file,
name,
for_=interface.Interface,
layer=IDefaultBrowserLayer,
contentType='text/html', **kwargs
):
# Make sure that the template exists
file = os.path.abspath( str( _context.path( file ) ) )
if not os.path.isfile( file ):
raise ConfigurationError( "No such file", file )
factory = TemplateFactory( file, contentType )
zcml.adapter( _context, ( factory, ), IPageTemplate, ( for_, layer ), name=name )
class PluggableTemplatesDirective( object ):
def __init__( self, _context, for_, layer=IDefaultBrowserLayer ):
self._context = _context
self.for_ = for_
self.layer = layer
def template( self, _context, file, name, contentType='text/html', layer=None, *args, **kw ):
#import pdb; pdb.set_trace()
file = os.path.abspath( str( self._context.path( file ) ) )
if not layer:
layer = self.layer
return templateDirective( self._context, file, name, self.for_, layer, contentType )
def __call__( self ):
pass | z3c.pluggabletemplates | /z3c.pluggabletemplates-0.2.tar.gz/z3c.pluggabletemplates-0.2/src/z3c/pluggabletemplates/zcml.py | zcml.py |
===================
Pluggable Templates
===================
This package does two things. First, it does everything z3c.viewtemplate does
-- seperate the view code layer from the template skin layer. Second, it
allows an unlimited number of templates to be plugged into any view class.
What's this for?
~~~~~~~~~~~~~~~~
Making masterpages simple is hard work. Using macros is fairly complicated for
designers to deal with. In fact they don't. Using z3c.viewtemplate with viewlets
is fairly complicated for programmers to deal with. In fact I don't. So this
is another evolutionary step to allow designers and programmersto work together
without necessarily knowing or even liking each other.
This work relies heavily on the working code done by Jurgen for z3c.viewtemplate.
A simple masterpage implementation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is a simple masterpage implementation without using pluggabletemplates.
browser.py::
class MyView(object):
masterpage = ViewTemplateFile('templates/masterpage.pt')
subpage = ViewTemplateFile('templates/content.pt')
authors = ['Roger Zelazny', 'Isaac Asimov', 'Robert Heinlien', 'J.R.R Tolkein']
def __call__(self):
return masterpage()
templates/masterpage.pt::
<html>...
<body>
<h2>My Master Page</h2>
<span tal:replace="view/subpage" />
</body>
</html>
templates/index.pt::
<ul>
<li tal:repeat="author view/authors" tal:content="author" />
</ul>
This is a very easy to follow pattern which can be extended fairly easily. This
pattern runs into immediate problems when you want to change skins. Changing skins
should be as easy as ++skin++design1 ... +++skin++design2, but to do so, all of the
view code needs to be duplicated. Which can be done, but as soon as one piece of view
code is changed, all the other view code has to be patched and easily falls out of
sync.
Enter viewplugs
~~~~~~~~~~~~~~~
design1/configure.zcml::
<browser:pluggableTemplates
for="myapp.browser.MyView"
layer=".skins.Design1"
>
<template
name="master"
file="templates/masterpage.pt"
/>
<template
name="subtemplate"
file="templates/subtemplate.pt
/>
</browser:pluggableTemplates>
So does this mean we'll need to duplicate all of this configuration for
++skin++design2?? Not necessarily::
class Design2(Design1):
""" Skin marker """
Now you can use ++skin++design1 one as your base and simply override
the views or templates you need to change et. al. stylesheets and
images.
By plugging templates into view code, each template can display each of the
other templates::
<span tal:replace="view/template1" />
<span tal:replace="view/template2" />
And of course all view attributes are available::
<span tal:replace="view/myattr1" />
You can add as many views as you like, though, too many, and it could get recomplicated.
Doctests
~~~~~~~~
Before we can setup a view component using this new method, we have to first
create a master template and subtemplate ...
>>> import os, tempfile
>>> temp_dir = tempfile.mkdtemp()
>>> master = os.path.join(temp_dir, 'master.pt')
>>> open(master, 'w').write('''<h2>Masterpage</h2><span tal:replace="view/subtemplate"/>''')
>>> subtemplate = os.path.join(temp_dir, 'subtemplate.pt')
>>> open(subtemplate, 'w').write('''This is the subtemplate: <span tal:replace="view/taste" />''')
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> from zope import interface
>>> from z3c.pluggabletemplates.baseview import MasterView
>>> from z3c.pluggabletemplates.pagetemplate import RegisteredPageTemplate
>>> class IMyView(interface.Interface):
... pass
>>> class MyView(MasterView):
... interface.implements(IMyView)
... master = RegisteredPageTemplate( 'master' )
... taste = 'success'
... subtemplate = RegisteredPageTemplate( 'subtemplate' )
>>> view = MyView(root, request)
Since the template is not yet registered, rendering the view will fail::
>>> print view()
Traceback (most recent call last):
...
ComponentLookupError: ......
Let's now register the template (commonly done using ZCML)::
>>> from zope import component
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from z3c.pluggabletemplates.zcml import TemplateFactory
>>> from zope.pagetemplate.interfaces import IPageTemplate
The template factory allows us to create a ViewPageTemplateFile instance::
>>> factory = TemplateFactory(master, 'text/html')
We register the factory on a view interface and a layer::
>>> component.provideAdapter(factory,
... (interface.Interface, IDefaultBrowserLayer),
... IPageTemplate, name="master")
>>> mastertemplate = component.getMultiAdapter(
... (view, request), IPageTemplate, name="master" )
>>> mastertemplate
<zope.app.pagetemplate.viewpagetemplatefile.ViewPageTemplateFile ...>
>>> factory = TemplateFactory(subtemplate, 'text/html')
We register the factory on a view interface and a layer::
>>> component.provideAdapter(factory,
... (interface.Interface, IDefaultBrowserLayer),
... IPageTemplate, name="subtemplate")
>>> subtemplate = component.getMultiAdapter(
... (view, request), IPageTemplate, name="subtemplate" )
>>> subtemplate
<zope.app.pagetemplate.viewpagetemplatefile.ViewPageTemplateFile ...>
Now that we have a registered template for the default layer we can call our
view again::
>>> print view()
<h2>Masterpage</h2>This is the subtemplate: success
<BLANKLINE>
Cleanup
>>> import shutil
>>> shutil.rmtree(temp_dir)
| z3c.pluggabletemplates | /z3c.pluggabletemplates-0.2.tar.gz/z3c.pluggabletemplates-0.2/src/z3c/pluggabletemplates/README.txt | README.txt |
Overview
========
``z3c.preference`` renders forms in the browser for the preference
sets which were defined using zope.preference_.
.. _zope.preference: http://pypi.python.org/pypi/zope.preference
Using z3c.preference
====================
There are some preconditions to use `z3c.preference`:
* The views for the ``++preferences++`` namespace are registered for
the layer ``z3c.preference.interfaces.IPreferenceLayer``. So you
have to add this interface to the browser layer of your application.
* Only users having the permission ``z3c.preference.EditPreference``
are allowed to access the the preference views. So you have to add this
permission to the users resp. roles which should be able to access
the preferences views.
Editing preferences
===================
Set up for tests
----------------
At first we have to define a preference interface:
>>> import zope.interface
>>> import zope.schema
>>> class IBackEndSettings(zope.interface.Interface):
... """Backend 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 back end.",
... values=['Hipp', 'Lame', 'Basic'],
... default='Basic')
...
... showLogo = zope.schema.Bool(
... title=u"Show Logo",
... description=u"Specifies whether the logo should be displayed.",
... default=True)
The interface must be registered for preferences:
>>> from zope.configuration import xmlconfig
>>> import zope.preference
>>> context = xmlconfig.file('meta.zcml', zope.preference)
>>> context = xmlconfig.string('''
... <configure
... xmlns="http://namespaces.zope.org/zope"
... i18n_domain="test">
...
... <preferenceGroup
... id="BackEndSettings"
... title="Back End Settings"
... schema="z3c.preference.README.IBackEndSettings"
... />
...
... </configure>''', context)
To access the forms a browser is needed, the user must be authorized as
the preferences are stored in the principal annotations:
>>> from zope.testbrowser.wsgi import Browser
>>> browser = Browser()
>>> browser.addHeader('Authorization', 'Basic mgr:mgrpw')
Editing preferences using browser
---------------------------------
There is a namespace to access the preferences. On the page a form is
displayed which shows the default values:
>>> browser.open('http://localhost/++preferences++/BackEndSettings')
>>> browser.getControl('E-mail Address').value
''
>>> browser.getControl('Skin').displayValue
['Basic']
>>> browser.getControl('yes').selected
True
>>> browser.getControl('no').selected
False
The values can be changed and submitting the form makes them persistent:
>>> browser.getControl('E-mail Address').value = '[email protected]'
>>> browser.getControl('Skin').displayValue = ['Hipp']
>>> browser.getControl('no').click()
>>> browser.getControl('Apply').click()
After submitting the form gets displayed again and shows the changed values:
>>> 'Data successfully updated.' in browser.contents
True
>>> browser.getControl('E-mail Address').value
'[email protected]'
>>> browser.getControl('Skin').displayValue
['Hipp']
>>> browser.getControl('no').selected
True
| z3c.preference | /z3c.preference-2.0-py3-none-any.whl/z3c/preference/README.rst | README.rst |
Editing preference group trees
==============================
`zope.preference` has the concept of `preference group trees`_ and
`preference categories` to group preferences.
.. _`preference group trees`: http://pypi.python.org/pypi/zope.preference#preference-group-trees
If a `preference category` is displayed using `z3c.preference` automatically
all `preference groups` belonging to the category are rendered as groups in the
edit form (aka ``GroupForm``).
**Note:** Currently only the preference category and its *direct* children
are rendered in the tree.
Set up
------
At first we have to define some preference interfaces presenting the tree. In
this example we think of a web application with some areas:
>>> import zope.interface
>>> import zope.schema
>>> class IGeneralSettings(zope.interface.Interface):
... """General preferences"""
...
... language = zope.schema.Choice(
... title=u"Language",
... description=u"The language which should be used for display.",
... values=['German', 'English', 'Russian'],
... default='German')
>>> class IRSSSettings(zope.interface.Interface):
... """Preferences for the RSS area of the application."""
...
... number = zope.schema.Int(
... title=u"Item count",
... description=u"Maximum number of items in each feed.")
>>> class ISearchSettings(zope.interface.Interface):
... """Preferences for the search area of the application."""
...
... store_searches = zope.schema.Bool(
... title=u"Store searches?",
... description=u"Should searches be kept for later use?",
... default=True)
The interfaces must be registered for preferences:
>>> from zope.configuration import xmlconfig
>>> import zope.preference
>>> context = xmlconfig.file('meta.zcml', zope.preference)
>>> context = xmlconfig.string('''
... <configure
... xmlns="http://namespaces.zope.org/zope"
... i18n_domain="test">
...
... <preferenceGroup
... id="app"
... title="General Settings"
... description="Settings for the whole app"
... schema="z3c.preference.categories.IGeneralSettings"
... category="true"
... />
...
... <preferenceGroup
... id="app.search"
... title="Search Settings"
... schema="z3c.preference.categories.ISearchSettings"
... category="false"
... />
...
... <preferenceGroup
... id="app.rss"
... title="RSS Settings"
... description="Settings for the RSS feeds"
... schema="z3c.preference.categories.IRSSSettings"
... category="false"
... />
...
... </configure>''', context)
To access the forms a browser is needed, the user must be authorized as
the preferences are stored in the principal annotations:
>>> from zope.testbrowser.wsgi import Browser
>>> browser = Browser()
>>> browser.addHeader('Authorization', 'Basic mgr:mgrpw')
The form displays the titles and descriptions of the categories:
>>> browser.open('http://localhost/++preferences++/app')
>>> print(browser.contents)
<!DOCTYPE ...
...General Settings...
...Settings for the whole app...
...RSS Settings...
...Settings for the RSS feeds...
...Search Settings...
Editing preference group trees using browser
--------------------------------------------
There is a namespace to access the preferences. On the page a form is
displayed which shows the default values:
>>> browser.open('http://localhost/++preferences++/app')
>>> browser.getControl('Language').displayValue
['German']
>>> browser.getControl('Item count').value
''
>>> browser.getControl('yes').selected
True
>>> browser.getControl('no').selected
False
The values can be changed and submitting the form makes them persistent:
>>> browser.getControl('Language').displayValue = ['English']
>>> browser.getControl('Item count').value = '20'
>>> browser.getControl('no').click()
>>> browser.getControl('Apply').click()
After submitting the form gets displayed again and shows the changed values:
>>> 'Data successfully updated.' in browser.contents
True
>>> browser.getControl('Language').displayValue
['English']
>>> browser.getControl('Item count').value
'20'
>>> browser.getControl('no').selected
True
| z3c.preference | /z3c.preference-2.0-py3-none-any.whl/z3c/preference/categories.rst | categories.rst |
==================
Web-based Profiler
==================
This package offers a profiler including a skin. This profiler allows
you to profile views on a existing Zope3 application.
Let's access the profiler start page:
>>> from z3c.etestbrowser.testing import ExtendedTestBrowser
>>> user = ExtendedTestBrowser()
>>> user.addHeader('Accept-Language', 'en')
>>> user.open('http://localhost/++skin++Profiler')
If you access the profiler, you can push the start button:
>>> user.getControl('Start').click()
>>> 'Show Profile' in user.contents
True
Now we can go to the ``help.html`` page which gets profiled. Let's use
another browser for this.
>>> newBrowser = ExtendedTestBrowser()
>>> newBrowser.open('http://localhost/++skin++Profiler/help.html')
>>> newBrowser.url
'http://localhost/++skin++Profiler/help.html'
After calling the ``help.html`` page, we can go to the ``doProfile``
page and show the profile by clicking on the ``Show Profile`` button:
>>> user.getControl('Show Profile').click()
If we whould not call this form within this test, we whould see the
profile data table. But we do not see the profile data table. Probably
the testrunner conflicts with the monkey call.
>>> print user.contents
<!DOCTYPE ...
<div>
No data available.
</div>
... | z3c.profiler | /z3c.profiler-0.10.0.tar.gz/z3c.profiler-0.10.0/src/z3c/profiler/README.txt | README.txt |
__docformat__ = "reStructuredText"
import sys
from cStringIO import StringIO
from zope.traversing.browser import absoluteURL
from z3c.pagelet import browser
from z3c.profiler.wsgi import getStats
from z3c.profiler.wsgi import listStats
from z3c.profiler.wsgi import installProfiler
from z3c.profiler.wsgi import uninstallProfiler
class ProfilerPagelet(browser.BrowserPagelet):
"""Profiler page.
It whould be so easy with z3c.form, but I decided to depend on
less packages as possible and not using z3c.form and other packages.
Forgive me the z3c.pagelet usage but it's so nice to do layout things
without METAL macros ;-)
Note: I didn't internationalize the profiler, should we?
The stats output is horrible for formatting in html, but let's try to
support a nice table instead of the ugly print out whihc needs a
monitor with at least 3000px width.
"""
doProfile = False
_statsData = {}
_callersData = {}
_callesData = {}
_printOutput = None
@property
def action(self):
try:
return '%s/doProfile' % absoluteURL(self.context, self.request)
except TypeError, e:
return './doProfile'
@property
def profilerButton(self):
if self.doProfile:
return {'name':'profiler.uninstall', 'value': 'Stop'}
else:
return {'name':'profiler.install', 'value': 'Start'}
@property
def showProfileButton(self):
if self.doProfile:
return True
else:
return False
@property
def statsData(self):
return self._statsData
@property
def callesData(self):
return self._callersData
@property
def callersData(self):
return self._callesData
@property
def printOutput(self):
return self._printOutput
def listStats(self):
return listStats()
def process(self):
aborted = False
stats = getStats()
if not stats:
return ''
uri = self.request.get('stats', None)
info = stats.get(uri)
if not info:
info = stats.items()[0][1]
stats = info[0]
output = StringIO()
stripdirs = self.request.get('stripdirs', False)
if stripdirs:
stats.strip_dirs()
sorton = self.request.get('sorton', 'time')
stats.sort_stats(sorton)
mode = self.request.get('mode', 'stats')
limit = int(self.request.get('limit', 500))
stats_stream = stats.stream
stats.stream = output
try:
getattr(stats, 'print_%s'%mode)(limit)
finally:
stats.stream = stats_stream
output.seek(0)
data = output
info = {}
rows = []
info['rows'] = rows
info['summary'] = []
info['errors'] = []
append = rows.append
lines = data.readlines()
if mode == 'stats':
for i, line in enumerate(lines):
print line,
try:
ncalls, tottime, totpercall, cumtime, percall, fn = line.split()
d = {}
d['ncalls'] = ncalls
d['tottime'] = tottime
d['totpercall'] = totpercall
d['cumtime'] = cumtime
d['percall'] = percall
d['fn'] = fn
if ncalls == 'ncalls':
d['thead'] = True
else:
d['thead'] = False
append(d)
except ValueError, e:
if i < 4:
info['summary'].append(line)
else:
# skip lines at the end and parser errors
info['errors'].append(line)
except Exception, e:
aborted = True
self._statsData = info
else:
for i, line in enumerate(lines):
try:
d = {}
print line,
if ('...' in line or
'Ordered by:' in line):
# skip header line
continue
varius = line.split()
if len(varius) == 0:
continue
if len(varius) == 1:
d['fn'] = ''
d['caller'] = varius[0]
d['time'] = ''
elif len(varius) == 2:
if varius[1] in ['->', '<-']:
d['fn'] = varius[0]
d['caller'] = ''
d['time'] = ''
else:
d['fn'] = ''
d['caller'] = varius[0]
d['time'] = varius[1]
elif len(varius) == 3:
d['fn'] = varius[0]
d['caller'] = varius[1]
d['time'] = varius[2]
elif len(varius) == 4:
d['fn'] = varius[0]
d['caller'] = varius[2]
d['time'] = varius[3]
elif len(varius) > 4:
continue
append(d)
except ValueError, e:
if i < 4:
if not 'Function' in line:
# append to summary, but skip header
info['summary'].append(line)
else:
# skip lines at the end and parser errors
info['errors'].append(line)
except Exception, e:
print ""
print e
aborted = True
if mode == 'callers':
self._callersData = info
if mode == 'callees':
self._callesData = info
if aborted:
self._statsData = {}
self._callersData = {}
self._callesData = {}
output.seek(0)
self._printOutput = output.getvalue()
def update(self):
self.process()
calls = int(self.request.get('calls', 2))
if 'profiler.install' in self.request:
installProfiler(calls)
self.doProfile = True
elif 'profiler.uninstall' in self.request:
uninstallProfiler(calls)
self.doProfile = False | z3c.profiler | /z3c.profiler-0.10.0.tar.gz/z3c.profiler-0.10.0/src/z3c/profiler/browser/profiler.py | profiler.py |
=========
z3c.proxy
=========
We can proxy a regular container derived from zope's btree container for
example:
>>> from zope.container.interfaces import IContainer
>>> from zope.container.btree import BTreeContainer
>>> container = BTreeContainer()
>>> container.__name__, container.__parent__ = u'c1', u'p1'
>>> from z3c.proxy import interfaces
>>> from z3c.proxy.container import LocationProxy
>>> from z3c.proxy.container import ContainerLocationProxy
>>> proxy = ContainerLocationProxy(container)
The name and the parent of the proxy is None. The proxy provides
IContainer:
>>> proxy.__name__ is None
True
>>> proxy.__parent__ is None
True
>>> IContainer.providedBy(proxy)
True
>>> interfaces.IContainerLocationProxy.providedBy(proxy)
True
First we check the empty proxy:
>>> proxy['x']
Traceback (most recent call last):
...
KeyError: 'x'
>>> 'x' in proxy
False
>>> proxy.has_key('x')
0
>>> [key for key in proxy.keys()]
[]
>>> [item for item in proxy.items()]
[]
>>> proxy.get('x') is None
True
>>> iterator = iter(proxy)
>>> iterator.next()
Traceback (most recent call last):
...
StopIteration
>>> proxy.values()
[]
>>> len(proxy)
0
>>> del proxy['x']
Traceback (most recent call last):
...
KeyError: 'x'
>>> from zope.container.contained import Contained
>>> proxy['x'] = x = Contained()
Now we added our first item. This item should be added to the container.
Its name will be x and its parent is the container itself:
>>> x is container['x']
True
>>> x.__name__
u'x'
>>> x.__parent__ is container
True
If we lookup 'x' within the proxy we do not get the blank 'x' but rather
the proxied 'x'. The proxy is not 'x' but only equal to 'x':
>>> x is proxy['x']
False
>>> x == proxy['x']
True
>>> x1 = proxy['x']
>>> from zope.proxy import isProxy
>>> isProxy(x1)
True
>>> isinstance(x1, LocationProxy)
True
The proxied 'x' has still the same name but not the same parent:
>>> x1.__name__
u'x'
>>> x1.__parent__ is container
False
>>> x1.__parent__ is proxy
True
If we add a second item to the container, it should appear in the
proxy, too. But this item is proxied as container location proxy:
>>> container['y'] = y = BTreeContainer()
>>> y1 = proxy['y']
>>> y1 is y
False
>>> y1 == y
True
>>> isinstance(y1, ContainerLocationProxy)
True
The container location proxy is able to proxy the location of
nested objects:
>>> proxy['y']['z'] = z = Contained()
>>> container['y']['z'] is z
True
>>> z1 = y1['z']
>>> z1 is z
False
>>> z1 == z
True
>>> isinstance(z1, LocationProxy)
True
>>> z1.__parent__ is y1
True
Finaly we check all other methods of the proxy:
>>> 'x' in proxy
True
>>> proxy.has_key('x')
1
>>> keys = [key for key in proxy.keys()]; keys.sort(); keys
[u'x', u'y']
>>> items = [item for item in proxy.items()]; items.sort()
>>> items == [(u'x', x), (u'y', y)]
True
>>> proxy.get('x') == x
True
>>> iterator = iter(proxy)
>>> iterator.next() in proxy
True
>>> iterator.next() in proxy
True
>>> iterator.next()
Traceback (most recent call last):
...
StopIteration
>>> values = proxy.values(); values.sort();
>>> x in values, y in values
(True, True)
>>> len(proxy)
2
>>> del proxy['x']
>>> 'x' in proxy
False
ObjectMover
-----------
To use an object mover, pass a contained ``object`` to the class. The
contained ``object`` should implement ``IContained``. It should be contained
in a container that has an adapter to ``INameChooser``.
Setup test container and proxies:
>>> from zope.interface import implements
>>> from zope.container.interfaces import INameChooser
>>> from zope.copypastemove import ExampleContainer
>>> from z3c.proxy.container import ProxyAwareObjectMover
>>> class ContainerLocationProxyStub(ContainerLocationProxy):
...
... implements(INameChooser)
...
... def chooseName(self, name, ob):
... while name in self:
... name += '_'
... return name
>>> container = ExampleContainer()
>>> container2 = ExampleContainer()
>>> ob = Contained()
>>> proxy = ContainerLocationProxyStub(container)
>>> proxy[u'foo'] = ob
>>> ob = proxy[u'foo']
>>> mover = ProxyAwareObjectMover(ob)
In addition to moving objects, object movers can tell you if the object is
movable:
>>> mover.moveable()
1
which, at least for now, they always are. A better question to ask is whether
we can move to a particular container. Right now, we can always move to a
container of the same class:
>>> proxy2 = ContainerLocationProxyStub(container2)
>>> mover.moveableTo(proxy2)
1
>>> mover.moveableTo({})
Traceback (most recent call last):
...
TypeError: Container is not a valid Zope container.
Of course, once we've decided we can move an object, we can use the mover to
do so:
>>> mover.moveTo(proxy2)
u'foo'
>>> list(proxy)
[]
>>> list(proxy2)
[u'foo']
>>> ob = proxy2[u'foo']
>>> ob.__parent__ is proxy2
True
We can also specify a name:
>>> mover.moveTo(proxy2, u'bar')
u'bar'
>>> list(proxy2)
[u'bar']
>>> ob = proxy2[u'bar']
>>> ob.__parent__ is proxy2
True
>>> ob.__name__
u'bar'
But we may not use the same name given, if the name is already in use:
>>> proxy2[u'splat'] = 1
>>> mover.moveTo(proxy2, u'splat')
u'splat_'
>>> l = list(proxy2)
>>> l.sort()
>>> l
[u'splat', u'splat_']
>>> ob = proxy2[u'splat_']
>>> ob.__name__
u'splat_'
If we try to move to an invalid container, we'll get an error:
>>> mover.moveTo({})
Traceback (most recent call last):
...
TypeError: Container is not a valid Zope container.
ObjectCopier
------------
To use an object copier, pass a contained ``object`` to the class. The
contained ``object`` should implement ``IContained``. It should be contained
in a container that has an adapter to `INameChooser`.
Setup test container and proxies:
>>> from z3c.proxy.container import ProxyAwareObjectCopier
>>> class ContainerLocationProxyStub(ContainerLocationProxy):
...
... implements(INameChooser)
...
... def chooseName(self, name, ob):
... while name in self:
... name += '_'
... return name
>>> container = ExampleContainer()
>>> container2 = ExampleContainer()
>>> proxy = ContainerLocationProxyStub(container)
>>> proxy[u'foo'] = ob = Contained()
>>> ob = proxy[u'foo']
>>> copier = ProxyAwareObjectCopier(ob)
In addition to moving objects, object copiers can tell you if the object is
movable:
>>> copier.copyable()
1
which, at least for now, they always are. A better question to ask is whether
we can copy to a particular container. Right now, we can always copy to a
container of the same class:
>>> proxy2 = ContainerLocationProxyStub(container2)
>>> copier.copyableTo(proxy2)
1
>>> copier.copyableTo({})
Traceback (most recent call last):
...
TypeError: Container is not a valid Zope container.
Of course, once we've decided we can copy an object, we can use the copier to
do so:
>>> copier.copyTo(proxy2)
u'foo'
>>> list(proxy)
[u'foo']
>>> list(proxy2)
[u'foo']
>>> ob.__parent__ is proxy
1
>>> proxy2[u'foo'] is ob
0
>>> proxy2[u'foo'].__parent__ is proxy2
1
>>> proxy2[u'foo'].__name__
u'foo'
We can also specify a name:
>>> copier.copyTo(proxy2, u'bar')
u'bar'
>>> l = list(proxy2)
>>> l.sort()
>>> l
[u'bar', u'foo']
>>> ob.__parent__ is proxy
1
>>> proxy2[u'bar'] is ob
0
>>> proxy2[u'bar'].__parent__ is proxy2
1
>>> proxy2[u'bar'].__name__
u'bar'
But we may not use the same name given, if the name is already in use:
>>> copier.copyTo(proxy2, u'bar')
u'bar_'
>>> l = list(proxy2)
>>> l.sort()
>>> l
[u'bar', u'bar_', u'foo']
>>> proxy2[u'bar_'].__name__
u'bar_'
If we try to copy to an invalid container, we'll get an error:
>>> copier.copyTo({})
Traceback (most recent call last):
...
TypeError: Container is not a valid Zope container.
ProxyAwareContainerItemRenamer
------------------------------
This adapter uses IObjectMover to move an item within the same container to
a different name. We need to first setup an adapter for IObjectMover:
Setup test container and proxies:
>>> from zope.container.sample import SampleContainer
>>> from zope.copypastemove import ContainerItemRenamer
>>> from zope.copypastemove import IObjectMover
>>> from z3c.proxy.container import ProxyAwareContainerItemRenamer
>>> import zope.component
>>> from zope.container.interfaces import IContained
>>> zope.component.provideAdapter(ProxyAwareObjectMover, [IContained],
... IObjectMover)
>>> class ContainerLocationProxyStub(ContainerLocationProxy):
...
... implements(INameChooser)
...
... def chooseName(self, name, ob):
... while name in self:
... name += '_'
... return name
To rename an item in a container, instantiate a ContainerItemRenamer with the
container:
>>> container = SampleContainer()
>>> proxy = ContainerLocationProxyStub(container)
>>> renamer = ProxyAwareContainerItemRenamer(container)
For this example, we'll rename an item 'foo':
>>> from z3c.proxy.container import _unproxy
>>> foo = Contained()
>>> proxy['foo'] = foo
>>> proxy['foo'] == _unproxy(foo)
True
to 'bar':
>>> renamer.renameItem('foo', 'bar')
>>> proxy['foo'] is foo
Traceback (most recent call last):
KeyError: 'foo'
>>> proxy['bar'] == _unproxy(foo)
True
If the item being renamed isn't in the container, a NotFoundError is raised:
>>> renamer.renameItem('foo', 'bar') # doctest:+ELLIPSIS
Traceback (most recent call last):
ItemNotFoundError: (<...SampleContainer...>, 'foo')
If the new item name already exists, a DuplicationError is raised:
>>> renamer.renameItem('bar', 'bar')
Traceback (most recent call last):
DuplicationError: bar is already in use
| z3c.proxy | /z3c.proxy-0.6.1.tar.gz/z3c.proxy-0.6.1/src/z3c/proxy/README.txt | README.txt |
__docformat__ = 'restructuredtext'
from zope.interface import implements
from zope.copypastemove import ObjectCopier
from zope.copypastemove import ObjectMover
from zope.copypastemove import ContainerItemRenamer
from zope.location import LocationProxy
from zope.proxy import getProxiedObject
from zope.proxy import non_overridable
from zope.proxy import isProxy
from zope.container.interfaces import IContainer
from z3c.proxy import interfaces
def proxify(container, item):
if IContainer.providedBy(item):
proxy = ContainerLocationProxy(item)
else:
proxy = LocationProxy(item)
proxy.__name__ = item.__name__
proxy.__parent__ = container
return proxy
def _unproxy(obj):
# precondition: treate only proxied objects
if not isProxy(obj):
return obj
# essential
return getProxiedObject(obj)
class ContainerLocationProxy(LocationProxy):
"""Proxy the location of a container an its items."""
implements(interfaces.IContainerLocationProxy)
# zope.app.conatiner.interfaces.IReadContainer
@non_overridable
def __getitem__(self, key):
return proxify(self, getProxiedObject(self).__getitem__(key))
@non_overridable
def __contains__(self, key):
return getProxiedObject(self).__contains__(key)
@non_overridable
def has_key(self, key):
return getProxiedObject(self).has_key(key)
@non_overridable
def keys(self):
return getProxiedObject(self).keys()
@non_overridable
def items(self):
return [(key, proxify(self, item)) for key, item in getProxiedObject(self).items()]
@non_overridable
def get(self, key, default=None):
item = getProxiedObject(self).get(key, default)
if item is not default:
return proxify(self, item)
else:
return default
@non_overridable
def __iter__(self):
return iter(getProxiedObject(self))
@non_overridable
def values(self):
return [proxify(self, value) for value in getProxiedObject(self).values()]
@non_overridable
def __len__(self):
return getProxiedObject(self).__len__()
# zope.app.conatiner.interfaces.IWriteContainer
@non_overridable
def __delitem__(self, key):
getProxiedObject(self).__delitem__(key)
@non_overridable
def __setitem__(self, key, value):
getProxiedObject(self).__setitem__(key, value)
class ProxyAwareObjectMover(ObjectMover):
"""Adapter for moving objects between containers that removes proxies."""
def __init__(self, object):
super(ProxyAwareObjectMover, self).__init__(_unproxy(object))
class ProxyAwareObjectCopier(ObjectCopier):
"""Adapter for copying objects between containers that removes proxies."""
def __init__(self, object):
super(ProxyAwareObjectCopier, self).__init__(_unproxy(object))
class ProxyAwareContainerItemRenamer(ContainerItemRenamer):
"""An IContainerItemRenamer adapter for containers."""
def __init__(self, container):
super(ProxyAwareContainerItemRenamer, self).__init__(
_unproxy(container)) | z3c.proxy | /z3c.proxy-0.6.1.tar.gz/z3c.proxy-0.6.1/src/z3c/proxy/container.py | container.py |
Overview
========
This package implements a compatibility-layer between the following
Zope Page Template engines:
* z3c.pt
* zope.pagetemplate
Usage
-----
Use the following import-clause:
>>> from z3c.pt.compat import ViewPageTemplateFile
If the environment-variable ``PREFER_Z3C_PT`` is set to a true value,
the ``z3c.pt`` engine will be used instead of ``zope.pagetemplate``.
Binding methods
---------------
Two methods are available to bind templates and template macros to a
view:
>>> from z3c.pt.compat import bind_template
>>> from z3c.pt.compat import bind_macro
Both function return render-methods that accept keyword arguments
which will be passed to the template.
>>> render = bind_template(template, view)
>>> render = bind_macro(template, view, request, macro)
| z3c.pt.compat | /z3c.pt.compat-0.3.tar.gz/z3c.pt.compat-0.3/README.txt | README.txt |
===========
Changelog
===========
4.0 (2023-03-27)
================
- Add support for Python 3.11.
- Drop support for Python 2.7, 3.5, 3.6.
3.3.1 (2021-12-17)
==================
- Add support for Python 3.9, and 3.10.
3.3.0 (2020-03-31)
==================
- Drop support for Python 3.4
- Add support for Python 3.8.
- Prevent interpolation (i.e. ``$``*var*, ``${``*path*``}`` replacements)
inside comments
(`Zope #716 <https://github.com/zopefoundation/Zope/issues/716>`_).
3.2.0 (2019-01-05)
==================
- Add support for Python 3.7.
- Drop support for running the tests using `python setup.py test`.
3.1.0 (2017-10-17)
==================
- Add support for Python 3.6.
- Drop support for Python 3.3.
- Use the adapter namespace from ``zope.pagetemplate`` if it's
available, instead of the backwards compatibility shim in
``zope.app.pagetemplate``. See `issue 3
<https://github.com/zopefoundation/z3c.pt/issues/3>`_.
- Add the ``string`` and ``nocall`` functions for use inside Python
expressions. See `issue 2
<https://github.com/zopefoundation/z3c.pt/issues/2>`_.
- Make bound page templates have ``__self__`` and ``__func__``
attributes to be more like Python 3 bound methods. (``im_func`` and
``im_self`` remain available.) See `issue 9
<https://github.com/zopefoundation/z3c.pt/issues/9>`_.
3.0 (2016-09-02)
================
- Added support for Python 3.4, 3.5, PyPy and PyPy3.
- Dropped support for Python 2.6.
3.0.0a1 (2013-02-25)
====================
Compatibility:
- Added support for Python 3.3.
- Added a small patch to ``chameleon.i18n`` to define ``basestring``.
Bugfixes:
- Allow segments of path expressions to start with a digit.
2.2.3 (2012-06-01)
==================
Compatibility:
- The translation function now accepts (but ignores) a ``context``
argument. This fixes a compatibility issue with Chameleon 2.9.x.
2.2.2 (2012-04-24)
==================
Bugfixes:
- Do not rely on the "LANGUAGE" request key to skip language
negotiation. Instead, we assume that negotiation is cheap (and
probably cached).
2.2.1 (2012-02-15)
==================
- Only require Chameleon >= 2.4, was needlessly bumped in last release.
- Add test extra, remove versions from buildout.cfg.
2.2 (2012-01-08)
================
Features:
- Whitespace between attributes is now reduced to a single whitespace
character.
- The ``request`` symbol is no longer required to evaluate a path
expression; it now defaults to ``None`` if not present in the
namespace.
Bugfixes:
- The content provider expression now correctly applies TAL namespace
data.
Changes:
- The ``ZopeTraverser`` class has been removed and replaced with a
simple function.
2.1.5 (2011-11-24)
==================
- Use non-strict mode if available for compatibility with the
reference engine where expressions are only compiled at evaluation
time.
2.1.4 (2011-09-14)
==================
- The provider expression is now first evaluated as a string
expression, the result of which is used as the content provider
name.
This fixes an issue where (provider-) string expressions would not
get evaluated correctly, e.g. ``provider: ${mgr}``.
2.1.3 (2011-08-22)
==================
- Configure HTML boolean attributes (in HTML-mode only)::
"compact", "nowrap", "ismap", "declare", "noshade",
"checked", "disabled", "readonly", "multiple", "selected",
"noresize", "defer"
2.1.2 (2011-08-19)
==================
- Enable option ``literal_false`` to get the behavior that a value of
``False`` does not drop an attribute.
2.1.1 (2011-08-11)
==================
- Make sure the builtin names 'path' and 'exists' can be redefined.
- Guard ``sys.modules`` (mapped to the builtin variable "modules")
against import-time side effects using ``ProxyFactory``.
2.1 (2011-07-28)
================
- Use dynamic expression evaluation framework that comes included with
Chameleon.
2.0 (2011-07-14)
================
- Point release.
- Move implementation-specific context setup to ``render``
method. This allows use of template class with an already prepared
context.
- Fixed issue with the call flag on the Zope traverser compiler.
2.0-rc3 (2011-07-11)
====================
- Python-expressions are no longer TALES-expressions; previously, the
pipe operator would split Python expression clauses, allowing
fallbacks even for Python expressions, but this is not the standard
behavior of ZPT.
- Fixed an issue where an error which occurred inside a dynamic
``path`` or ``exists`` evaluation would fail to propagate due to a
missing remote context.
- Set variables ``here`` and ``context`` to the bound instance value
on ``PageTemplate`` instances.
2.0-rc2 (2011-03-24)
====================
- Fixed an issue with ``"exists:"`` expression where a callable would
be attempted called. It is meanwhile implied with this expression
types that it should use the ``"nocall:"`` pragma.
2.0-rc1 (2011-02-28)
====================
- Update to Chameleon 2.0.
This release includes many changes and is a complete rewrite of the
1.x series.
Platform:
* Python 2.5+ now required.
Notable changes:
* Expression interpolation is always enabled.
* Whitespace output is different, now closely aligned to the
template input.
* New language constructs:
1) tal:on-error
2) tal:switch
3) tal:case
Incompatibilities:
* The expression translation interface has been replaced with an
expression engine. This means that all expressions must be
rewritten.
- The exists expression evaluator should ignore KeyError exceptions
as well.
- Special-case handling of Zope2's Missing.MV as used by
Products.ZCatalog for LP#649343.
[rossp]
1.2.1 (2010/05/13)
------------------
- Bind template to the template object in the general case.
1.2 (2010/05/12)
----------------
- Fixed compatibility issue with recent change in Chameleon.
- Fixed regression introduced with ``args`` being passed
in. Incidentally, the name ``args`` was used as the star argument
name.
- Look at language set on request before invoking the zope.i18n
negotiator. This makes i18n work again on Zope2.
1.1.1 (2010/04/06)
------------------
- Fixed issue where arguments were not passed on to template as
``args``.
1.1.0 (2010/01/09)
------------------
- Update to combined Chameleon distribution.
1.0.1 (2009/07/06)
------------------
- Bind translation context (request) to translation method. Although
not required in newer versions of the translation machinery, some
versions will ask for a translation context in order to negotiate
language even when a language is explicitly passed in.
- Declare zope security settings for classes when zope.security is present
as the "class" ZCML directive was moved there.
1.0.0 (2009/07/06)
------------------
- First point release.
1.0b17 (2009/06/14)
-------------------
- Made the Zope security declaration for the repeat dictionary be conditional
on the presence of zope.app.security instead of zope.app.component.
1.0b16 (2009/05/20)
-------------------
- Updated run-time expression evaluator method to work after a recent
architectural change in Chameleon. [malthe]
- Check that we have a non-trivial response-object before trying to
set the content type. [malthe]
- Wrap ``sys.modules`` dictionary in an "opaque" dictionary class,
such that the representation string does not list all loaded
modules. [malthe]
1.0b15 (2009/04/24)
-------------------
- Removed lxml extra, as we do no longer depend on it. [malthe]
- Make sure the path expression is a simple string, not
unicode. [malthe]
- Detect path prefix properly for ViewPageTemplateFile usage in
doctests. [sidnei]
- The ``template`` symbol is already set by the template base
class. [malthe]
- Set Content-Type header, for backwards compatibility with
zope.app.pagetemplate. [sidnei]
1.0b14 (2009/03/31)
-------------------
- Updated language adapter to work with 'structure' meta
attribute. [malthe]
1.0b13 (2009/03/23)
-------------------
- When traversing on dictionaries, only exposes dictionary items
(never attributes); this is to avoid ambiguity. [sidnei, malthe]
- Path expressions need to pass further path items in reverse order to
traversePathElement, because that's what it expects. [sidnei]
1.0b12 (2009/03/09)
-------------------
- Insert initial variable context into dynamic scope. The presence of
these is expected by many application. [malthe]
1.0b11 (2009/03/05)
-------------------
- If a namespace-acquired object provides ``ITraversable``, use path
traversal. [malthe]
- Implemented TALES function namespaces. [sidnei, malthe]
- Catch ``NameError`` in exists-traverser (return false). [malthe]
- Catch ``NameError`` in exists-evaluator (return false). [malthe]
- If the supplied ``context`` and ``request`` parameters are trivial,
get them from the view instance. [malthe]
- Expressions in text templates are never escaped. [malthe]
- Do not bind template to a trivial instance. [malthe]
1.0b10 (2009/02/24)
-------------------
- Fixed exists-traverser such that it always returns a boolean
value. [malthe]
1.0b9 (2009/02/19)
------------------
- When evaluating path-expressions at runtime (e.g. the ``path``
method), run the source through the transform first to support
dynamic scope. [malthe]
1.0b8 (2009/02/17)
------------------
- Allow attribute access to ``__call__`` method on bound page
templates. [malthe]
1.0b7 (2009/02/13)
------------------
- Fixed issue where symbol mapping would not be carried through under
a negation (not). [malthe]
- Optimize simple case: if path expression is a single path and path
is 'nothing' or has 'nocall:', just return value as-is, without
going through path_traverse. [sidnei]
- Moved evaluate_path and evaluate_exists over from ``five.pt``, adds
support for global ``path()`` and ``exists()`` functions for use in
``python:`` expressions (LP #317967).
- Added Zope security declaration for the repeat dictionary (tales
iterator). [malthe]
1.0b6 (2008/12/18)
------------------
- The 'not' pragma acts recursively. [malthe]
1.0b5 (2008/12/15)
------------------
- View templates now support argument-passing for alternative context
and request (for compatibility with
``zope.app.pagetemplate``). [malthe]
- Switched off the $-interpolation feature per default; It may be activated
on a per-template basis using ``meta:interpolation='true'``. [seletz]
- Allow more flexibility in overriding the PathTranslator method. [hannosch]
- Removed the forced defaultencoding from the benchmark suite. [hannosch]
1.0b4 (2008/11/19)
------------------
- Split out content provider function call to allow modification
through subclassing. [malthe]
- Added language negotiation. [malthe]
- Simplified template class inheritance. [malthe]
- Added support for the question-mark operator in path-expressions. [malthe]
- Updated expressions to recent API changes. [malthe]
- Added 'exists' and 'not' translators. [malthe]
Bug fixes
- Adjusted the bigtable benchmark test to API changes. [hannosch]
1.0b3 (2008/11/12)
------------------
- Added ``PageTemplate`` and ``PageTemplateFile`` classes. [malthe]
1.0b2 (2008/11/03)
------------------
Bug fixes
- Allow '.' character in content provider expressions.
- Allow '+' character in path-expressions.
1.0b1 (2008/10/02)
------------------
Package changes
- Split out compiler to "Chameleon" package. [malthe]
Backwards incompatibilities
- Moved contents of ``z3c.pt.macro`` module into
``z3c.pt.template``. [malthe]
- Namespace attribute "xmlns" no longer rendered for templates with no
explicit document type. [malthe]
- Changes to template method signatures. [malthe]
- Engine now expects all strings to be unicode or contain ASCII
characters only, unless an encoding is provided. [malthe]
- The default path traverser no longer proxies objects. [malthe]
- Template output is now always converted to unicode. [malthe]
- The ``ViewPageTemplateFile`` class now uses 'path' as the default
expression type. [malthe]
- The compiler now expects an instantiated parser instance. [malthe]
Features
- Added expression translator "provider:" (which renders a content
provider as defined in the ``zope.contentprovider``
package). [malthe]
- Added template API to render macros. [malthe]
- Optimized template loader so only a single template is instantiated
per file. [malthe]
- Made ``z3c.pt`` a namespace package. [malthe]
- Added reduce and restore operation to the compilation and rendering
flow in the test examples to verify integrity. [malthe]
- The ZPT parser now supports prefixed native attributes,
e.g. <tal:foo tal:bar="" />. [malthe]
- Source-code is now written to disk in debug mode. [malthe]
- Custom validation error is now raised if inserted string does not
validate (when debug mode is enabled). [malthe]
- Added support for omitting rendering of HTML "toggle" attributes
(option's ``selected`` and input's ``checked``) within dynamic
attribute assignment. If the value of the expression in the
assignment evaluates equal to boolean False, the attribute will not
be rendered. If the value of the expression in the assignment
evaluates equal to boolean True, the attribute will be rendered and
the value of the attribute will be the value returned by the
expression. [chrism]
- XML namespace attribute is now always printed for root tag. [malthe]
- Allow standard HTML entities. [malthe]
- Added compiler option to specify an implicit doctype; this is
currently used by the template classes to let the loose XHTML
doctype be the default. [malthe]
- Added support for translation of tag body. [malthe]
- Added security configuration for the TALES iterator (repeat
dictionary). This is made conditional on the availability of the
application security framework. [malthe]
- Dynamic attributes are now ordered as they appear in the
template. [malthe]
- Added ``symbol_mapping`` attribute to code streams such that
function dependencies can be registered at compile-time. [malthe]
- Allow BaseTemplate-derived classes (PageTemplate, PageTemplateFile,
et. al) to accept a ``doctype`` argument, which will override the
doctype supplied by the source of the template if specified. [chrism]
- Language negotiation is left to the page template superclass, so we
don't need to pass in a translation context anymore. [malthe]
- The ``ViewPageTemplateFile`` class now uses the module path of the
calling class to get an absolute path to a relative filename passed
to the constructor. [malthe]
- Added limited support for the XInclude ``include`` directive. The
implemented subset corresponds to the Genshi implementation, except
Match-templates, which are not made available to the calling
template. [malthe]
- Use a global template registry for templates on the
file-system. This makes it inexpensive to have multiple template
class instances pointing to the same file. [malthe]
- Reimplemented the disk cache to correctly restore all template
data. This implementation keeps a cache in a pickled format in a
file next to the original template. [malthe]
- Refactored compilation classes to better separate concerns. [malthe]
- Genshi macros (py:def) are now available globally. [malthe]
- A syntax error is now raised when an interpolation expression is not
exhausted, e.g. only a part of the string is a valid
Python-expression. [malthe]
- System variables are now defined in a configuration class. [malthe]
- Improve performance of codegen by not repeatedly calling
an expensive "flatten" function. [chrism]
- Remove ``safe_render`` implementation detail. It hid information
in tracebacks. [chrism]
- Implemented TAL global defines. [malthe]
- Added support for variables with global scope. [malthe]
- Curly braces may now be omitted in an expression interpolation if
the expression is just a variable name; this complies with the
Genshi syntax. [malthe]
- UTF-8 encode Unicode attribute literals. [chrism]
- Substantially reduced compiler overhead for lxml CDATA
workaround. [malthe]
- Split out element compiler classes for Genshi and Zope language
dialects. [malthe]
- Make lxml a setuptools "extra". To install with lxml support
(currently required by Genshi), specify "z3c.pt [lxml]" in
any references you need to make to the package in buildout or
in setup.py install_requires. [chrism]
- Add test-nolxml and py-nolxml parts to buildout so the package's
tests can be run without lxml. [chrism]
- No longer require default namespace. [malthe]
- Changed source code debug mode files to be named <filename>.py instead of
<filename>.source.
- Generalized ElementTree-import to allow both Python 2.5's
``xml.etree`` module and the standalone ``ElementTree``
package. [malthe]
- Expression results are now validated for XML correctness when the
compiler is running in debug-mode. [malthe]
- Preliminary support for using ``xml.etree`` as fallback for
``lxml.etree``. [malthe]
- String-expressions may now contain semi-colons using a double
semi-colon literal (;;). [malthe]
- Preserve CDATA sections. [malthe]
- Get rid of package-relative magic in constructor of BaseTemplateFile
in favor of just requiring an absolute path or a path relative
to getcwd(). Rationale: it didn't work when called from __main__
when the template was relative to getcwd(), which is the 99% case
for people first trying it out. [chrism]
- Added support for METAL.
[malthe]
- Add a TemplateLoader class to have a convenient method to instantiate
templates. This is similar to the template loaders from other template
toolkits and makes integration with Pylons a lot simpler.
[wichert]
- Switch from hardcoding all options in config.py to using parameters
for the template. This also allows us to use the more logical
auto_reload flag instead of reusing PROD_MODE, which is also used
for other purposes.
[wichert]
- Treat comments, processing instructions, and named entities in the
source template as "literals", which will be rendered into the
output unchanged. [chrism]
Bugfixes
- Skip elements in a "define-slot" clause if its being filled by the
calling template. [malthe]
- Support "fill-slot" on elements with METAL namespace. [malthe]
- Omit element text when rendering macro. [malthe]
- ``Macros`` class should not return callable functions, but rather a
``Macro`` object, which has a ``render``-method. This makes it
possible to use a path-expression to get to a macro without calling
it. [malthe]
- Fixed bug where a repeat-clause would reset the repeat variable
before evaluating the expression. [malthe]
- Fixed an issue related to correct restoring of ghosted template
objects. [malthe]
- Implicit doctype is correctly reestablished from cache. [malthe]
- Remove namespace declaration on root tag to work around syntax error
raised when parsing an XML tree loaded from the file cache. [malthe]
- Attribute assignments with an expression value that started with the
characters ``in`` (e.g. ``info.somename``) would be rendered to the
generated Python without the ``in`` prefix (as
e.g. ``fo.somename``). [chrism]
- When filling METAL slots (possibly with a specific version of
libxml2, I am using 2.6.32) it was possible to cause the translator
to attempt to add a stringtype to a NoneType (on a line that reads
``variable = self.symbols.slot+element.node.fill_slot`` because an
XPath expression looking for fill-slot nodes did not work
properly). [chrism]
- Preserve whitespace in string translation expressions. [malthe]
- Fixed interpolation bug where multiple attributes with interpolation
expressions would result in corrupted output. [malthe]
- Support try-except operator ('|') when 'python' is the default
expression type. [malthe]
- METAL macros should render in the template where they're
defined. [malthe]
- Avoid printing a line-break when we repeat over a single item
only. [malthe]
- Corrected Genshi namespace (needs a trailing slash). [malthe]
- Fixed a few more UnicodeDecodeErrors (test contributed by Wiggy).
In particular, never upcast to unicode during transformation, and
utf-8 encode Unicode attribute keys and values in Assign expressions
(e.g. py:attrs). [chrism]
- Fixed off-by-one bug in interpolation routine. [malthe]
- The repeat-clause should not output tail with every iteration. [malthe]
- CDATA sections are now correctly handled when using the
ElementTree-parser. [malthe]
- Fixed bug in path-expressions where string instances would be
(attempted) called. [malthe]
- CDATA sections are now correctly preserved when using expression
interpolation. [malthe]
- The Genshi interpolation operator ${} should not have its result
escaped when used in the text or tail regions. [malthe]
- Fixed edge case bug where inserting both a numeric entity and a
literal set of unicode bytes into the same document would cause a
UnicodeDecodeError. See also
http://groups.google.com/group/z3c_pt/browse_thread/thread/aea963d25a1778d0?hl=en
[chrism]
- Static attributes are now properly overriden by py:attr-attributes.
[malthe]
0.9 (2008/08/07)
----------------
- Added support for Genshi-templates.
[malthe]
- Cleanup and refactoring of translation module.
[malthe]
- If the template source contains a DOCTYPE declaration, output it
during rendering. [chrism]
- Fixed an error where numeric entities specified in text or tail
portions of elements would cause a UnicodeDecodeError to be raised
on systems configured with an 'ascii' default encoding. [chrism]
- Refactored file system based cache a bit and added a simple benchmark for
the cache. The initial load speed for a template goes down significantly
with the cache. Compared to zope.pagetemplate we are only 3x slower,
compared to 50x slower when cooking each template on process startup.
- Got rid entirely of the _escape function and inlined the actual code
instead. We go up again to 12x for path and 19x for Python expressions :)
[hannosch]
- Avoid string concatenation and use multiple write statements instead. These
are faster now, since we use a list append internally.
[hannosch]
- Inline the _escape function, because function calls are expensive in Python.
Added missing escaping for Unicode values.
[fschulze, hannosch]
- When templates are instantiated outside of a class-definition, a
relative file path will be made absolute using the module path.
[malthe]
- Simplified the _escape function handling by pulling in the str call into the
function. Corrected the bigtable hotshot test to only benchmark rendering.
- Replaced the cgi.escape function by an optimized local version, we go up
to 11x for path and 16x for Python expressions :) In the bigtable benchmark
the enhancement is more noticable - we are the same speed as spitfire -O1
templates now and just half the speed of -O3 :))
- Added a new benchmark test called bigtable that produces results which are
directly comparable to those produced by the bigtable.py benchmark in the
spitfire project.
- Introduce a new config option called `Z3C_PT_DISABLE_I18N`. If this
environment variable is set to `true`, the template engine will not call
into the zope.i18n machinery anymore, but fall back to simple interpolation
in all cases. In a normal Zope environment that has the whole i18n
infrastructure set up, this will render the templates about 15x faster than
normal TAL, instead of only 10x faster at this point.
- Removed the `second rendering` tests from the benchmark suite. Since we
enable the file cache for the benchmarks, there's no difference between the
first and second rendering anymore after the cache file has been written.
- Require zope.i18n 3.5 and add support for using its new negotiate function.
If you use the `zope_i18n_allowed_languages` environment variable the target
language for a template is only negotiated once per template, instead of
once for each translate function call. This more than doubles the speed
and the benchmark is back at 9.2 times faster.
- Extended the i18n handling to respect the passed in translation context to
the template. Usually this is the request, which is passed on under the
internal name of `_context` into the render functions. After extending the
i18n tests to include a negotiator and message catalog the improvement is
only at 4.5 anymore, as most of the time is spent inside the i18n machinery.
- Added persistent file cache functionality. If the environment variable is
set, each file system based template will add a directory to the cache
(currently a SHA-1 of the file's absolute path is used as the folder name)
and in the folder one file per params for the template (cache filename is
the hash of the params). Once a template file is initialized, an instance
local registry is added, which then looks up all cached files and
pre-populates the registry with the render functions.
- Fixed interpolation edge case bugs.
[malthe]
- Added new `Z3C_PT_FILECACHE` environment variable pointing to a directory.
If set, this will be used to cache the compiled files.
- Added a second variation of the repeat clause, using a simple for loop. It
doesn't support the repeatdict, though and is therefor not used yet. Also
began work to add introspection facilities to clauses about the variables
being used in them. The simpler loop causes the benchmarks to go up to a
10.5 (old 9.5) for path expressions and 14.5 (12.5) for python expressions.
So the next step is to introduce an optimization phase, that can decide
which variant of the loops to use.
- Made the debug mode independent from the Python debug mode. You can now
specify an environment variable called `Z3C_PT_DEBUG` to enable it.
- Added some code in a filecache module that can later be used to write out
and reload the compiled Python code to and from the file system. We should
be able to avoid reparsing on Python process restart.
- Simplified the generated _escape code. cgi.escape's second argument is a
simple boolean and not a list of characters to quote.
- Use a simple list based BufferIO class instead of a cStringIO for the out
stream. Avoiding the need to encode Unicode data is a bigger win. We do
not support arbitrarily mixing of Unicode and non-ascii inside the engine.
- Merged two adjacent writes into one inside the Tag clause.
- Applied a bunch of micro-optimizations. ''.join({}) is slightly faster
than ''.join({}.keys()) and does the same. Avoid a try/except for error
handling in non-debug mode. Test against 'is None' instead of a boolean
check for the result of the template registry lookup. Made PROD_MODE
available defined as 'not DEBUG_MODE' in config.py, so we avoid the 'not'
in every cook-check.
- Added more benchmark tests for the file variants.
- Optimized 'is None' handling in Tag clause similar to the Write clause.
- Made the _out.write method directly available as _write in all scopes, so
we avoid the method lookup call each time.
- Optimized 'is None' handling in Write clause.
- Slightly refactored benchmark tests and added tests for the file variants.
- In debug mode the actual source code for file templates is written out to
a <filename>.source file, to make it easier to inspect it.
- Make debug mode setting explicit in a config.py. Currently it is bound to
Python's __debug__, which is False when run with -O and otherwise True.
- Use a simplified UnicodeWrite clause for the result of _translate calls,
as the result value is guaranteed to be Unicode.
- Added benchmark tests for i18n handling.
- Added more tests for i18n attributes handling.
- Don't generate empty mappings for expressions with a trailing semicolon.
- Fixed undefined name 'static' error in i18n attributes handling and added
quoting to i18n attributes.
- Added condition to the valid attributes on tags in the tal namespace.
- Made sure the traceback from the *first* template exception
is carried over to __traceback_info__
- Added template source annotations on exceptions raised while
rendering a template.
0.8 (2008/03/19)
----------------
- Added support for 'nocall' and 'not' (for path-expressions).
- Added support for path- and string-expressions.
- Abstracted expression translation engine. Expression implementations
are now pluggable. Expression name pragmas are supported throughout.
- Formalized expression types
- Added support for 'structure'-keyword for replace and content.
- Result of 'replace' and 'content' is now escaped by default.
- Benchmark is now built as a custom testrunner
0.7 (2008/03/10)
----------------
- Added support for comments; expressions are allowed
inside comments, i.e.
<!-- ${'Hello World!'} -->
Comments are always included.
0.7 (2008/02/24)
----------------
- Added support for text templates; these allow expression
interpolation in non-XML documents like CSS stylesheets and
javascript files.
0.5 (2008/02/23)
----------------
- Expression interpolation implemented.
0.4 (2008/02/22)
----------------
- Engine now uses cStringIO yielding a 2.5x performance
improvement. Unicode is now handled correctly.
0.3 (2007/12/23)
----------------
- Code optimization; bug fixing spree
- Added ``ViewPageTemplateFile`` class
- Added support for i18n
- Engine rewrite; improved code generation abstractions
0.2 (2007/12/05)
----------------
- Major optimizations to the generated code
0.1 (2007/12/03)
----------------
- First public release
| z3c.pt | /z3c.pt-4.0.tar.gz/z3c.pt-4.0/CHANGES.rst | CHANGES.rst |
========
z3c.pt
========
.. image:: https://img.shields.io/pypi/v/z3c.pt.svg
:target: https://pypi.python.org/pypi/z3c.pt/
:alt: Latest release
.. image:: https://img.shields.io/pypi/pyversions/z3c.pt.svg
:target: https://pypi.org/project/z3c.pt/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/z3c.pt/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/z3c.pt/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/z3c.pt/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/z3c.pt?branch=master
.. image:: https://readthedocs.org/projects/z3cpt/badge/?version=latest
:target: https://z3cpt.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
This is a fast implementation of the ZPT template engine for Zope 3
which uses Chameleon to compile templates to byte-code.
The package provides application support equivalent to
``zope.pagetemplate``.
| z3c.pt | /z3c.pt-4.0.tar.gz/z3c.pt-4.0/README.rst | README.rst |
==========
Overview
==========
This section demonstrates the high-level template classes. All page
template classes in ``z3c.pt`` use path-expressions by default.
Page templates
==============
>>> from z3c.pt.pagetemplate import PageTemplate
>>> from z3c.pt.pagetemplate import PageTemplateFile
The ``PageTemplate`` class is initialized with a string.
>>> template = PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... Hello World!
... </div>""")
>>> print(template())
<div xmlns="http://www.w3.org/1999/xhtml">
Hello World!
</div>
The ``PageTemplateFile`` class is initialized with an absolute
path to a template file on disk.
>>> template_file = PageTemplateFile('tests/helloworld.pt')
>>> print(template_file())
<div xmlns="http://www.w3.org/1999/xhtml">
Hello World!
</div>
>>> import os
>>> template_file.filename.startswith(os.sep)
True
If a ``content_type`` is not informed and one is not present in the
request, it will be set to 'text/html'.
>>> class Response(object):
... def __init__(self):
... self.headers = {}
... self.getHeader = self.headers.get
... self.setHeader = self.headers.__setitem__
>>> class Request(object):
... def __init__(self):
... self.response = Response()
>>> template_file = PageTemplateFile('tests/helloworld.pt')
>>> request = Request()
>>> print(request.response.getHeader('Content-Type'))
None
>>> template = template_file.bind(None, request=request)
>>> print(template())
<div xmlns="http://www.w3.org/1999/xhtml">
Hello World!
</div>
>>> print(request.response.getHeader('Content-Type'))
text/html
If a ``content_type`` is present in the request, then we don't override it.
>>> request = Request()
>>> request.response.setHeader('Content-Type', 'text/xml')
>>> print(request.response.getHeader('Content-Type'))
text/xml
>>> template = template_file.bind(None, request=request)
>>> print(template())
<div xmlns="http://www.w3.org/1999/xhtml">
Hello World!
</div>
>>> print(request.response.getHeader('Content-Type'))
text/xml
A ``content_type`` can be also set at instantiation time, and it will
be respected.
>>> template_file = PageTemplateFile('tests/helloworld.pt',
... content_type='application/rdf+xml')
>>> request = Request()
>>> print(request.response.getHeader('Content-Type'))
None
>>> template = template_file.bind(None, request=request)
>>> print(template())
<div xmlns="http://www.w3.org/1999/xhtml">
Hello World!
</div>
>>> print(request.response.getHeader('Content-Type'))
application/rdf+xml
Both may be used as class attributes (properties).
>>> class MyClass(object):
... template = PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... Hello World!
... </div>""")
...
... template_file = PageTemplateFile('tests/helloworld.pt')
>>> instance = MyClass()
>>> print(instance.template())
<div xmlns="http://www.w3.org/1999/xhtml">
Hello World!
</div>
>>> print(instance.template_file())
<div xmlns="http://www.w3.org/1999/xhtml">
Hello World!
</div>
View page templates
===================
>>> from z3c.pt.pagetemplate import ViewPageTemplate
>>> from z3c.pt.pagetemplate import ViewPageTemplateFile
>>> class View(object):
... request = u'request'
... context = u'context'
...
... def __repr__(self):
... return 'view'
>>> view = View()
As before, we can initialize view page templates with a string (here
incidentally loaded from disk).
>>> from z3c.pt import tests
>>> path = tests.__path__[0]
>>> with open(path + '/view.pt') as f:
... template = ViewPageTemplate(f.read())
To render the template in the context of a view, we bind the template
passing the view as an argument (view page templates derive from the
``property``-class and are usually defined as an attribute on a view
class).
>>> print(template.bind(view)(test=u'test'))
<div xmlns="http://www.w3.org/1999/xhtml">
<span>view</span>
<span>context</span>
<span>request</span>
<span>test</span>
<span>test</span>
</div>
The exercise is similar for the file-based variant.
>>> template = ViewPageTemplateFile('tests/view.pt')
>>> print(template.bind(view)(test=u'test'))
<div xmlns="http://www.w3.org/1999/xhtml">
<span>view</span>
<span>context</span>
<span>request</span>
<span>test</span>
<span>test</span>
</div>
For compatibility reasons, view templates may be called with an
alternative context and request.
>>> print(template(view, u"alt_context", "alt_request", test=u'test'))
<div xmlns="http://www.w3.org/1999/xhtml">
<span>view</span>
<span>alt_context</span>
<span>alt_request</span>
<span>test</span>
<span>test</span>
</div>
Non-keyword arguments
=====================
These are passed in as ``options/args``, when using the ``__call__`` method.
>>> print(PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... <div tal:repeat="arg options/args">
... <span tal:content="arg" />
... </div>
... </div>""").__call__(1, 2, 3))
<div xmlns="http://www.w3.org/1999/xhtml">
<div>
<span>1</span>
</div>
<div>
<span>2</span>
</div>
<div>
<span>3</span>
</div>
</div>
Global 'path' Function
======================
Just like ``zope.pagetemplate``, it is possible to use a globally
defined ``path()`` function in a ``python:`` expression in ``z3c.pt``:
>>> template = PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... <span tal:content="options/test" />
... <span tal:content="python: path('options/test')" />
... </div>""")
>>> print(template(test='test'))
<div xmlns="http://www.w3.org/1999/xhtml">
<span>test</span>
<span>test</span>
</div>
Global 'exists' Function
========================
The same applies to the ``exists()`` function:
>>> template = PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... <span tal:content="python: exists('options/test') and 'Yes' or 'No'" />
... </div>""")
>>> print(template(test='test'))
<div xmlns="http://www.w3.org/1999/xhtml">
<span>Yes</span>
</div>
'default' and path expressions
==============================
Another feature from standard ZPT: using 'default' means whatever the
the literal HTML contains will be output if the condition is not met.
This works for attributes:
>>> template = PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... <span tal:attributes="class options/not-existing | default"
... class="blue">i'm blue</span>
... </div>""")
>>> print(template())
<div xmlns="http://www.w3.org/1999/xhtml">
<span class="blue">i'm blue</span>
</div>
And also for contents:
>>> template = PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... <span tal:content="options/not-existing | default">default content</span>
... </div>""")
>>> print(template())
<div xmlns="http://www.w3.org/1999/xhtml">
<span>default content</span>
</div>
'exists'-type expression
========================
Using 'exists()' function on non-global name and global name:
>>> template = PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... <span tal:content="python: exists('options/nope') and 'Yes' or 'No'">do I exist?</span>
... <span tal:content="python: exists('nope') and 'Yes' or 'No'">do I exist?</span>
... </div>""")
>>> print(template())
<div xmlns="http://www.w3.org/1999/xhtml">
<span>No</span>
<span>No</span>
</div>
Using 'exists:' expression on non-global name and global name
>>> template = PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... <span tal:define="yup exists:options/nope"
... tal:content="python: yup and 'Yes' or 'No'">do I exist?</span>
... <span tal:define="yup exists:nope"
... tal:content="python: yup and 'Yes' or 'No'">do I exist?</span>
... </div>""")
>>> print(template())
<div xmlns="http://www.w3.org/1999/xhtml">
<span>No</span>
<span>No</span>
</div>
Using 'exists:' in conjunction with a negation:
>>> print(PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... <span tal:condition="not:exists:options/nope">I don't exist?</span>
... </div>""")())
<div xmlns="http://www.w3.org/1999/xhtml">
<span>I don't exist?</span>
</div>
path expression with dictionaries
=================================
Path expressions give preference to dictionary items instead of
dictionary attributes.
>>> print(PageTemplate("""\
... <div xmlns="http://www.w3.org/1999/xhtml"
... tal:define="links python:{'copy':'XXX', 'delete':'YYY'}">
... <span tal:content="links/copy">ZZZ</span>
... </div>""")())
<div xmlns="http://www.w3.org/1999/xhtml">
<span>XXX</span>
</div>
Variable from one tag never leak into another
=============================================
>>> body = """\
... <div xmlns="http://www.w3.org/1999/xhtml"
... xmlns:tal="http://xml.zope.org/namespaces/tal"
... xmlns:metal="http://xml.zope.org/namespaces/metal">
... <div class="macro" metal:define-macro="greeting"
... tal:define="greeting greeting|string:'Hey'">
... <span tal:replace="greeting" />
... </div>
... <div tal:define="greeting string:'Hello'">
... <metal:block metal:use-macro="python:template.macros['greeting']" />
... </div>
... <div>
... <metal:block metal:use-macro="python:template.macros['greeting']" />
... </div>
... </div>"""
>>> print(PageTemplate(body)())
<div xmlns="http://www.w3.org/1999/xhtml">
<div class="macro">
'Hey'
</div>
<div>
<div class="macro">
'Hello'
</div>
<BLANKLINE>
</div>
<div>
<div class="macro">
'Hey'
</div>
<BLANKLINE>
</div>
</div>
TALES Function Namespaces
=========================
As described on http://wiki.zope.org/zope3/talesns.html, it is
possible to implement custom TALES Namespace Adapters. We also support
low-level TALES Function Namespaces (which the TALES Namespace
Adapters build upon).
>>> import datetime
>>> import zope.interface
>>> import zope.component
>>> from zope.traversing.interfaces import ITraversable
>>> from zope.traversing.interfaces import IPathAdapter
>>> from zope.tales.interfaces import ITALESFunctionNamespace
>>> from z3c.pt.namespaces import function_namespaces
>>> @zope.interface.implementer(ITALESFunctionNamespace)
... class ns1(object):
... def __init__(self, context):
... self.context = context
... def parent(self):
... return self.context.parent
>>> function_namespaces.namespaces['ns1'] = ns1
>>> class ns2(object):
... def __init__(self, context):
... self.context = context
... def upper(self):
... return self.context.upper()
>>> zope.component.getGlobalSiteManager().registerAdapter(
... ns2, [zope.interface.Interface], IPathAdapter, 'ns2')
>>> class ns3(object):
... def __init__(self, context):
... self.context = context
... def fullDateTime(self):
... return self.context.strftime('%Y-%m-%d %H:%M:%S')
>>> zope.component.getGlobalSiteManager().registerAdapter(
... ns3, [zope.interface.Interface], IPathAdapter, 'ns3')
A really corner-ish case from a legacy application: the TALES
Namespace Adapter doesn't have a callable function but traverses the
remaining path instead::
>>> from zope.traversing.interfaces import TraversalError
>>> @zope.interface.implementer(ITraversable)
... class ns4(object):
...
... def __init__(self, context):
... self.context = context
...
... def traverse(self, name, furtherPath):
... if name == 'page':
... if len(furtherPath) == 1:
... pagetype = furtherPath.pop()
... elif not furtherPath:
... pagetype = 'default'
... else:
... raise TraversalError("Max 1 path segment after ns4:page")
... return self._page(pagetype)
... if len(furtherPath) == 1:
... name = '%s/%s' % (name, furtherPath.pop())
... return 'traversed: ' + name
...
... def _page(self, pagetype):
... return 'called page: ' + pagetype
>>> zope.component.getGlobalSiteManager().registerAdapter(
... ns4, [zope.interface.Interface], IPathAdapter, 'ns4')
>>> @zope.interface.implementer(ITraversable)
... class ns5(object):
...
... def __init__(self, context):
... self.context = context
...
... def traverse(self, name, furtherPath):
... name = '/'.join([name] + furtherPath[::-1])
... del furtherPath[:]
... return 'traversed: ' + name
>>> zope.component.getGlobalSiteManager().registerAdapter(
... ns5, [zope.interface.Interface], IPathAdapter, 'ns5')
>>> class Ob(object):
... def __init__(self, title, date, parent=None, child=None):
... self.title = title
... self.date = date
... self.parent = parent
... self.child = child
>>> child = Ob('child', datetime.datetime(2008, 12, 30, 13, 48, 0, 0))
>>> father = Ob('father', datetime.datetime(1978, 12, 30, 13, 48, 0, 0))
>>> grandpa = Ob('grandpa', datetime.datetime(1948, 12, 30, 13, 48, 0, 0))
>>> child.parent = father
>>> father.child = child
>>> father.parent = grandpa
>>> grandpa.child = father
>>> class View(object):
... request = u'request'
... context = father
...
... def __repr__(self):
... return 'view'
>>> view = View()
>>> template = ViewPageTemplateFile('tests/function_namespaces.pt')
>>> print(template.bind(view)())
<div xmlns="http://www.w3.org/1999/xhtml">
<span>GRANDPA</span>
<span>2008-12-30 13:48:00</span>
<span>traversed: link:main</span>
<span>called page: default</span>
<span>called page: another</span>
<span></span>
<span>traversed: zope.Public</span>
<span>traversed: text-to-html</span>
<span>traversed: page/yet/even/another</span>
</div>
| z3c.pt | /z3c.pt-4.0.tar.gz/z3c.pt-4.0/src/z3c/pt/README.rst | README.rst |
import ast
import re
from types import MethodType
import zope.event
from chameleon.astutil import Builtin
from chameleon.astutil import NameLookupRewriteVisitor
from chameleon.astutil import Symbol
from chameleon.astutil import load
from chameleon.codegen import template
from chameleon.exc import ExpressionError
from chameleon.tales import ExistsExpr as BaseExistsExpr
from chameleon.tales import PythonExpr as BasePythonExpr
from chameleon.tales import StringExpr
from chameleon.tales import TalesExpr
from zope.contentprovider.interfaces import BeforeUpdateEvent
from zope.contentprovider.interfaces import ContentProviderLookupError
from zope.contentprovider.interfaces import IContentProvider
from zope.contentprovider.tales import addTALNamespaceData
from zope.location.interfaces import ILocation
from zope.traversing.adapters import traversePathElement
from zope.traversing.interfaces import ITraversable
import z3c.pt.namespaces
_marker = object()
def render_content_provider(econtext, name):
name = name.strip()
context = econtext.get("context")
request = econtext.get("request")
view = econtext.get("view")
cp = zope.component.queryMultiAdapter(
(context, request, view), IContentProvider, name=name
)
# provide a useful error message, if the provider was not found.
# Be sure to provide the objects in addition to the name so
# debugging ZCML registrations is possible
if cp is None:
raise ContentProviderLookupError(name, (context, request, view))
# add the __name__ attribute if it implements ILocation
if ILocation.providedBy(cp):
cp.__name__ = name
# Insert the data gotten from the context
addTALNamespaceData(cp, econtext)
# Stage 1: Do the state update.
zope.event.notify(BeforeUpdateEvent(cp, request))
cp.update()
# Stage 2: Render the HTML content.
return cp.render()
def path_traverse(base, econtext, call, path_items):
if path_items:
request = econtext.get("request")
path_items = list(path_items)
path_items.reverse()
while path_items:
name = path_items.pop()
ns_used = ":" in name
if ns_used:
namespace, name = name.split(":", 1)
base = z3c.pt.namespaces.function_namespaces[namespace](base)
if ITraversable.providedBy(base):
base = traversePathElement(
base, name, path_items, request=request
)
# base = proxify(base)
continue
# special-case dicts for performance reasons
if isinstance(base, dict):
next = base.get(name, _marker)
else:
next = getattr(base, name, _marker)
if next is not _marker:
base = next
if ns_used and isinstance(base, MethodType):
base = base()
# The bytecode peephole optimizer removes the next line:
continue # pragma: no cover
else:
base = traversePathElement(
base, name, path_items, request=request
)
# if not isinstance(base, (basestring, tuple, list)):
# base = proxify(base)
if call and getattr(base, "__call__", _marker) is not _marker:
return base()
return base
class ContextExpressionMixin:
"""Mixin-class for expression compilers."""
transform = None
def __call__(self, target, engine):
# Make call to superclass to assign value to target
assignment = super().__call__(
target, engine
)
transform = template(
"target = transform(econtext, target)",
target=target,
transform=self.transform,
)
return assignment + transform
class PathExpr(TalesExpr):
path_regex = re.compile(
r"^(?:(nocall|not):\s*)*((?:[A-Za-z0-9_][A-Za-z0-9_:]*)"
+ r"(?:/[?A-Za-z0-9_@\-+][?A-Za-z0-9_@\-\.+/:]*)*)$"
)
interpolation_regex = re.compile(r"\?[A-Za-z][A-Za-z0-9_]+")
traverser = Symbol(path_traverse)
def _find_translation_components(self, parts):
components = []
for part in parts[1:]:
interpolation_args = []
def replace(match):
start, end = match.span()
interpolation_args.append(part[start + 1: end])
return "%s"
while True:
part, count = self.interpolation_regex.subn(replace, part)
if count == 0:
break
if interpolation_args:
component = template(
"format % args",
format=ast.Str(part),
args=ast.Tuple(
list(map(load, interpolation_args)), ast.Load()
),
mode="eval",
)
else:
component = ast.Str(part)
components.append(component)
return components
def translate(self, string, target):
"""
>>> from chameleon.tales import test
>>> test(PathExpr('None')) is None
True
"""
string = string.strip()
if not string:
return template("target = None", target=target)
m = self.path_regex.match(string)
if m is None:
raise ExpressionError("Not a valid path-expression.", string)
nocall, path = m.groups()
# note that unicode paths are not allowed
parts = str(path).split("/")
components = self._find_translation_components(parts)
base = parts[0]
if not components:
if len(parts) == 1 and (nocall or base == "None"):
return template("target = base", base=base, target=target)
else:
components = ()
call = template(
"traverse(base, econtext, call, path_items)",
traverse=self.traverser,
base=load(base),
call=load(str(not nocall)),
path_items=ast.Tuple(elts=components),
mode="eval",
)
return template("target = value", target=target, value=call)
class NocallExpr(PathExpr):
"""A path-expression which does not call the resolved object."""
def translate(self, expression, engine):
return super().translate(
"nocall:%s" % expression, engine
)
class ExistsExpr(BaseExistsExpr):
exceptions = AttributeError, LookupError, TypeError, KeyError, NameError
def __init__(self, expression):
super().__init__("nocall:" + expression)
class ProviderExpr(ContextExpressionMixin, StringExpr):
transform = Symbol(render_content_provider)
class PythonExpr(BasePythonExpr):
builtins = {
name: template(
"tales(econtext, rcontext, name)",
tales=Builtin("tales"),
name=ast.Str(s=name),
mode="eval",
)
for name in ("path", "exists", "string", "nocall")
}
def __call__(self, target, engine):
return self.translate(self.expression, target)
def rewrite(self, node):
builtin = self.builtins.get(node.id)
if builtin is not None:
return template(
"get(name) if get(name) is not None else builtin",
get=Builtin("get"),
name=ast.Str(s=node.id),
builtin=builtin,
mode="eval",
)
@property
def transform(self):
return NameLookupRewriteVisitor(self.rewrite) | z3c.pt | /z3c.pt-4.0.tar.gz/z3c.pt-4.0/src/z3c/pt/expressions.py | expressions.py |
import os
import sys
from chameleon.compiler import ExpressionEvaluator
from chameleon.i18n import fast_translate
from chameleon.tales import NotExpr
from chameleon.tales import StringExpr
from chameleon.zpt import template
from zope import i18n
from zope.security.proxy import ProxyFactory
from z3c.pt import expressions
try:
from Missing import MV
MV = MV # pragma: no cover
except ImportError:
MV = object()
_marker = object()
BOOLEAN_HTML_ATTRS = frozenset(
[
# List of Boolean attributes in HTML that should be rendered in
# full form, e.g., <img ismap="ismap"> rather than their minimized
# form <img ismap>, as required by XML 1.0.
# From https://www.w3.org/TR/xhtml1/#C_10 and
# https://www.w3.org/TR/xhtml1/#h-4.5
"compact",
"nowrap",
"ismap",
"declare",
"noshade",
"checked",
"disabled",
"readonly",
"multiple",
"selected",
"noresize",
"defer",
]
)
class OpaqueDict(dict):
def __new__(cls, dictionary):
inst = dict.__new__(cls)
inst.dictionary = dictionary
return inst
def __getitem__(self, name):
return self.dictionary[name]
def __len__(self):
return len(self.dictionary)
def __repr__(self):
return "{...} (%d entries)" % len(self)
sys_modules = ProxyFactory(OpaqueDict(sys.modules))
class BaseTemplate(template.PageTemplate):
content_type = None
version = 2
expression_types = {
"python": expressions.PythonExpr,
"string": StringExpr,
"not": NotExpr,
"exists": expressions.ExistsExpr,
"path": expressions.PathExpr,
"provider": expressions.ProviderExpr,
"nocall": expressions.NocallExpr,
}
default_expression = "path"
literal_false = True
strict = False
trim_attribute_space = True
# https://github.com/zopefoundation/Zope/issues/716
enable_comment_interpolation = False
@property
def boolean_attributes(self):
if self.content_type == "text/xml":
return set()
return BOOLEAN_HTML_ATTRS
@property
def builtins(self):
builtins = {"nothing": None, "modules": sys_modules}
tales = ExpressionEvaluator(self.engine, builtins)
builtins["tales"] = tales
return builtins
def bind(self, ob, request=None):
def render(request=request, **kwargs):
context = self._pt_get_context(ob, request, kwargs)
return self.render(**context)
return BoundPageTemplate(self, render)
def render(self, target_language=None, **context):
# We always include a ``request`` variable; it is (currently)
# depended on in various expression types and must be defined
request = context.setdefault("request", None)
if target_language is None:
try:
target_language = i18n.negotiate(request)
except Exception:
target_language = None
context["target_language"] = target_language
# bind translation-method to request
def translate(
msgid,
domain=None,
mapping=None,
target_language=None,
default=None,
context=None,
):
if msgid is MV:
# Special case handling of Zope2's Missing.MV
# (Missing.Value) used by the ZCatalog but is
# unhashable.
# This case cannot arise in ordinary templates; msgid
# comes from i18n:translate attributes, which does not
# take a TALES expression, just a literal string.
# However, the 'context' argument is available as an
# implementation detail for macros
return
return fast_translate(
msgid, domain, mapping, request, target_language, default
)
context["translate"] = translate
if request is not None and not isinstance(request, str):
content_type = self.content_type or "text/html"
response = request.response
if response and not response.getHeader("Content-Type"):
response.setHeader("Content-Type", content_type)
base_renderer = super().render
return base_renderer(**context)
def __call__(self, *args, **kwargs):
bound_pt = self.bind(self)
return bound_pt(*args, **kwargs)
def _pt_get_context(self, instance, request, kwargs):
return dict(
context=instance,
here=instance,
options=kwargs,
request=request,
template=self,
)
class BaseTemplateFile(BaseTemplate, template.PageTemplateFile):
"""If ``filename`` is a relative path, the module path of the
class where the instance is used to get an absolute path."""
cache = {}
def __init__(self, filename, path=None, content_type=None, **kwargs):
if path is not None:
filename = os.path.join(path, filename)
if not os.path.isabs(filename):
for depth in (1, 2):
frame = sys._getframe(depth)
package_name = frame.f_globals.get("__name__", None)
if (
package_name is not None
and package_name != self.__module__
):
module = sys.modules[package_name]
try:
path = module.__path__[0]
except AttributeError:
path = module.__file__
path = path[: path.rfind(os.sep)]
break
else:
package_path = frame.f_globals.get("__file__", None)
if package_path is not None:
path = os.path.dirname(package_path)
break
if path is not None:
filename = os.path.join(path, filename)
template.PageTemplateFile.__init__(self, filename, **kwargs)
# Set content-type last, so that we can override whatever was
# magically sniffed from the source template.
self.content_type = content_type
class PageTemplate(BaseTemplate):
"""Page Templates using TAL, TALES, and METAL.
This class is suitable for standalone use or class
property. Keyword-arguments are passed into the template as-is.
Initialize with a template string."""
version = 1
def __get__(self, instance, type):
if instance is not None:
return self.bind(instance)
return self
class PageTemplateFile(BaseTemplateFile, PageTemplate):
"""Page Templates using TAL, TALES, and METAL.
This class is suitable for standalone use or class
property. Keyword-arguments are passed into the template as-is.
Initialize with a filename."""
cache = {}
class ViewPageTemplate(PageTemplate):
"""Template class suitable for use with a Zope browser view; the
variables ``view``, ``context`` and ``request`` variables are
brought in to the local scope of the template automatically, while
keyword arguments are passed in through the ``options``
dictionary. Note that the default expression type for this class
is 'path' (standard Zope traversal)."""
def _pt_get_context(self, view, request, kwargs):
context = kwargs.get("context")
if context is None:
context = view.context
request = request or kwargs.get("request") or view.request
return dict(
view=view,
context=context,
request=request,
options=kwargs,
template=self,
)
def __call__(self, _ob=None, context=None, request=None, **kwargs):
kwargs.setdefault("context", context)
kwargs.setdefault("request", request)
bound_pt = self.bind(_ob)
return bound_pt(**kwargs)
class ViewPageTemplateFile(ViewPageTemplate, PageTemplateFile):
"""If ``filename`` is a relative path, the module path of the
class where the instance is used to get an absolute path."""
cache = {}
class BoundPageTemplate:
"""When a page template class is used as a property, it's bound to
the class instance on access, which is implemented using this
helper class."""
__self__ = None
__func__ = None
def __init__(self, pt, render):
object.__setattr__(self, "__self__", pt)
object.__setattr__(self, "__func__", render)
im_self = property(lambda self: self.__self__)
im_func = property(lambda self: self.__func__)
macros = property(lambda self: self.__self__.macros)
filename = property(lambda self: self.__self__.filename)
def __call__(self, *args, **kw):
kw.setdefault("args", args)
return self.__func__(**kw)
def __setattr__(self, name, v):
raise AttributeError("Can't set attribute", name)
def __repr__(self):
return "<{}.Bound{} {!r}>".format(
type(self.__self__).__module__,
type(self.__self__).__name__,
self.filename,
) | z3c.pt | /z3c.pt-4.0.tar.gz/z3c.pt-4.0/src/z3c/pt/pagetemplate.py | pagetemplate.py |
import zope.component
from zope.traversing.interfaces import IPathAdapter
class AdapterNamespaces:
"""Simulate tales function namespaces with adapter lookup.
When we are asked for a namespace, we return an object that
actually computes an adapter when called:
To demonstrate this, we need to register an adapter:
>>> def adapter1(ob):
... return 1
>>> zope.component.getGlobalSiteManager().registerAdapter(
... adapter1, [zope.interface.Interface], IPathAdapter, 'a1')
Now, with this adapter in place, we can try out the namespaces:
>>> ob = object()
>>> namespaces = AdapterNamespaces()
>>> namespace = namespaces['a1']
>>> namespace(ob)
1
>>> namespace = namespaces['a2']
>>> namespace(ob)
Traceback (most recent call last):
...
KeyError: 'a2'
"""
def __init__(self):
self.namespaces = {}
def __getitem__(self, name):
namespace = self.namespaces.get(name)
if namespace is None:
def namespace(object):
try:
return zope.component.getAdapter(
object, IPathAdapter, name
)
except zope.component.ComponentLookupError:
raise KeyError(name)
self.namespaces[name] = namespace
return namespace
def registerFunctionNamespace(self, namespacename, namespacecallable):
"""Register a function namespace
namespace - a string containing the name of the namespace to
be registered
namespacecallable - a callable object which takes the following
parameter:
context - the object on which the functions
provided by this namespace will
be called
This callable should return an object which
can be traversed to get the functions provided
by the this namespace.
example:
class stringFuncs(object):
def __init__(self,context):
self.context = str(context)
def upper(self):
return self.context.upper()
def lower(self):
return self.context.lower()
engine.registerFunctionNamespace('string',stringFuncs)
"""
self.namespaces[namespacename] = namespacecallable
def getFunctionNamespace(self, namespacename):
"""
Returns the function namespace, if registered.
Unlike ``__getitem__``, this method will immediately raise a
KeyError if no such function is registered.
"""
return self.namespaces[namespacename]
function_namespaces = AdapterNamespaces()
try:
# If zope.pagetemplate is available, use the adapter
# registered with the main zope.pagetemplate engine so that
# we don't need to re-register them.
from zope.pagetemplate.engine import Engine
function_namespaces = Engine.namespaces
except (ImportError, AttributeError): # pragma: no cover
pass | z3c.pt | /z3c.pt-4.0.tar.gz/z3c.pt-4.0/src/z3c/pt/namespaces.py | namespaces.py |
.. _index:
======
z3c.pt
======
This package provides a fast implementation of the Zope Page Templates (ZPT) language which aims to be fully compatible with the reference implementation. The template engine is based on Chameleon.
.. note:: If you're looking to use Chameleon outside a Zope 2 or 3 environment, the `chameleon.zpt <http://pypi.python.org/pypi/chameleon.zpt>`_ package provides a light-weight implementation of the ZPT language.
Zope Page Templates (ZPT) is a system which can generate HTML and XML.
ZPT is formed by the *Template Attribute Language* (*TAL*), the
*Expression Syntax* (*TALES*), *Intertionalization* (*I18N*) and the *Macro Expansion Template Attribute Language* (*METAL*).
The package also implementation a text-mode which supports non-structural content like JavaScript.
Language Reference
==================
For a general reference, see the `documentation <http://chameleon.repoze.org/docs/zpt>`_ for the :mod:`chameleon.zpt` package. In the present reference, the language details that are specific to this implementation are described.
.. toctree::
:maxdepth: 2
narr/tales
narr/i18n
API documentation
=================
:mod:`z3c.pt` API documentation.
.. toctree::
:maxdepth: 2
api
Support and Development
=======================
This package is developed and maintained by `Malthe Borch <mailto:[email protected]>`_ and the Zope Community.
To report bugs, use the `bug tracker <https://bugs.launchpad.net/z3c.pt/>`_.
If you've got questions that aren't answered by this documentation,
please contact the `maillist
<http://groups.google.com/group/z3c_pt>`_.
Browse and check out tagged and trunk versions of :mod:`z3c.pt`
via the `Subversion repository <http://svn.zope.org/z3c.pt/>`_. To
check out the trunk via Subversion, use this command::
svn co svn://svn.zope.org/repos/main/z3c.pt/trunk z3c.pt
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| z3c.pt | /z3c.pt-4.0.tar.gz/z3c.pt-4.0/docs/index.rst | index.rst |
.. _tales_chapter:
TALES Expressions
=================
The *Template Attribute Language Expression Syntax* (TALES) standard
describes expressions that supply :term:`TAL` and :term:`METAL` with
data. TALES is *one* possible expression syntax for these languages,
but they are not bound to this definition. Similarly, TALES could be
used in a context having nothing to do with TAL or METAL.
.. note:: The TALES expression components used by the reference implementation are incompatible with :mod:`z3c.pt` and will not work. This :mod:`z3c.pt` package provides its own implementations.
TALES expressions are described below with any delimiter or quote
markup from higher language layers removed. Here is the basic
definition of TALES syntax::
Expression ::= [type_prefix ':'] String
type_prefix ::= Name
Here are some simple examples::
a.b.c
a/b/c
nothing
python: 1 + 2
string:Hello, ${user/getUserName}
The optional *type prefix* determines the semantics and syntax of the
*expression string* that follows it. A given implementation of TALES
can define any number of expression types, with whatever syntax you
like. It also determines which expression type is indicated by
omitting the prefix.
These are the TALES expression types supported by :mod:`z3c.pt`:
* ``python`` - execute a Python expression
* ``path`` - locate a value by its "path" (via getattr and getitem)
* ``nocall`` - locate an object by its path.
* ``not`` - negate an expression
* ``string`` - format a string
.. note:: if you do not specify a prefix within an expression context,
:mod:`z3c.pt`` assumes that the expression is a *path*
expression.
.. _tales_built_in_names:
Built-in Names
--------------
In addition to ``template``, ``macros``, ``default`` and ``repeat``, the following names are always available to TALES expressions in :mod:`z3c.pt`:
- ``nothing`` - equal to the Python null-value ``None``.
The following names are available in TALES expressions when evaluated inside page templates:
- ``options`` - contains the keyword arguments passed to the render-method.
- ``context`` - the template context
- ``request`` - the current request
- ``path`` - a method which will evaluate a path-expression, expressed as a string.
- ``exists`` - a method which will evaluate an exists-expression, expressed as a string.
- ``modules`` - provides access to previously imported system modules; using this variable is not recommended.
- ``econtext`` - dynamic variable scope dictionary which keeps track of global variables brought into scope using macros; used internally by the engine, relying on this variable is not recommended (although some legacy applications do so).
Finally, view page templates provide the following names:
- ``view`` - the view instance
``nocall`` expressions
----------------------
Syntax
~~~~~~
``nocall`` expression syntax::
nocall_expression ::= 'nocall:' path_expression
Description
~~~~~~~~~~~
Nocall expressions avoid calling the __call__ method of the last
element of a path expression.
An ordinary path expression tries to render the object that it
fetches. This means that if the object is a function, method, or some
other kind of executable thing, then expression will evaluate to the
result of calling the object. This is usually what you want, but not
always.
Examples
~~~~~~~~
Using nocall to prevent calling the ``__call__`` of the last element
of a path expression::
<span tal:define="doc nocall:context/acallabledocument"
tal:content="string:${doc/getId}: ${doc/title}">
Id: Title</span>
``not`` expressions
-------------------
Syntax
~~~~~~
``not`` expression syntax::
not_expression ::= 'not:' expression
Description
~~~~~~~~~~~
A ``not`` expression evaluates the expression string (recursively) as
a full expression, and returns the boolean negation of its value. If
the expression supplied does not evaluate to a boolean value, *not*
will issue a warning and *coerce* the expression's value into a
boolean type based on the following rules:
#. the number 0 is *false*
#. positive and negative numbers are *true*
#. an empty string or other sequence is *false*
#. a non-empty string or other sequence is *true*
#. a *non-value* (e.g. None) is *false*
#. all other values are implementation-dependent.
If no expression string is supplied, an error should be generated.
:mod:`z3c.pt` considers all objects not specifically listed above as
*false* to be *true*.
Examples
~~~~~~~~
Testing a sequence::
<p tal:condition="not:context/keys">
There are no keys.
</p>
``path`` expressions
--------------------
Syntax
~~~~~~
Path expression syntax::
PathExpr ::= Path [ '|' Expression ]
Path ::= variable [ '/' PathSegment ]*
variable ::= Name
PathSegment ::= ( '?' variable ) | PathChar+
PathChar ::= AlphaNumeric | ' ' | '_' | '-' | '.' | ',' | '~'
Description
~~~~~~~~~~~
A path expression consists of a *path* optionally followed by a
vertical bar (|) and alternate expression. A path consists of one or
more non-empty strings separated by slashes. The first string must be
a variable name (a built-in variable or a user defined variable), and
the remaining strings, the *path segments*, may contain letters,
digits, spaces, and the punctuation characters underscore, dash,
period, comma, and tilde.
A limited amount of indirection is possible by using a variable name
prefixed with ``?`` as a path segment. The variable must contain a
string, which replaces that segment before the path is traversed.
For example::
request/cookies/oatmeal
nothing
here/some-file 2001_02.html.tar.gz/foo
root/to/branch | default
request/name | string:Anonymous Coward
here/?tname/macros/?mname
When a path expression is evaluated, :mod:`z3c.pt` attempts to
traverse the path, from left to right, until it succeeds or runs out
of paths segments. To traverse a path, it first fetches the object
stored in the variable. For each path segment, it traverses from the
current object to the subobject named by the path segment. Subobjects
are located according to standard traversal rules.
.. note:: The Zope 3 traversal API is used to traverse to subobjects. The `five.pt <http://pypi.python.org/pypi/five.pt>`_ package provides a Zope 2-compatible path expression.
Once a path has been successfully traversed, the resulting object is
the value of the expression. If it is a callable object, such as a
method or template, it is called.
If a traversal step fails, and no alternate expression has been
specified, an error results. Otherwise, the alternate expression is
evaluated.
The alternate expression can be any TALES expression. For example,
``request/name | string:Anonymous Coward`` is a valid path
expression. This is useful chiefly for providing default values, such
as strings and numbers, which are not expressable as path expressions.
Since the alternate expression can be a path expression, it is
possible to "chain" path expressions, as in ``first | second | third |
nothing``.
If no path is given the result is *nothing*.
Since every path must start with a variable name, you need a set of
starting variables that you can use to find other objects and values.
See the :ref:`tales_built_in_names` for a list of built-in variables.
Variable names are looked up first in locals, then in the built-in
list, so the built-in variables act just like built-ins in Python;
They are always available, but they can be shadowed by a local
variable declaration.
Examples
~~~~~~~~
Inserting a cookie variable or a property::
<span tal:replace="request/cookies/pref | here/pref">
preference
</span>
Inserting the user name::
<p tal:content="user/getUserName">
User name
</p>
``python`` expressions
----------------------
Syntax
~~~~~~
Python expression syntax::
Any valid Python language expression
Description
~~~~~~~~~~~
Python expressions evaluate Python code in a restricted
environment (no access to variables starting with an underscore). Python expressions offer the same facilities as those
available in Python-based Scripts and DTML variable expressions.
.. warning: Zope 2 page templates may be executed in a security-restricted environment which ties in with the Zope 2 security model. This is not supported by :mod:`z3c.pt`.
Examples
~~~~~~~~
Using a module usage (pick a random choice from a list)::
<span tal:replace="python:random.choice([
'one', 'two', 'three', 'four', 'five'])">
A random number between one and five
</span>
String processing (capitalize the user name)::
<p tal:content="python:user.getUserName().capitalize()">
User Name
</p>
Basic math (convert an image size to megabytes)::
<p tal:content="python:image.getSize() / 1048576.0">
12.2323
</p>
String formatting (format a float to two decimal places)::
<p tal:content="python:'%0.2f' % size">
13.56
</p>
``string`` expressions
----------------------
Syntax
~~~~~~
String expression syntax::
string_expression ::= ( plain_string | [ varsub ] )*
varsub ::= ( '$' Path ) | ( '${' Path '}' )
plain_string ::= ( '$$' | non_dollar )*
non_dollar ::= any character except '$'
Description
~~~~~~~~~~~
String expressions interpret the expression string as text. If no
expression string is supplied the resulting string is *empty*. The
string can contain variable substitutions of the form ``$name`` or
``${path}``, where ``name`` is a variable name, and ``path`` is a path
expression. The escaped string value of the path expression is
inserted into the string.
.. note:: To prevent a ``$`` from being interpreted this
way, it must be escaped as ``$$``.
Examples
~~~~~~~~
Basic string formatting::
<span tal:replace="string:$this and $that">
Spam and Eggs
</span>
Using paths::
<p tal:content="string:${request/form/total}">
total: 12
</p>
Including a dollar sign::
<p tal:content="string:$$$cost">
cost: $42.00
</p>
| z3c.pt | /z3c.pt-4.0.tar.gz/z3c.pt-4.0/docs/narr/tales.rst | tales.rst |
Changelog
=========
2.3.0 (2021-12-16)
------------------
- Add support for Python 3.8, 3.9, and 3.10.
- Drop support for Python 3.4.
2.2.0 (2019-01-27)
------------------
- Add support for Python 3.7.
- Drop support for running the tests using `python setup.py test`
2.1.0 (2017-10-17)
------------------
- Fix rendering with Chameleon 3.0 and above. See `issue 2
<https://github.com/zopefoundation/z3c.ptcompat/issues/2>`_.
- Add support for Python 3.6.
- Drop support for Python 3.3.
2.0 (2016-09-02)
----------------
- Added support for Python 3.4, 3.5, PyPy and PyPy3.
- Dropped support for Python 2.6.
2.0.0a1 (2013-02-25)
--------------------
- Added support for Python 3.3.
- Ensured that ``chameleon.tal.ReapeatDict`` can be adapted. (Needs to be
fixed in Chameleon.)
- Replaced deprecated ``zope.interface.implements`` usage with equivalent
``zope.interface.implementer`` decorator.
- Dropped support for Python 2.4 and 2.5.
1.0.1 (2012-02-15)
------------------
- Move ``zope.testing`` to test dependencies, add undeclared dependencies.
1.0 (2011-10-10)
----------------
- Update implementation to use component-based template engine
configuration, plugging directly into the Zope Toolkit framework.
The package no longer provides template classes, or ZCML directives;
you should import directly from the ZTK codebase.
Also, note that the ``PREFER_Z3C_PT`` environment option has been
rendered obsolete; instead, this is now managed via component
configuration.
- Upgrade to Chameleon 2.x.
0.5.7 (2010-11-25)
------------------
- Added not yet declared test dependency on ``zope.testing``.
- Fixed test tear down so tests can be run multiple times.
0.5.6 (2010-04-19)
------------------
- Remove broken templates from registry during engine migration. In
some testing situation, stale templates would be tracked in the
regsitry.
- Existing template instances are now migrated to the right engine
when using the ``enable`` and ``disable`` methods. [malthe]
0.5.5 (2009-07-24)
------------------
- Make tests pass in a binary release by not relying on the pacakge structure.
0.5.4 (2009-07-23)
------------------
- Added a test requirement explicitely.
0.5.3 (2009-05-28)
------------------
- Added support for browser:addform, browser:editform, browser:form,
and browser:schemadisplay directives.
0.5.2 (2009-03-09)
------------------
- Fixing brown-bag release 0.5.1.
0.5.1 (2009-03-09)
------------------
- Added missing ``lxml`` test dependency.
- Fixed tests to work with current version of z3c.pt.
- Fixed autor e-mail address.
- Added doctests and change log to long description to show up at pypi
homepage.
- Reformatted release dates in change log to use iso dates.
0.5 (2009-02-16)
----------------
- Added module which patches ``zope.app.pagetemplate`` such that
template classes depend on ``z3c.pt`` for rendering (import
optional). [malthe]
0.4 (2009-02-10)
----------------
- Rename project to z3c.ptcompat to deal with setuptools issues (as discussed
on zope-dev http://mail.zope.org/pipermail/zope-dev/2008-December/033820.html)
- Added optional option ``doctest`` for output checker to allow usage
with alternative implementations, e.g. the Zope doctest
module. [malthe]
- Added tests for meta-directives and fixed some minor errors. [malthe]
- Added update-tool to walk a source tree and automatically rewrite
template import statements in each file. [malthe]
- Added meta-directives for browser pages and viewlets. These build
upon the original implementations, but make sure that the Chameleon
template engine is used. [malthe]
- Added ``PageTemplateFile``. [malthe]
0.3 (2008-10-02)
----------------
- Various changes.
0.2 (2008-09-13)
----------------
- Various changes.
0.1 (2008-09-09)
----------------
- Initial release.
| z3c.ptcompat | /z3c.ptcompat-2.3.0.tar.gz/z3c.ptcompat-2.3.0/CHANGES.rst | CHANGES.rst |
Overview
========
.. image:: https://img.shields.io/pypi/v/z3c.ptcompat.svg
:target: https://pypi.python.org/pypi/z3c.ptcompat/
:alt: Latest release
.. image:: https://img.shields.io/pypi/pyversions/z3c.ptcompat.svg
:target: https://pypi.org/project/z3c.ptcompat/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/z3c.ptcompat/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/z3c.ptcompat/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/z3c.ptcompat/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/z3c.ptcompat?branch=master
This package provides a page template engine implementation based on
Chameleon. It plugs into the `zope.pagetemplate
<https://pypi.python.org/pypi/zope.pagetemplate>`_ package and has an
explicit dependency on this package.
You can use the package to replace Zope's reference template engine
with Chameleon in an application based on the Zope Toolkit.
Configuration
-------------
The package is configured via ZCML.
| z3c.ptcompat | /z3c.ptcompat-2.3.0.tar.gz/z3c.ptcompat-2.3.0/README.rst | README.rst |
import os
import re
import sys
import difflib
import optparse
import subprocess
parser = optparse.OptionParser()
parser.add_option(
"-n",
"--dry-run",
action="store_true",
dest="dry_run",
default=False,
help="Don't actually make any changes.",
)
parser.add_option(
"-v",
"--verbose",
action="store_true",
dest="verbose",
default=False,
help="Verbose output.",
)
re_vptf_sub = (
re.compile(
r"^from zope\.app\.pagetemplate(\.viewpagetemplatefile)?"
r" import ViewPageTemplateFile$",
re.M,
),
r"from z3c.ptcompat import ViewPageTemplateFile",
)
re_ptf_sub = (
re.compile(
r"^from zope\.pagetemplate(\.pagetemplatefile)?"
r" import PageTemplateFile$",
re.M,
),
r"from z3c.ptcompat import PageTemplateFile",
)
def log(msg):
for line in msg.split("\n"):
print(">>> %s" % line)
def status(msg):
for line in msg.split("\n"):
print(" %s" % line)
def main(options, args):
if options.dry_run:
status(
"Warning: Dry run---no changes will be made to the file-system."
)
path = os.getcwd()
status("Working directory: %s" % path)
log("Analyzing source-code...")
registry = {}
count = 0
for arg, dirname, names in os.walk(path):
for name in names:
base, ext = os.path.splitext(name)
if ext != ".py":
continue
if options.verbose and count > 0 and count % 500 == 0:
status("Processed %d files." % count)
count += 1
filename = os.path.join(arg, name)
diff = create_diff(filename)
if diff is not None:
registry[filename] = diff
status("%d files processed" % count)
log("Updating import-statements in %d files..." % len(registry.keys()))
if options.dry_run:
queue = (["patch", "-p0", "--dry-run"],)
else:
queue = ["patch", "-p0", "--dry-run"], ["patch", "-p0"]
for args in queue:
if options.verbose:
args.append("--verbose")
else:
args.append("--quiet")
proc = subprocess.Popen(
" ".join(args),
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
diffs = []
for filename, body in registry.iteritems():
if options.verbose:
changes = body.count("+++ ")
status(
"%s (%d %s)."
% (
filename,
changes,
"changes" if (changes > 1) else "change",
)
)
diffs.append(body)
if not diffs:
break
output, err = proc.communicate("\n".join(diffs) + "\n")
if proc.returncode != 0:
for line in output.split("\n"):
status(line)
status("An error occurred while applying patches.")
break
else:
status("Succesfully patched files.")
if "--dry-run" in args:
status("No files were changed.")
sys.exit(proc.returncode)
def create_diff(filename):
original = open(filename).read()
new = original
# process regular expression substitutions
for exp, replacement in (re_vptf_sub, re_ptf_sub):
new = exp.sub(replacement, new)
if original != new:
return ''.join(
difflib.unified_diff(
original.splitlines(True),
new.splitlines(True),
filename,
filename)
)
if __name__ == "__main__":
main(*parser.parse_args()) | z3c.ptcompat | /z3c.ptcompat-2.3.0.tar.gz/z3c.ptcompat-2.3.0/tools/update.py | update.py |
Setting up a PyPI "simple" index
================================
This package provides a mirror for the PyPI simple interface,
http://cheeseshop.python.org/simple/.
To set up a mirror:
- install this package using setuptools (easy_install, buildout, etc.)
so that the script, pypimirror script is installed.
- create your mirror configuration file maybe based on config.cfg.sample
- Run the pypimirror script passing the name of the mirror configuration
file
This will initialize the mirror.
- Set up a cron job to run update-mirror periodically.
LICENSE
=======
Zope Public License 2.1 (ZPL 2.1)
Authors
=======
z3c.pypimirror took place at the Blackforest Sprint 2008 and involved the
the following persons:
- Daniel Kraft (Lead)
- Gottfried Ganssauge
- Josip Delic
- Andreas Jung
| z3c.pypimirror | /z3c.pypimirror-1.0.16.tar.gz/z3c.pypimirror-1.0.16/README.txt | README.txt |
z3c.pypimirror
==============
>>> import os, sys
First we try to get a list from pypi, to test xmlrpc connection.
>>> packageprefix = 'zope.app.c'
>>> from z3c.pypimirror.mirror import PypiPackageList, Mirror, Package
>>> pypi_pl = PypiPackageList()
>>> pypi_list = pypi_pl.list()
>>> pypi_list2 = pypi_pl.list([packageprefix + '*'])
>>> False not in [item.startswith(packageprefix) for item in pypi_list2]
True
>>> len(pypi_list) > len(pypi_list2)
True
If we got an list from pypi we try parse the output and download a
file.
>>> mirror = Mirror(join(sample_buildout, "mirror"))
>>> packagename = pypi_list2[0]
>>> package = Package(packagename)
>>> mirrorpackage = mirror.package(packagename)
>>> file = package.ls()[0]
>>> data = package.get(file)
>>> mirrorpackage.write(file[1], data)
>>> packagename in os.listdir(join(sample_buildout, 'mirror'))
True
Now we create a `index.html` for the package.
>>> mirrorpackage.index_html('http://pypi.python.org/simple')
>>> path_package_index = mirrorpackage.path('index.html')
>>> packagename in open(path_package_index, 'r').read()
True
# Is the following intemded to work?
#
#Now we create a `index2.html` for the mirror.
#
#>>> mirror.index_html()
#>>> path_index = join(mirror.base_path, 'index2.html')
#>>> packagename in open(path_index, 'r').read()
#True
If a file is not on the mirror and cleanup is activated it will
be removed. First we add a dummy file.
>>> write(mirrorpackage.path(), 'dummy.egg',
... """
... Banane
... """)
>>> ls(mirrorpackage.path())
- dummy.egg
...
>>> mirrorpackage.cleanup([file,])
>>> 'dummy.egg' not in os.listdir(mirrorpackage.path())
True
Now we're trying everything in concert
First cleanup a bit
>>> remove(mirrorpackage.path())
>>> packagename in os.listdir(join(sample_buildout, 'mirror'))
False
Create a configuration involving our mirror path
>>> cfg = join (mirror.base_path, 'mirror.cfg')
>>> write(cfg, """
... [DEFAULT]
... mirror_file_path = %s
... package_matches =
... %s
... """ % (mirror.base_path, packagename))
Generate a script (don't know how to use the one generated by buildout)
>>> write ('pypimirror.py',
... '''
... import sys
... sys.path[:] = [
... "%s"
... ]
... from z3c.pypimirror.mirror import run
... run()
... ''' % '",\n "'.join (sys.path))
| z3c.pypimirror | /z3c.pypimirror-1.0.16.tar.gz/z3c.pypimirror-1.0.16/src/z3c/pypimirror/README.txt | README.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.