code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
Containment constraints
=======================
Containment constraints allow us to express restrictions on the types
of items that can be placed in containers or on the types of
containers an item can be placed in. We express these constraints in
interfaces. We will use some container and item interfaces defined
in :mod:`zope.container.tests.constraints_example`:
.. literalinclude:: ../src/zope/container/tests/constraints_example.py
:lines: 1-9
In this example, we used the contains function to declare that objects
that provide IBuddyFolder can only contain items that provide IBuddy.
Note that we used a string containing a dotted name for the IBuddy
interface. This is because IBuddy hasn't been defined yet. When we
define IBuddy, we can use IBuddyFolder directly:
.. literalinclude:: ../src/zope/container/tests/constraints_example.py
:lines: 11-12
Now, with these interfaces in place, we can define Buddy and
BuddyFolder classes:
.. literalinclude:: ../src/zope/container/tests/constraints_example.py
:lines: 14-20
and verify that we can put buddies in buddy folders:
.. doctest::
>>> from zope.component.factory import Factory
>>> from zope.container.constraints import checkFactory
>>> from zope.container.constraints import checkObject
>>> from zope.container.tests.constraints_example import Buddy
>>> from zope.container.tests.constraints_example import BuddyFolder
>>> checkObject(BuddyFolder(), 'x', Buddy())
>>> checkFactory(BuddyFolder(), 'x', Factory(Buddy))
True
If we try to use other containers or folders, we'll get errors:
.. doctest::
>>> from zope.container.interfaces import IContainer
>>> from zope.interface import implementer
>>> @implementer(IContainer)
... class Container:
... pass
>>> from zope.location.interfaces import IContained
>>> @implementer(IContained)
... class Contained:
... pass
>>> checkObject(Container(), 'x', Buddy())
... # doctest: +ELLIPSIS
Traceback (most recent call last):
zope.container.interfaces.InvalidContainerType: ...
>>> checkFactory(Container(), 'x', Factory(Buddy))
False
>>> checkObject(BuddyFolder(), 'x', Contained())
... # doctest: +ELLIPSIS
Traceback (most recent call last):
zope.container.interfaces.InvalidItemType: ...
>>> checkFactory(BuddyFolder(), 'x', Factory(Contained))
False
In the example, we defined the container first and then the items. We
could have defined these in the opposite order:
.. literalinclude:: ../src/zope/container/tests/constraints_example.py
:lines: 22-34
.. doctest::
>>> from zope.container.tests.constraints_example import Contact
>>> from zope.container.tests.constraints_example import Contacts
>>> checkObject(Contacts(), 'x', Contact())
>>> checkFactory(Contacts(), 'x', Factory(Contact))
True
>>> checkObject(Contacts(), 'x', Buddy())
... # doctest: +ELLIPSIS
Traceback (most recent call last):
zope.container.interfaces.InvalidItemType: ...
>>> checkFactory(Contacts(), 'x', Factory(Buddy))
False
The constraints prevent us from moving a container beneath itself (either into
itself or another folder beneath it):
.. doctest::
>>> container = Container()
>>> checkObject(container, 'x', container)
Traceback (most recent call last):
TypeError: Cannot add an object to itself or its children.
>>> from zope.interface import directlyProvides
>>> from zope.location.interfaces import ILocation
>>> subcontainer = Container()
>>> directlyProvides(subcontainer, ILocation)
>>> subcontainer.__parent__ = container
>>> checkObject(subcontainer, 'x', container)
Traceback (most recent call last):
TypeError: Cannot add an object to itself or its children.
| zope.container | /zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/constraints.rst | constraints.rst |
from persistent import Persistent
from zope.proxy import AbstractPyProxyBase
from zope.container._util import use_c_impl
_MARKER = object()
def _special_name(name):
"attribute names we delegate to Persistent for"
return (name.startswith('_Persistent')
or name.startswith('_p_')
or name.startswith('_v_')
or name in ContainedProxyBase.__slots__)
@use_c_impl
class ContainedProxyBase(AbstractPyProxyBase, Persistent):
"""Persistent proxy
"""
__slots__ = ('_wrapped', '__parent__', '__name__', '__weakref__')
def __new__(cls, obj):
inst = super().__new__(cls, obj)
inst.__parent__ = None
inst.__name__ = None
return inst
def __init__(self, obj):
super().__init__(obj)
self.__parent__ = None
self.__name__ = None
def __reduce__(self):
return (type(self),
(self._wrapped,),
(self.__parent__, self.__name__))
def __reduce_ex__(self, protocol):
return self.__reduce__()
def __setstate__(self, state):
object.__setattr__(self, '__parent__', state[0])
object.__setattr__(self, '__name__', state[1])
def __getstate__(self):
return (self.__parent__, self.__name__)
def __getnewargs__(self):
return (self._wrapped,)
def _p_invalidate(self):
# The superclass wants to clear the __dict__, which
# we don't have, but we would otherwise delegate
# to the wrapped object, which is clearly wrong in this case.
# This method is a copy of the super method with
# clearing the dict omitted
if self._Persistent__jar is not None:
if self._Persistent__flags is not None:
self._Persistent__flags = None
try:
object.__getattribute__(self, '__dict__').clear()
except AttributeError:
pass
# Attribute protocol
def __getattribute__(self, name):
if _special_name(name):
# Our own attribute names need to go to Persistent so we get
# activated
return Persistent.__getattribute__(self, name)
if name in (
'__reduce__',
'__reduce_ex__',
'__getstate__',
'__setstate__',
'__getnewargs__',
):
return object.__getattribute__(self, name)
return super().__getattribute__(name)
def __setattr__(self, name, value):
if _special_name(name):
# Our own attribute names need to go directly to Persistent
# so that _p_changed gets set, in addition to the _p values
# themselves
return Persistent.__setattr__(self, name, value)
return super().__setattr__(name, value)
@use_c_impl
def getProxiedObject(obj):
if isinstance(obj, ContainedProxyBase):
return obj._wrapped
return obj
@use_c_impl
def setProxiedObject(obj, new_value):
if not isinstance(obj, ContainedProxyBase):
raise TypeError('Not a proxy')
old, obj._wrapped = obj._wrapped, new_value
return old | zope.container | /zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/_proxy.py | _proxy.py |
__docformat__ = 'restructuredtext'
from zope.interface import implementer
from zope.container.contained import Contained
from zope.container.contained import setitem
from zope.container.contained import uncontained
from zope.container.interfaces import IContainer
@implementer(IContainer)
class SampleContainer(Contained):
"""Sample container implementation suitable for testing.
It is not suitable, directly as a base class unless the subclass
overrides `_newContainerData` to return a persistent mapping object.
"""
def __init__(self):
self.__data = self._newContainerData()
def _newContainerData(self):
"""Construct an item-data container
Subclasses should override this if they want different data.
The value returned is a mapping object that also has `get`,
`has_key`, `keys`, `items`, and `values` methods.
"""
return {}
def keys(self):
'''See interface `IReadContainer`'''
return self.__data.keys()
def __iter__(self):
return iter(self.__data)
def __getitem__(self, key):
'''See interface `IReadContainer`'''
return self.__data[key]
def get(self, key, default=None):
'''See interface `IReadContainer`'''
return self.__data.get(key, default)
def values(self):
'''See interface `IReadContainer`'''
return self.__data.values()
def __len__(self):
'''See interface `IReadContainer`'''
return len(self.__data)
def items(self):
'''See interface `IReadContainer`'''
return self.__data.items()
def __contains__(self, key):
'''See interface `IReadContainer`'''
return key in self.__data
has_key = __contains__
def __setitem__(self, key, object):
'''See interface `IWriteContainer`'''
setitem(self, self.__data.__setitem__, key, object)
def __delitem__(self, key):
'''See interface `IWriteContainer`'''
uncontained(self.__data[key], self, key)
del self.__data[key] | zope.container | /zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/sample.py | sample.py |
"""Find Support
"""
__docformat__ = 'restructuredtext'
from zope.interface import implementer
from .interfaces import IFind
from .interfaces import IIdFindFilter
from .interfaces import IObjectFindFilter
from .interfaces import IReadContainer
@implementer(IFind)
class FindAdapter:
"""Adapts :class:`zope.container.interfaces.IReadContainer`"""
__used_for__ = IReadContainer
def __init__(self, context):
self._context = context
def find(self, id_filters=None, object_filters=None):
'See IFind'
id_filters = id_filters or []
object_filters = object_filters or []
result = []
container = self._context
for id, object in container.items():
_find_helper(id, object, container,
id_filters, object_filters,
result)
return result
def _find_helper(id, object, container, id_filters, object_filters, result):
for id_filter in id_filters:
if not id_filter.matches(id):
break
else:
# if we didn't break out of the loop, all name filters matched
# now check all object filters
for object_filter in object_filters:
if not object_filter.matches(object):
break
else:
# if we didn't break out of the loop, all filters matched
result.append(object)
if not IReadContainer.providedBy(object):
return
container = object
for id, object in container.items():
_find_helper(id, object, container, id_filters, object_filters, result)
@implementer(IIdFindFilter)
class SimpleIdFindFilter:
"""Filter objects by ID"""
def __init__(self, ids):
self._ids = ids
def matches(self, id):
'See INameFindFilter'
return id in self._ids
@implementer(IObjectFindFilter)
class SimpleInterfacesFindFilter:
"""Filter objects on the provided interfaces"""
def __init__(self, *interfaces):
self.interfaces = interfaces
def matches(self, object):
for iface in self.interfaces:
if iface.providedBy(object):
return True
return False | zope.container | /zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/find.py | find.py |
"""Traversal components for containers
"""
__docformat__ = 'restructuredtext'
from zope.component import ComponentLookupError
from zope.component import getSiteManager
from zope.component import queryMultiAdapter
from zope.interface import implementer
from zope.interface import providedBy
from zope.publisher.interfaces import IDefaultViewName
from zope.publisher.interfaces import NotFound
from zope.publisher.interfaces.browser import IBrowserPublisher
from zope.publisher.interfaces.xmlrpc import IXMLRPCPublisher
from zope.traversing.interfaces import ITraversable
from zope.traversing.interfaces import TraversalError
from zope.container.interfaces import IItemContainer
from zope.container.interfaces import IReadContainer
from zope.container.interfaces import ISimpleReadContainer
# Note that the next two classes are included here because they
# can be used for multiple view types.
@implementer(IBrowserPublisher, IXMLRPCPublisher)
class ContainerTraverser:
"""A traverser that knows how to look up objects by name in a container."""
__used_for__ = ISimpleReadContainer
def __init__(self, container, request):
self.context = container
self.request = request
def publishTraverse(self, request, name):
"""See zope.publisher.interfaces.IPublishTraverse"""
subob = self.context.get(name, None)
if subob is None:
view = queryMultiAdapter((self.context, request), name=name)
if view is not None:
return view
raise NotFound(self.context, name, request)
return subob
def browserDefault(self, request):
"""See zope.publisher.browser.interfaces.IBrowserPublisher"""
# XXX this re-implements
# zope.app.publisher.browser.getDefaultViewName()
# to break our only dependency on it.
view_name = getSiteManager(None).adapters.lookup(
map(providedBy, (self.context, request)), IDefaultViewName)
if view_name is None:
raise ComponentLookupError("Couldn't find default view name",
self.context, request)
view_uri = "@@%s" % view_name
return self.context, (view_uri,)
class ItemTraverser(ContainerTraverser):
"""A traverser that knows how to look up objects by name in an item
container."""
__used_for__ = IItemContainer
def publishTraverse(self, request, name):
"""See zope.publisher.interfaces.IPublishTraverse"""
try:
return self.context[name]
except KeyError:
view = queryMultiAdapter((self.context, request), name=name)
if view is not None:
return view
raise NotFound(self.context, name, request)
_marker = object()
@implementer(ITraversable)
class ContainerTraversable:
"""Traverses containers via `getattr` and `get`."""
__used_for__ = IReadContainer
def __init__(self, container):
self._container = container
def traverse(self, name, furtherPath):
container = self._container
v = container.get(name, _marker)
if v is _marker:
try:
# Note that if name is a unicode string, getattr will
# implicitly try to encode it using the system
# encoding (usually ascii). Failure to encode means
# invalid attribute name.
v = getattr(container, name, _marker)
except UnicodeEncodeError:
raise TraversalError(container, name)
if v is _marker:
raise TraversalError(container, name)
return v | zope.container | /zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/traversal.py | traversal.py |
__docformat__ = 'restructuredtext'
import sys
import zope.schema
from zope.cachedescriptors.property import readproperty
from zope.dottedname.resolve import resolve
from zope.interface import providedBy
from zope.container.i18n import ZopeMessageFactory as _
from zope.container.interfaces import IContainer
from zope.container.interfaces import InvalidContainerType
from zope.container.interfaces import InvalidItemType
def checkObject(container, name, object):
"""Check containment constraints for an object and container
"""
# check __setitem__ precondition
containerProvided = providedBy(container)
__setitem__ = containerProvided.get('__setitem__')
if __setitem__ is not None:
precondition = __setitem__.queryTaggedValue('precondition')
if precondition is not None:
precondition(container, name, object)
# check that object is not being pasted into itself or its children.
target = container
while target is not None:
if target is object:
raise TypeError("Cannot add an object to itself or its children.")
if zope.location.interfaces.ILocation.providedBy(target):
target = target.__parent__
else:
target = None
# check the constraint on __parent__
__parent__ = providedBy(object).get('__parent__')
try:
validate = __parent__.validate
except AttributeError:
pass
else:
validate(container)
if not containerProvided.extends(IContainer):
# If it doesn't implement IContainer, it can't contain stuff.
raise TypeError(
_('Container is not a valid Zope container.')
)
def checkFactory(container, name, factory):
__setitem__ = providedBy(container).get('__setitem__')
try:
precondition = __setitem__.queryTaggedValue('precondition')
precondition = precondition.factory
except AttributeError:
pass
else:
try:
precondition(container, name, factory)
except zope.interface.Invalid:
return False
# check the constraint on __parent__
__parent__ = factory.getInterfaces().get('__parent__')
try:
validate = __parent__.validate
except AttributeError:
pass
else:
try:
validate(container)
except zope.interface.Invalid:
return False
return True
class IItemTypePrecondition(zope.interface.Interface):
def __call__(container, name, object):
"""Test whether container setitem arguments are valid.
Raise zope.interface.Invalid if the object is invalid.
"""
def factory(container, name, factory):
"""Test whether objects provided by the factory are acceptable
Return a boolean value.
"""
class _TypesBased:
@readproperty
def types(self):
raw_types, module = self.raw_types
types = []
for t in raw_types:
if isinstance(t, str):
t = resolve(t, module)
types.append(t)
self.types = types
return types
def __init__(self, *types, **kw):
if [t for t in types if isinstance(t, str)]:
# have dotted names
module = kw.get('module', sys._getframe(1).f_globals['__name__'])
self.raw_types = types, module
else:
self.types = types
@zope.interface.implementer(IItemTypePrecondition)
class ItemTypePrecondition(_TypesBased):
"""Specify a `__setitem__` precondition that restricts item types
Items must be one of the given types.
>>> class I1(zope.interface.Interface):
... pass
>>> class I2(zope.interface.Interface):
... pass
>>> precondition = ItemTypePrecondition(I1, I2)
>>> class Ob(object):
... pass
>>> ob = Ob()
>>> class Factory(object):
... def __call__(self):
... return Ob()
... def getInterfaces(self):
... return zope.interface.implementedBy(Ob)
>>> factory = Factory()
>>> try:
... precondition(None, 'foo', ob)
... except InvalidItemType as v:
... v.args[0], (v.args[1] is ob), (v.args[2] == (I1, I2))
... else:
... print('Should have failed')
(None, True, True)
>>> try:
... precondition.factory(None, 'foo', factory)
... except InvalidItemType as v:
... v.args[0], (v.args[1] is factory), (v.args[2] == (I1, I2))
... else:
... print('Should have failed')
(None, True, True)
>>> zope.interface.classImplements(Ob, I2)
>>> precondition(None, 'foo', ob)
>>> precondition.factory(None, 'foo', factory)
"""
def __call__(self, container, name, object):
for iface in self.types:
if iface.providedBy(object):
return
raise InvalidItemType(container, object, self.types)
def factory(self, container, name, factory):
implemented = factory.getInterfaces()
for iface in self.types:
if implemented.isOrExtends(iface):
return
raise InvalidItemType(container, factory, self.types)
def contains(*types):
"""Declare that a container type contains only the given types
This is used within a class suite defining an interface to create
a __setitem__ specification with a precondition allowing only the
given types:
>>> class IFoo(zope.interface.Interface):
... pass
>>> class IBar(zope.interface.Interface):
... pass
>>> class IFooBarContainer(IContainer):
... contains(IFoo, IBar)
>>> __setitem__ = IFooBarContainer['__setitem__']
>>> __setitem__.getTaggedValue('precondition').types == (IFoo, IBar)
True
It is invalid to call contains outside a class suite:
>>> contains(IFoo, IBar)
Traceback (most recent call last):
...
TypeError: contains not called from suite
"""
frame = sys._getframe(1)
f_locals = frame.f_locals
f_globals = frame.f_globals
if not (f_locals is not f_globals
and f_locals.get('__module__')
and f_locals.get('__module__') == f_globals.get('__name__')
):
raise TypeError("contains not called from suite")
def __setitem__(key, value):
"""
This serves as a copy of IContainer.__setitem__ to hold
the ``precondition`` attribute. Note that it replaces a local
__setitem__ defined before.
"""
__setitem__.__doc__ = IContainer['__setitem__'].__doc__
__setitem__.precondition = ItemTypePrecondition(
*types,
**dict(module=f_globals['__name__'])
)
f_locals['__setitem__'] = __setitem__
class IContainerTypesConstraint(zope.interface.Interface):
def __call__(object):
"""Test whether object is valid.
Return True if valid.
Raise zope.interface.Invalid if the objet is invalid.
"""
@zope.interface.implementer(IContainerTypesConstraint)
class ContainerTypesConstraint(_TypesBased):
"""Constrain a container to be one of a number of types
>>> class I1(zope.interface.Interface):
... pass
>>> class I2(zope.interface.Interface):
... pass
>>> class Ob(object):
... pass
>>> ob = Ob()
>>> constraint = ContainerTypesConstraint(I1, I2)
>>> try:
... constraint(ob)
... except InvalidContainerType as v:
... (v.args[0] is ob), (v.args[1] == (I1, I2))
... else:
... print('Should have failed')
(True, True)
>>> zope.interface.classImplements(Ob, I2)
>>> constraint(Ob())
True
"""
def __call__(self, object):
for iface in self.types:
if iface.providedBy(object):
return True
raise InvalidContainerType(object, self.types)
def containers(*types):
"""Declare the container types a type can be contained in
This is used within a class suite defining an interface to create
a __parent__ specification with a constraint allowing only the
given types:
>>> class IFoo(IContainer):
... pass
>>> class IBar(IContainer):
... pass
>>> from zope.location.interfaces import IContained
>>> class IFooBarContained(IContained):
... containers(IFoo, IBar)
>>> __parent__ = IFooBarContained['__parent__']
>>> __parent__.constraint.types == (IFoo, IBar)
True
It is invalid to call containers outside a class suite:
>>> containers(IFoo, IBar)
Traceback (most recent call last):
...
TypeError: containers not called from suite
"""
frame = sys._getframe(1)
f_locals = frame.f_locals
f_globals = frame.f_globals
if not (f_locals is not f_globals
and f_locals.get('__module__')
and f_locals.get('__module__') == f_globals.get('__name__')
):
raise TypeError("containers not called from suite")
__parent__ = zope.schema.Field(
constraint=ContainerTypesConstraint(
*types,
**dict(module=f_globals['__name__'])
)
)
f_locals['__parent__'] = __parent__ | zope.container | /zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/constraints.py | constraints.py |
"""This module provides a sample btree container implementation.
"""
__docformat__ = 'restructuredtext'
from BTrees.Length import Length
from BTrees.OOBTree import OOBTree
from persistent import Persistent
from zope.cachedescriptors.property import Lazy
from zope.interface import implementer
from zope.container.contained import Contained
from zope.container.contained import setitem
from zope.container.contained import uncontained
from zope.container.interfaces import IBTreeContainer
@implementer(IBTreeContainer)
class BTreeContainer(Contained, Persistent):
"""OOBTree-based container"""
def __init__(self):
# We keep the previous attribute to store the data
# for backward compatibility
self._SampleContainer__data = self._newContainerData()
self.__len = Length()
def _newContainerData(self):
"""Construct an item-data container
Subclasses should override this if they want different data.
The value returned is a mapping object that also has get,
has_key, keys, items, and values methods.
The default implementation uses an OOBTree.
"""
return OOBTree()
def __contains__(self, key):
"""See interface IReadContainer
"""
return key in self._SampleContainer__data
@Lazy
def _BTreeContainer__len(self):
l_ = Length()
ol = len(self._SampleContainer__data)
if ol > 0:
l_.change(ol)
self._p_changed = True
return l_
def __len__(self):
return self.__len()
def _setitemf(self, key, value):
# make sure our lazy property gets set
l_ = self.__len
self._SampleContainer__data[key] = value
l_.change(1)
def __iter__(self):
return iter(self._SampleContainer__data)
def __getitem__(self, key):
'''See interface `IReadContainer`'''
return self._SampleContainer__data[key]
def get(self, key, default=None):
'''See interface `IReadContainer`'''
return self._SampleContainer__data.get(key, default)
def __setitem__(self, key, value):
setitem(self, self._setitemf, key, value)
def __delitem__(self, key):
# make sure our lazy property gets set
l_ = self.__len
item = self._SampleContainer__data[key]
del self._SampleContainer__data[key]
l_.change(-1)
uncontained(item, self, key)
has_key = __contains__
def items(self, key=None):
return self._SampleContainer__data.items(key)
def keys(self, key=None):
return self._SampleContainer__data.keys(key)
def values(self, key=None):
return self._SampleContainer__data.values(key) | zope.container | /zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/btree.py | btree.py |
"""Classes to support implementing `IContained`
"""
# pylint:disable=too-many-lines
import zope.component
from zope.event import notify
from zope.interface import Interface
from zope.interface import implementedBy
from zope.interface import providedBy
from zope.interface.declarations import Provides
from zope.interface.declarations import getObjectSpecification
from zope.lifecycleevent import ObjectAddedEvent
from zope.lifecycleevent import ObjectModifiedEvent
from zope.lifecycleevent import ObjectMovedEvent
from zope.lifecycleevent import ObjectRemovedEvent
from zope.location.interfaces import IContained
from zope.location.interfaces import ILocation
from zope.location.interfaces import ISublocations
from zope.security.checker import CombinedChecker
from zope.security.checker import selectChecker
from zope.container._proxy import ContainedProxyBase
from zope.container._proxy import getProxiedObject
from zope.container.i18n import ZopeMessageFactory as _
from zope.container.interfaces import IContainerModifiedEvent
from zope.container.interfaces import INameChooser
from zope.container.interfaces import IReservedNames
from zope.container.interfaces import NameReserved
try:
from ZODB.interfaces import IBroken
except ImportError: # pragma: no cover
class IBroken(Interface): # pylint:disable=inherit-non-class
pass
@zope.interface.implementer(IContained)
class Contained:
"""
Simple mix-in that defines ``__parent__`` and ``__name__``
attributes and implements `IContained`.
"""
__parent__ = __name__ = None
@zope.interface.implementer(IContainerModifiedEvent)
class ContainerModifiedEvent(ObjectModifiedEvent):
"""The container has been modified."""
def dispatchToSublocations(object, event): # pylint:disable=redefined-builtin
"""Dispatch an event to sublocations of a given object
When a move event happens for an object, it's important to notify
subobjects as well.
We do this based on locations.
Suppose, for example, that we define some location objects.
>>> @zope.interface.implementer(ILocation)
... class L(object):
... def __init__(self, name):
... self.__name__ = name
... self.__parent__ = None
... def __repr__(self):
... return '%s(%s)' % (
... self.__class__.__name__, str(self.__name__))
>>> @zope.interface.implementer(ISublocations)
... class C(L):
... def __init__(self, name, *subs):
... L.__init__(self, name)
... self.subs = subs
... for sub in subs:
... sub.__parent__ = self
... def sublocations(self):
... return self.subs
>>> c = C(1,
... C(11,
... L(111),
... L(112),
... ),
... C(12,
... L(121),
... L(122),
... L(123),
... L(124),
... ),
... L(13),
... )
Now, if we call the dispatcher, it should call event handlers
for all of the objects.
Lets create an event handler that records the objects it sees:
>>> seen = []
>>> def handler(ob, event):
... seen.append((ob, event.object))
Note that we record the the object the handler is called on as
well as the event object:
Now we'll register it:
>>> from zope import component
>>> from zope.lifecycleevent.interfaces import IObjectMovedEvent
>>> component.provideHandler(handler, [None, IObjectMovedEvent])
We also register our dispatcher:
>>> component.provideHandler(dispatchToSublocations,
... [None, IObjectMovedEvent])
We can then call the dispatcher for the root object:
>>> event = ObjectRemovedEvent(c)
>>> dispatchToSublocations(c, event)
Now, we should have seen all of the subobjects:
>>> seenreprs = sorted(map(repr, seen))
>>> seenreprs
['(C(11), C(1))', '(C(12), C(1))', '(L(111), C(1))',""" \
""" '(L(112), C(1))', '(L(121), C(1))', '(L(122), C(1))',""" \
""" '(L(123), C(1))', '(L(124), C(1))', '(L(13), C(1))']
We see that we get entries for each of the subobjects and
that,for each entry, the event object is top object.
This suggests that location event handlers need to be aware that
the objects they are called on and the event objects could be
different.
"""
subs = ISublocations(object, None)
if subs is not None:
for sub in subs.sublocations():
zope.component.handle(sub, event)
class ContainerSublocations:
"""Get the sublocations for a container
Obviously, this is the container values:
>>> class MyContainer(object):
... def __init__(self, **data):
... self.data = data
... def __iter__(self):
... return iter(self.data)
... def __getitem__(self, key):
... return self.data[key]
>>> container = MyContainer(x=1, y=2, z=42)
>>> adapter = ContainerSublocations(container)
>>> sublocations = list(adapter.sublocations())
>>> sublocations.sort()
>>> sublocations
[1, 2, 42]
"""
def __init__(self, container):
self.container = container
def sublocations(self):
container = self.container
for key in container:
yield container[key]
def containedEvent(object, container, name=None):
"""Establish the containment of the object in the container
The object and necessary event are returned. The object may be a
`ContainedProxy` around the original object. The event is an added
event, a moved event, or None.
If the object implements `IContained`, simply set its ``__parent__``
and ``__name__`` attributes:
>>> container = {}
>>> item = Contained()
>>> x, event = containedEvent(item, container, 'foo')
>>> x is item
True
>>> item.__parent__ is container
True
>>> item.__name__
'foo'
We have an added event:
>>> event.__class__.__name__
'ObjectAddedEvent'
>>> event.object is item
True
>>> event.newParent is container
True
>>> event.newName
'foo'
>>> event.oldParent
>>> event.oldName
Now if we call contained again:
>>> x2, event = containedEvent(item, container, 'foo')
>>> x2 is item
True
>>> item.__parent__ is container
True
>>> item.__name__
'foo'
We don't get a new added event:
>>> event
If the object already had a parent but the parent or name was
different, we get a moved event:
>>> x, event = containedEvent(item, container, 'foo2')
>>> event.__class__.__name__
'ObjectMovedEvent'
>>> event.object is item
True
>>> event.newParent is container
True
>>> event.newName
'foo2'
>>> event.oldParent is container
True
>>> event.oldName
'foo'
If the *object* implements `ILocation`, but not `IContained`, set its
``__parent__`` and ``__name__`` attributes *and* declare that it
implements `IContained`:
>>> from zope.location import Location
>>> from zope.location.interfaces import IContained
>>> item = Location()
>>> IContained.providedBy(item)
False
>>> x, event = containedEvent(item, container, 'foo')
>>> x is item
True
>>> item.__parent__ is container
True
>>> item.__name__
'foo'
>>> IContained.providedBy(item)
True
If the *object* doesn't even implement `ILocation`, put a
`ContainedProxy` around it:
>>> item = []
>>> x, event = containedEvent(item, container, 'foo')
>>> x is item
False
>>> x.__parent__ is container
True
>>> x.__name__
'foo'
Make sure we don't lose existing directly provided interfaces.
>>> from zope.interface import Interface, directlyProvides
>>> class IOther(Interface):
... pass
>>> from zope.location import Location
>>> item = Location()
>>> directlyProvides(item, IOther)
>>> IOther.providedBy(item)
True
>>> x, event = containedEvent(item, container, 'foo')
>>> IOther.providedBy(item)
True
"""
if not IContained.providedBy(object):
if ILocation.providedBy(object):
zope.interface.alsoProvides(object, IContained)
else:
object = ContainedProxy(object)
oldparent = object.__parent__
oldname = object.__name__
if oldparent is container and oldname == name:
# No events
return object, None
object.__parent__ = container
object.__name__ = name
if oldparent is None or oldname is None:
event = ObjectAddedEvent(object, container, name)
else:
event = ObjectMovedEvent(object, oldparent, oldname, container, name)
return object, event
def contained(object, container, name=None):
"""Establish the containment of the object in the container
Just return the contained object without an event. This is a convenience
"macro" for:
``containedEvent(object, container, name)[0]``
This function is only used for tests.
"""
return containedEvent(object, container, name)[0]
def notifyContainerModified(object, *descriptions):
"""Notify that the container was modified."""
notify(ContainerModifiedEvent(object, *descriptions))
_SENTINEL = object()
def checkAndConvertName(name):
# Basic name checks, including converting bytes to text.
# Not a documented public API function.
if isinstance(name, bytes):
try:
name = name.decode('ascii')
except UnicodeError:
raise TypeError("name not unicode or ascii string")
elif not isinstance(name, str):
raise TypeError("name not unicode or ascii string")
if not name:
raise ValueError("empty names are not allowed")
return name
def setitem(container, setitemf, name, object):
r"""Helper function to set an item and generate needed events
This helper is needed, in part, because the events need to get
published after the *object* has been added to the *container*.
If the item implements `IContained`, simply set its ``__parent__``
and ``__name__`` attributes:
>>> class IItem(zope.interface.Interface):
... pass
>>> @zope.interface.implementer(IItem)
... class Item(Contained):
... def setAdded(self, event):
... self.added = event
... def setMoved(self, event):
... self.moved = event
>>> from zope.lifecycleevent.interfaces import IObjectAddedEvent
>>> from zope.lifecycleevent.interfaces import IObjectMovedEvent
>>> from zope import component
>>> component.provideHandler(lambda obj, event: obj.setAdded(event),
... [IItem, IObjectAddedEvent])
>>> component.provideHandler(lambda obj, event: obj.setMoved(event),
... [IItem, IObjectMovedEvent])
>>> item = Item()
>>> container = {}
>>> setitem(container, container.__setitem__, 'c', item)
>>> container['c'] is item
True
>>> item.__parent__ is container
True
>>> item.__name__
'c'
If we run this using the testing framework, we'll use `getEvents` to
track the events generated:
>>> from zope.component.eventtesting import getEvents
>>> from zope.lifecycleevent.interfaces import IObjectModifiedEvent
We have an added event:
>>> len(getEvents(IObjectAddedEvent))
1
>>> event = getEvents(IObjectAddedEvent)[-1]
>>> event.object is item
True
>>> event.newParent is container
True
>>> event.newName
'c'
>>> event.oldParent
>>> event.oldName
As well as a modification event for the container:
>>> len(getEvents(IObjectModifiedEvent))
1
>>> getEvents(IObjectModifiedEvent)[-1].object is container
1
The item's hooks have been called:
>>> item.added is event
1
>>> item.moved is event
1
We can suppress events and hooks by setting the ``__parent__`` and
``__name__`` first:
>>> item = Item()
>>> item.__parent__, item.__name__ = container, 'c2'
>>> setitem(container, container.__setitem__, 'c2', item)
>>> len(container)
2
>>> len(getEvents(IObjectAddedEvent))
1
>>> len(getEvents(IObjectModifiedEvent))
1
>>> getattr(item, 'added', None)
>>> getattr(item, 'moved', None)
If the item had a parent or name (as in a move or rename),
we generate a move event, rather than an add event:
>>> setitem(container, container.__setitem__, 'c3', item)
>>> len(container)
3
>>> len(getEvents(IObjectAddedEvent))
1
>>> len(getEvents(IObjectModifiedEvent))
2
>>> len(getEvents(IObjectMovedEvent))
2
(Note that we have 2 move events because add are move events.)
We also get the move hook called, but not the add hook:
>>> event = getEvents(IObjectMovedEvent)[-1]
>>> getattr(item, 'added', None)
>>> item.moved is event
1
If we try to replace an item without deleting it first, we'll get
an error:
>>> setitem(container, container.__setitem__, 'c', [])
Traceback (most recent call last):
...
KeyError: 'c'
>>> del container['c']
>>> setitem(container, container.__setitem__, 'c', [])
>>> len(getEvents(IObjectAddedEvent))
2
>>> len(getEvents(IObjectModifiedEvent))
3
If the object implements `ILocation`, but not `IContained`, set it's
``__parent__`` and ``__name__`` attributes *and* declare that it
implements `IContained`:
>>> from zope.location import Location
>>> item = Location()
>>> IContained.providedBy(item)
0
>>> setitem(container, container.__setitem__, 'l', item)
>>> container['l'] is item
1
>>> item.__parent__ is container
1
>>> item.__name__
'l'
>>> IContained.providedBy(item)
1
We get new added and modification events:
>>> len(getEvents(IObjectAddedEvent))
3
>>> len(getEvents(IObjectModifiedEvent))
4
If the object doesn't even implement `ILocation`, put a
`ContainedProxy` around it:
>>> item = []
>>> setitem(container, container.__setitem__, 'i', item)
>>> container['i']
[]
>>> container['i'] is item
0
>>> item = container['i']
>>> item.__parent__ is container
1
>>> item.__name__
'i'
>>> IContained.providedBy(item)
1
>>> len(getEvents(IObjectAddedEvent))
4
>>> len(getEvents(IObjectModifiedEvent))
5
We'll get type errors if we give keys that aren't unicode or ascii keys:
>>> setitem(container, container.__setitem__, 42, item)
Traceback (most recent call last):
...
TypeError: name not unicode or ascii string
>>> setitem(container, container.__setitem__, None, item)
Traceback (most recent call last):
...
TypeError: name not unicode or ascii string
>>> setitem(container, container.__setitem__, b'hello \xc8', item)
Traceback (most recent call last):
...
TypeError: name not unicode or ascii string
and we'll get a value error of we give an empty string or unicode:
>>> setitem(container, container.__setitem__, '', item)
Traceback (most recent call last):
...
ValueError: empty names are not allowed
>>> setitem(container, container.__setitem__, '', item)
Traceback (most recent call last):
...
ValueError: empty names are not allowed
"""
# Do basic name check:
name = checkAndConvertName(name)
old = container.get(name, _SENTINEL)
if old is object:
return
if old is not _SENTINEL:
raise KeyError(name)
object, event = containedEvent(object, container, name)
setitemf(name, object)
if event:
notify(event)
notifyContainerModified(container)
fixing_up = False
def uncontained(object, container, name=None):
"""Clear the containment relationship between the *object* and
the *container*.
If we run this using the testing framework, we'll use `getEvents` to
track the events generated:
>>> from zope.component.eventtesting import getEvents
>>> from zope.lifecycleevent.interfaces import IObjectModifiedEvent
>>> from zope.lifecycleevent.interfaces import IObjectRemovedEvent
We'll start by creating a container with an item:
>>> class Item(Contained):
... pass
>>> item = Item()
>>> container = {'foo': item}
>>> x, event = containedEvent(item, container, 'foo')
>>> item.__parent__ is container
1
>>> item.__name__
'foo'
Now we'll remove the item. It's parent and name are cleared:
>>> uncontained(item, container, 'foo')
>>> item.__parent__
>>> item.__name__
We now have a new removed event:
>>> len(getEvents(IObjectRemovedEvent))
1
>>> event = getEvents(IObjectRemovedEvent)[-1]
>>> event.object is item
1
>>> event.oldParent is container
1
>>> event.oldName
'foo'
>>> event.newParent
>>> event.newName
As well as a modification event for the container:
>>> len(getEvents(IObjectModifiedEvent))
1
>>> getEvents(IObjectModifiedEvent)[-1].object is container
1
Now if we call uncontained again:
>>> uncontained(item, container, 'foo')
We won't get any new events, because __parent__ and __name__ are None:
>>> len(getEvents(IObjectRemovedEvent))
1
>>> len(getEvents(IObjectModifiedEvent))
1
But, if either the name or parent are not ``None`` and they are not the
container and the old name, we'll get a modified event but not a removed
event.
>>> item.__parent__, item.__name__ = container, None
>>> uncontained(item, container, 'foo')
>>> len(getEvents(IObjectRemovedEvent))
1
>>> len(getEvents(IObjectModifiedEvent))
2
>>> item.__parent__, item.__name__ = None, 'bar'
>>> uncontained(item, container, 'foo')
>>> len(getEvents(IObjectRemovedEvent))
1
>>> len(getEvents(IObjectModifiedEvent))
3
If one tries to delete a Broken object, we allow them to do
just that.
>>> class Broken(object):
... __Broken_state__ = {}
>>> broken = Broken()
>>> broken.__Broken_state__['__name__'] = 'bar'
>>> broken.__Broken_state__['__parent__'] = container
>>> container['bar'] = broken
>>> uncontained(broken, container, 'bar')
>>> len(getEvents(IObjectRemovedEvent))
2
"""
try:
oldparent = object.__parent__
oldname = object.__name__
except AttributeError:
# The old object doesn't implements IContained
# Maybe we're converting old data:
if hasattr(object, '__Broken_state__'):
state = object.__Broken_state__
oldparent = state['__parent__']
oldname = state['__name__']
else:
if not fixing_up:
raise
oldparent = None
oldname = None
if oldparent is not container or oldname != name:
if oldparent is not None or oldname is not None:
notifyContainerModified(container)
return
event = ObjectRemovedEvent(object, oldparent, oldname)
notify(event)
if not IBroken.providedBy(object):
object.__parent__ = None
object.__name__ = None
notifyContainerModified(container)
@zope.interface.implementer(INameChooser)
class NameChooser:
def __init__(self, context):
self.context = context
def checkName(self, name, object): # pylint:disable=redefined-builtin
"""See zope.container.interfaces.INameChooser
We create and populate a dummy container
>>> from zope.container.sample import SampleContainer
>>> container = SampleContainer()
>>> container['foo'] = 'bar'
>>> from zope.container.contained import NameChooser
An invalid name raises a ValueError:
>>> NameChooser(container).checkName('+foo', object())
Traceback (most recent call last):
...
ValueError: Names cannot begin with '+' or '@' or contain '/'
A name that already exists raises a KeyError:
>>> NameChooser(container).checkName('foo', object())
Traceback (most recent call last):
...
KeyError: 'The given name is already being used'
A name must be a string or unicode string:
>>> NameChooser(container).checkName(2, object())
Traceback (most recent call last):
...
TypeError: ('Invalid name type', <class 'int'>)
A correct name returns True:
>>> NameChooser(container).checkName('2', object())
True
We can reserve some names by providing a IReservedNames adapter
to a container:
>>> from zope.container.interfaces import IContainer
>>> @zope.component.adapter(IContainer)
... @zope.interface.implementer(IReservedNames)
... class ReservedNames(object):
...
... def __init__(self, context):
... self.reservedNames = set(('reserved', 'other'))
>>> zope.component.getSiteManager().registerAdapter(ReservedNames)
>>> NameChooser(container).checkName('reserved', None)
Traceback (most recent call last):
...
zope.container.interfaces.NameReserved: reserved
"""
if isinstance(name, bytes):
name = name.decode('ascii')
elif not isinstance(name, str):
raise TypeError("Invalid name type", type(name))
if not name:
raise ValueError(
_("An empty name was provided. Names cannot be empty.")
)
if name[:1] in '+@' or '/' in name:
raise ValueError(
_("Names cannot begin with '+' or '@' or contain '/'")
)
reserved = IReservedNames(self.context, None)
if reserved is not None:
if name in reserved.reservedNames:
raise NameReserved(name)
if name in self.context:
raise KeyError(
_("The given name is already being used")
)
return True
def chooseName(self, name, object): # pylint:disable=redefined-builtin
"""See zope.container.interfaces.INameChooser
The name chooser is expected to choose a name without error
We create and populate a dummy container
>>> from zope.container.sample import SampleContainer
>>> container = SampleContainer()
>>> container['foobar.old'] = 'rst doc'
>>> from zope.container.contained import NameChooser
the suggested name is converted to unicode:
>>> NameChooser(container).chooseName('foobar', object())
'foobar'
>>> NameChooser(container).chooseName(b'foobar', object())
'foobar'
If it already exists, a number is appended but keeps the same
extension:
>>> NameChooser(container).chooseName('foobar.old', object())
'foobar-2.old'
Bad characters are turned into dashes:
>>> NameChooser(container).chooseName('foo/foo', object())
'foo-foo'
If no name is suggested, it is based on the object type:
>>> NameChooser(container).chooseName('', [])
'list'
"""
container = self.context
# convert to unicode and remove characters that checkName does not
# allow
if isinstance(name, bytes):
name = name.decode('ascii')
if not isinstance(name, str):
try:
name = str(name)
except Exception:
name = ''
name = name.replace('/', '-').lstrip('+@')
if not name:
name = object.__class__.__name__
if isinstance(name, bytes):
name = name.decode('ascii')
# for an existing name, append a number.
# We should keep client's os.path.extsep (not ours), we assume it's '.'
dot = name.rfind('.')
if dot >= 0:
suffix = name[dot:]
name = name[:dot]
else:
suffix = ''
n = name + suffix
i = 1
while n in container:
i += 1
n = name + '-' + str(i) + suffix
# Make sure the name is valid. We may have started with something bad.
self.checkName(n, object)
return n
class DecoratorSpecificationDescriptor(
zope.interface.declarations.ObjectSpecificationDescriptor):
"""Support for interface declarations on decorators
>>> from zope.interface import Interface, directlyProvides, implementer
>>> class I1(Interface):
... pass
>>> class I2(Interface):
... pass
>>> class I3(Interface):
... pass
>>> class I4(Interface):
... pass
>>> @implementer(I1)
... class D1(ContainedProxy):
... pass
>>> @implementer(I2)
... class D2(ContainedProxy):
... pass
>>> @implementer(I3)
... class X:
... pass
>>> x = X()
>>> directlyProvides(x, I4)
Interfaces of X are ordered with the directly-provided interfaces first
>>> [interface.getName() for interface in list(providedBy(x))]
['I4', 'I3']
When we decorate objects, what order should the interfaces come in? One
could argue that decorators are less specific, so they should come last.
This is subject to respecting the C3 resolution order, of course.
>>> [interface.getName() for interface in list(providedBy(D1(x)))]
['I4', 'I3', 'I1', 'IContained', 'IPersistent']
>>> [interface.getName() for interface in list(providedBy(D2(D1(x))))]
['I4', 'I3', 'I1', 'I2', 'IContained', 'IPersistent']
"""
def __get__(self, inst, cls=None):
if inst is None: # pragma: no cover (Not sure how we can get here)
return getObjectSpecification(cls)
provided = providedBy(getProxiedObject(inst))
# Use type rather than __class__ because inst is a proxy and
# will return the proxied object's class.
cls = type(inst)
implemented_by_cls = implementedBy(cls)
for iface in list(provided):
if implemented_by_cls.isOrExtends(iface):
provided = provided - iface
return Provides(cls, provided)
class DecoratedSecurityCheckerDescriptor:
"""
Descriptor for a Decorator that provides a decorated security
checker.
>>> class WithChecker(object):
... __Security_checker__ = object()
>>> class D1(ContainedProxy):
... pass
>>> d = D1(object())
>>> d.__Security_checker__ # doctest: +ELLIPSIS
<...Checker...>
An existing checker is added to this one:
>>> d = D1(WithChecker())
>>> d.__Security_checker__ # doctest: +ELLIPSIS
<...CombinedChecker...>
"""
def __get__(self, inst, cls=None):
if inst is None: # pragma: no cover (Not sure how we can get here)
return self
proxied_object = getProxiedObject(inst)
checker = getattr(proxied_object, '__Security_checker__', None)
if checker is None:
checker = selectChecker(proxied_object)
wrapper_checker = selectChecker(inst)
if wrapper_checker is None: # pragma: no cover
return checker
if checker is None:
return wrapper_checker
return CombinedChecker(wrapper_checker, checker)
class ContainedProxyClassProvides(zope.interface.declarations.ClassProvides):
"""
Delegates __provides__ to the instance.
>>> class D1(ContainedProxy):
... pass
>>> class Base(object):
... pass
>>> base = Base()
>>> d = D1(base)
>>> d.__provides__ = 42
>>> base.__provides__
42
>>> del d.__provides__
>>> hasattr(base, '__provides__')
False
"""
def __set__(self, inst, value):
inst = getProxiedObject(inst)
inst.__provides__ = value
def __delete__(self, inst):
# CPython can hit this, PyPy/PURE_PYTHON cannot
inst = getProxiedObject(inst)
del inst.__provides__
@zope.interface.implementer(IContained)
class ContainedProxy(ContainedProxyBase):
"""
Wraps an object to implement :class:`zope.container.interfaces.IContained`
with a new ``__name__`` and ``__parent__``.
The new object provides everything the wrapped object did, plus
`IContained` and `IPersistent`.
"""
# Prevent proxies from having their own instance dictionaries:
__slots__ = ()
__safe_for_unpickling__ = True
__providedBy__ = zope.proxy.non_overridable(
DecoratorSpecificationDescriptor())
__Security_checker__ = zope.proxy.non_overridable(
DecoratedSecurityCheckerDescriptor())
ContainedProxy.__provides__ = ContainedProxyClassProvides(ContainedProxy, type) | zope.container | /zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/contained.py | contained.py |
"""Provider TALES expression"""
import zope.component
import zope.event
import zope.interface
import zope.schema
from zope.location.interfaces import ILocation
from zope.tales import expressions
from zope.contentprovider import interfaces
def addTALNamespaceData(provider, context):
"""Add the requested TAL attributes to the provider"""
data = {}
for interface in zope.interface.providedBy(provider):
if interfaces.ITALNamespaceData.providedBy(interface):
for name, field in zope.schema.getFields(interface).items():
data[name] = context.vars.get(name, field.default)
provider.__dict__.update(data)
@zope.interface.implementer(interfaces.ITALESProviderExpression)
class TALESProviderExpression(expressions.StringExpr):
"""
Collect content provider via a TAL namespace.
Note that this implementation of the TALES ``provider`` namespace
does not work with interdependent content providers, since each
content-provider's stage one call is made just before the second
stage is executed. If you want to implement interdependent
content providers, you need to consider a TAL-independent view
implementation such as zope.viewlet that will complete all content
providers' stage one before rendering any of them.
Implements `zope.contentprovider.interfaces.ITALESProviderExpression`
"""
def __call__(self, econtext):
name = super().__call__(econtext)
context = econtext.vars['context']
request = econtext.vars['request']
view = econtext.vars['view']
# Try to look up the provider.
provider = zope.component.queryMultiAdapter(
(context, request, view), interfaces.IContentProvider, name)
# Provide a useful error message, if the provider was not found.
if provider is None:
raise interfaces.ContentProviderLookupError(name)
# add the __name__ attribute if it implements ILocation
if ILocation.providedBy(provider):
provider.__name__ = name
# Insert the data gotten from the context
addTALNamespaceData(provider, econtext)
# Stage 1: Do the state update.
zope.event.notify(interfaces.BeforeUpdateEvent(provider, request))
provider.update()
# Stage 2: Render the HTML content.
return provider.render() | zope.contentprovider | /zope.contentprovider-5.0-py3-none-any.whl/zope/contentprovider/tales.py | tales.py |
"""Content provider interfaces"""
import zope.component
import zope.interface
from zope.interface.interfaces import IObjectEvent
from zope.interface.interfaces import ObjectEvent
from zope.publisher.interfaces import browser
from zope.tales import interfaces
class IUpdateNotCalled(zope.interface.common.interfaces.IRuntimeError):
"""Update Not Called
An error that is raised when any content provider method is called before
the ``update()`` method.
"""
class UpdateNotCalled(RuntimeError):
"""Default implementation of `IUpdateNotCalled`."""
def __init__(self, *args):
if not args:
args = ('``update()`` was not called yet.',)
super().__init__(*args)
class IBeforeUpdateEvent(IObjectEvent):
"""A content provider will be updated"""
request = zope.interface.Attribute(
"""The request in which the object is udpated, might also be
None""")
@zope.interface.implementer(IBeforeUpdateEvent)
class BeforeUpdateEvent(ObjectEvent):
"""Default implementation of `IBeforeUpdateEvent`."""
def __init__(self, provider, request=None):
super().__init__(provider)
self.request = request
class IContentProvider(browser.IBrowserView):
"""A piece of content to be shown on a page.
Objects implementing this interface are providing HTML content when they
are rendered. It is up to the implementation to decide how to lookup
necessary data to complete the job.
Content Providers use a two-stage process to fulfill their contract:
(1) The first stage is responsible to calculate the state of the content
provider and, if applicable, edit the data. This stage is executed
using the :meth:`update` method.
(2) During the second stage the provider constructs/renders its HTML
output based on the state that was calculated in the first stage. This
stage is executed using the :meth:`render` method.
Content Providers are discriminated by three components: the context, the
request and the view. This allows great control over the selection of the
provider.
"""
__parent__ = zope.interface.Attribute(
"""The view the provider appears in.
The view is the third discriminator of the content provider. It allows
that the content can be controlled for different views.
Having it stored as the parent is also very important for the security
context to be kept.
""")
def update():
"""Initialize the content provider.
This method should perform all state calculation and *not* refer it to
the rendering stage.
In this method, all state must be calculated from the current
interaction (e.g., the browser request); all contained or managed
content providers must have ``update()`` be called as well; any
additional stateful API for contained or managed content providers
must be handled; and persistent objects should be modified, if the
provider is going to do it.
Do *not* store state about persistent objects: the rendering process
should actually use the persistent objects for the data, in case other
components modify the object between the update and render stages.
This method *must* be called before any other method that mutates the
instance (besides the class constructor). Non-mutating methods and
attributes may raise an error if used before ``update()`` is
called. The view may rely on this order but is *not required* to
explicitly enforce this. Implementations *may* enforce it as a
developer aid.
"""
def render(*args, **kw):
"""Return the content provided by this content provider.
Calling this method before :meth:`update` *may* (but is not required
to) raise an `UpdateNotCalled` error.
"""
class IContentProviderType(zope.interface.interfaces.IInterface):
"""Type interface for content provider types
(interfaces derived from IContentProvider).
"""
class ITALNamespaceData(zope.interface.interfaces.IInterface):
"""A type interface that marks an interface as a TAL data specification.
All fields specified in an interface that provides `ITALNamespaceData`
will be looked up in the TAL context and stored on the content provider. A
content provider can have multiple interfaces that are of this type.
"""
class ContentProviderLookupError(zope.component.ComponentLookupError):
"""No content provider was found."""
class ITALESProviderExpression(interfaces.ITALESExpression):
"""Return the HTML content of the named provider.
To call a content provider in a view use the the following syntax in a page
template::
<tal:block replace="structure provider:provider.name">
The content provider is looked up by the (context, request, view) objects
and the name (``provider.name``).
""" | zope.contentprovider | /zope.contentprovider-5.0-py3-none-any.whl/zope/contentprovider/interfaces.py | interfaces.py |
__docformat__ = "reStructuredText"
import re
# TODO: This still needs to support comments in structured fields as
# specified in RFC 2822.
def parse(string):
"""
Parse the given string as a MIME type.
This uses :func:`parseOrdered` and can raise the same
exceptions it does.
:return: A tuple ``(major, minor, params)`` where ``major``
and ``minor`` are the two parts of the type, and ``params``
is a dictionary containing any parameters by name.
:param str string: The string to parse.
"""
major, minor, params = parseOrdered(string)
d = {}
for (name, value) in params:
d[name] = value
return major, minor, d
def parseOrdered(string):
"""
Parse the given string as a MIME type.
:return: A tuple ``(major, minor, params)`` where ``major``
and ``minor`` are the two parts of the type, and ``params`` is a
sequence of the parameters in order.
:raises ValueError: If the *string* is malformed.
:param str string: The string to parse.
"""
if ";" in string:
type, params = string.split(";", 1)
params = _parse_params(params)
else:
type = string
params = []
if "/" not in type:
raise ValueError("content type missing major/minor parts: %r" % type)
type = type.strip()
major, minor = type.lower().split("/", 1)
return _check_token(major.strip()), _check_token(minor.strip()), params
def _parse_params(string):
result = []
string = string.strip()
while string:
if "=" not in string:
raise ValueError("parameter values are not optional")
name, rest = string.split("=", 1)
name = _check_token(name.strip().lower())
rest = rest.strip()
# rest is: value *[";" parameter]
if rest[:1] == '"':
# quoted-string, defined in RFC 822.
m = _quoted_string_match(rest)
if m is None:
raise ValueError("invalid quoted-string in %r" % rest)
value = m.group()
rest = rest[m.end():].strip()
if rest[:1] not in ("", ";"):
raise ValueError(
"invalid token following quoted-string: %r" % rest)
rest = rest[1:]
value = _unescape(value)
elif ";" in rest:
value, rest = rest.split(";")
value = _check_token(value.strip())
else:
value = _check_token(rest.strip())
rest = ""
result.append((name, value))
string = rest.strip()
return result
_quoted_string_match = re.compile('"(?:\\\\.|[^"\n\r\\\\])*"', re.DOTALL).match
_token_match = re.compile("[^][ \t\n\r()<>@,;:\"/?=\\\\]+$").match
def _check_token(string):
if _token_match(string) is None:
raise ValueError('"%s" is not a valid token' % string)
return string
def _unescape(string):
assert string[0] == '"'
assert string[-1] == '"'
string = string[1:-1]
if "\\" in string:
string = re.sub(r"\\(.)", r"\1", string)
return string
def join(spec):
"""
Given a three-part tuple as produced by :func:`parse` or
:func:`parseOrdered`, return the string representation.
:returns: The string representation. For example, given ``('text', 'plain',
[('encoding','utf-8')])``, this will produce
``'text/plain;encoding=utf-8'``.
:rtype: str
"""
(major, minor, params) = spec
pstr = ""
try:
params.items
except AttributeError:
pass
else:
params = params.items()
# ensure a predictable order:
params = sorted(params)
for name, value in params:
pstr += ";{}={}".format(name, _escape(value))
return "{}/{}{}".format(major, minor, pstr)
def _escape(string):
try:
return _check_token(string)
except ValueError:
# '\\' must be first
for c in '\\"\n\r':
string = string.replace(c, "\\" + c)
return '"%s"' % string | zope.contenttype | /zope.contenttype-5.0-py3-none-any.whl/zope/contenttype/parse.py | parse.py |
import mimetypes
import os.path
import re
find_binary = re.compile(b'[\0-\7]').search
def text_type(s):
"""
Given an unnamed piece of data, try to guess its content type.
Detects HTML, XML, and plain text.
:return: A MIME type string such as 'text/html'.
:rtype: str
:param bytes s: The binary data to examine.
"""
# at least the maximum length of any tags we look for
max_tags = 14
s2 = s.strip()[:max_tags].lower()
if len(s2) == max_tags:
if s2.startswith(b'<html>'):
return 'text/html'
if s2.startswith(b'<!doctype html'):
return 'text/html'
# what about encodings??
if s2.startswith(b'<?xml'):
return 'text/xml'
# we also recognize small snippets of HTML - the closing tag might be
# anywhere, even at the end of
if b'</' in s:
return 'text/html'
return 'text/plain'
def guess_content_type(name='', body=b'', default=None):
"""
Given a named piece of content, try to guess its content type.
The implementation relies on the :mod:`mimetypes` standard Python module,
the :func:`text_type` function also defined in this module, and a simple
heuristic for detecting binary data.
:return: A tuple of ``(type, encoding)`` like :func:`mimetypes.guess_type`.
:keyword str name: The file name for the content. This is given priority
when guessing the type.
:keyword bytes body: The binary data of the content.
:keyword str default: If given, and no content type can be guessed, this
will be returned as the ``type`` portion.
"""
# Attempt to determine the content type (and possibly
# content-encoding) based on an an object's name and
# entity body.
type, enc = mimetypes.guess_type(name)
if type is None:
if body:
if find_binary(body) is not None:
type = default or 'application/octet-stream'
else:
type = (default or text_type(body)
or 'text/x-unknown-content-type')
else:
type = default or 'text/x-unknown-content-type'
return type.lower(), enc.lower() if enc else None
def add_files(filenames):
"""
Add the names of MIME type map files to the standard :mod:`mimetypes`
module.
MIME type map files are used for detecting the MIME type of some content
based on the content's filename extension.
The files should be formatted similarly to the 'mime.types' file
included in this package. Each line specifies a MIME type and the
file extensions that imply that MIME type. Here are some sample lines::
text/css css
text/plain bat c h pl ksh
text/x-vcard vcf
"""
# Make sure the additional files are either loaded or scheduled to
# be loaded:
if mimetypes.inited:
# Re-initialize the mimetypes module, loading additional files
mimetypes.init(filenames)
else:
# Tell the mimetypes module about the additional files so
# when it is initialized, it will pick up all of them, in
# the right order.
mimetypes.knownfiles.extend(filenames)
# Provide definitions shipped as part of Zope:
here = os.path.dirname(os.path.abspath(__file__))
add_files([os.path.join(here, "mime.types")])
def main():
items = mimetypes.types_map.items()
items = sorted(items)
for item in items:
print("%s:\t%s" % item) | zope.contenttype | /zope.contenttype-5.0-py3-none-any.whl/zope/contenttype/__init__.py | __init__.py |
=========
Changes
=========
4.3 (2022-11-29)
================
- Add support for Python 3.8, 3.9, 3.10, 3.11.
- Drop support for Python 3.4.
4.2 (2018-10-04)
================
- Use the latest and fastest protocol when pickling and unpickling and object
during the clone operation
- Add support for Python 3.7.
4.1.0 (2017-07-31)
==================
- Drop support for Python 2.6, 3.2 and 3.3.
- Add support for Python 3.5 and 3.6.
- Restore ``zope.component`` as a testing requirement for running doctests.
4.0.3 (2014-12-26)
==================
- Add support for PyPy3.
4.0.2 (2014-03-19)
==================
- Add support for Python 3.3 and 3.4.
- Update ``boostrap.py`` to version 2.2.
4.0.1 (2012-12-31)
==================
- Flesh out PyPI Trove classifiers.
4.0.0 (2012-06-13)
==================
- Add support for Python 3.2.
- Drop ``zope.component`` as a testing requirement. Instead, register
explicit (dummy) adapter hooks where needed.
- Add PyPy support.
- 100% unit test coverage.
- Add support for continuous integration using ``tox`` and ``jenkins``.
- Add Sphinx documentation: moved doctest examples to API reference.
- Add 'setup.py docs' alias (installs ``Sphinx`` and dependencies).
- Add 'setup.py dev' alias (runs ``setup.py develop`` plus installs
``nose``, ``coverage``, and testing dependencies).
- Drop support for Python 2.4 and 2.5.
- Include tests of the LocationCopyHook from zope.location.
3.5.0 (2009-02-09)
==================
- Initial release. The functionality was extracted from ``zc.copy`` to
provide a generic object copying mechanism with minimal dependencies.
| zope.copy | /zope.copy-4.3.tar.gz/zope.copy-4.3/CHANGES.rst | CHANGES.rst |
===============
``zope.copy``
===============
.. image:: https://img.shields.io/pypi/v/zope.copy.svg
:target: https://pypi.python.org/pypi/zope.copy/
:alt: Latest release
.. image:: https://img.shields.io/pypi/pyversions/zope.copy.svg
:target: https://pypi.org/project/zope.copy/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/zope.copy/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/zope.copy/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/zope.copy/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/zope.copy?branch=master
.. image:: https://readthedocs.org/projects/zopecopy/badge/?version=latest
:target: http://zopecopy.readthedocs.org/en/latest/
:alt: Documentation Status
This package provides a pluggable mechanism for copying persistent objects.
Documentation is hosted at https://zopecopy.readthedocs.io/
| zope.copy | /zope.copy-4.3.tar.gz/zope.copy-4.3/README.rst | README.rst |
import tempfile
from zope.copy import interfaces
from zope.copy._compat import Pickler
from zope.copy._compat import Unpickler
from zope.copy._compat import _get_obj
from zope.copy._compat import _get_pid
def clone(obj):
"""Clone an object by pickling and unpickling it"""
with tempfile.TemporaryFile() as tmp:
persistent = CopyPersistent(obj)
# Pickle the object to a temporary file
pickler = Pickler(tmp, protocol=-1)
pickler.persistent_id = persistent.id
pickler.dump(obj)
# Now load it back
tmp.seek(0)
unpickler = Unpickler(tmp)
unpickler.persistent_load = persistent.load
res = unpickler.load()
# run the registered cleanups
def convert(obj):
pid = _get_pid(pickler, id(obj))
try:
return _get_obj(unpickler, pid)
except KeyError: # pragma: no cover (PyPy)
return _get_obj(unpickler, str(pid))
for call in persistent.registered:
call(convert)
return res
def copy(obj):
"""Clone an object, clearing the __name__ and __parent__ attribute
values of the copy."""
res = clone(obj)
if getattr(res, '__parent__', None) is not None:
try:
res.__parent__ = None
except AttributeError:
pass
if getattr(res, '__name__', None) is not None:
try:
res.__name__ = None
except AttributeError:
pass
return res
class CopyPersistent(object):
"""A helper class providing the persisntent_id and persistent_load
functions for pickling and unpickling respectively.
It uses the adaptation to ICopyHook to allow control over object
copying. See README.txt for more information on that mechanism.
"""
def __init__(self, obj):
self.toplevel = obj
self.pids_by_id = {}
self.others_by_pid = {}
self.load = self.others_by_pid.get
self.registered = []
def id(self, obj):
hook = interfaces.ICopyHook(obj, None)
if hook is not None:
oid = id(obj)
if oid in self.pids_by_id:
return self.pids_by_id[oid]
try:
res = hook(self.toplevel, self.registered.append)
except interfaces.ResumeCopy:
pass
else:
pid = len(self.others_by_pid)
# The following is needed to overcome a bug
# in pickle.py. The pickle checks the boolean value
# of the id, rather than whether it is None.
pid += 1
self.pids_by_id[oid] = pid
self.others_by_pid[pid] = res
return pid
return None | zope.copy | /zope.copy-4.3.tar.gz/zope.copy-4.3/src/zope/copy/__init__.py | __init__.py |
Hacking on :mod:`zope.copy`
===========================
Getting the Code
################
The main repository for :mod:`zope.copy` is in the Zope Foundation
Github repository:
https://github.com/zopefoundation/zope.copy
You can get a read-only checkout from there:
.. code-block:: sh
$ git clone https://github.com/zopefoundation/zope.copy.git
or fork it and get a writeable checkout of your fork:
.. code-block:: sh
$ git clone [email protected]/jrandom/zope.copy.git
The project also mirrors the trunk from the Github repository as a
Bazaar branch on Launchpad:
https://code.launchpad.net/zope.copy
You can branch the trunk from there using Bazaar:
.. code-block:: sh
$ bzr branch lp:zope.copy
Working in a ``virtualenv``
###########################
Installing
----------
If you use the ``virtualenv`` package to create lightweight Python
development environments, you can run the tests using nothing more
than the ``python`` binary in a virtualenv. First, create a scratch
environment:
.. code-block:: sh
$ /path/to/virtualenv --no-site-packages /tmp/hack-zope.copy
Next, get this package registered as a "development egg" in the
environment:
.. code-block:: sh
$ /tmp/hack-zope.copy/bin/python setup.py develop
Running the tests
-----------------
Then, you canrun the tests using the build-in ``setuptools`` testrunner:
.. code-block:: sh
$ /tmp/hack-zope.copy/bin/python setup.py test -q
...........
----------------------------------------------------------------------
Ran 11 tests in 0.000s
OK
If you have the :mod:`nose` package installed in the virtualenv, you can
use its testrunner too:
.. code-block:: sh
$ /tmp/hack-zope.copy/bin/nosetests
............
----------------------------------------------------------------------
Ran 12 tests in 0.011s
OK
If you have the :mod:`coverage` pacakge installed in the virtualenv,
you can see how well the tests cover the code:
.. code-block:: sh
$ .tox/coverage/bin/nosetests --with-coverage
............
Name Stmts Miss Cover Missing
----------------------------------------------------
zope.copy 59 0 100%
zope.copy._compat 6 0 100%
zope.copy.examples 4 0 100%
zope.copy.interfaces 5 0 100%
----------------------------------------------------
TOTAL 74 0 100%
----------------------------------------------------------------------
Ran 12 tests in 0.062s
OK
Building the documentation
--------------------------
:mod:`zope.copy` uses the nifty :mod:`Sphinx` documentation system
for building its docs. Using the same virtualenv you set up to run the
tests, you can build the docs:
.. code-block:: sh
$ /tmp/hack-zope.copy/bin/easy_install Sphinx
...
$ cd docs
$ PATH=/tmp/hack-zope.copy/bin:$PATH make html
sphinx-build -b html -d _build/doctrees . _build/html
...
build succeeded.
Build finished. The HTML pages are in _build/html.
You can also test the code snippets in the documentation:
.. code-block:: sh
$ PATH=/tmp/hack-zope.copy/bin:$PATH make doctest
sphinx-build -b doctest -d _build/doctrees . _build/doctest
...
running tests...
Document: narr
--------------
1 items passed all tests:
93 tests in default
93 tests in 1 items.
93 passed and 0 failed.
Test passed.
Doctest summary
===============
93 tests
0 failures in tests
0 failures in setup code
0 failures in cleanup code
build succeeded.
Testing of doctests in the sources finished, look at the \
results in _build/doctest/output.txt.
Using :mod:`zc.buildout`
########################
Setting up the buildout
-----------------------
:mod:`zope.copy` ships with its own :file:`buildout.cfg` file and
:file:`bootstrap.py` for setting up a development buildout:
.. code-block:: sh
$ /path/to/python2.6 bootstrap.py
...
Generated script '.../bin/buildout'
$ bin/buildout
Develop: '/home/jrandom/projects/Zope/zope.event/.'
...
Running the tests
-----------------
You can now run the tests:
.. code-block:: sh
$ bin/test --all
Running zope.testing.testrunner.layer.UnitTests tests:
Set up zope.testing.testrunner.layer.UnitTests in 0.000 seconds.
Ran 2 tests with 0 failures and 0 errors in 0.000 seconds.
Tearing down left over layers:
Tear down zope.testing.testrunner.layer.UnitTests in 0.000 seconds.
Using :mod:`tox`
################
Running Tests on Multiple Python Versions
-----------------------------------------
`tox <http://tox.testrun.org/latest/>`_ is a Python-based test automation
tool designed to run tests against multiple Python versions. It creates
a ``virtualenv`` for each configured version, installs the current package
and configured dependencies into each ``virtualenv``, and then runs the
configured commands.
:mod:`zope.copy` configures the following :mod:`tox` environments via
its ``tox.ini`` file:
- The ``py26``, ``py27``, ``py32``, ``py33``, ``py34``, and ``pypy``
environments build a ``virtualenv`` with the appropriate interpreter,
installs :mod:`zope.copy` and dependencies, and runs the tests
via ``python setup.py test -q``.
- The ``coverage`` environment builds a ``virtualenv`` with ``python2.6``,
installs :mod:`zope.copy`, installs
:mod:`nose` and :mod:`coverage`, and runs ``nosetests`` with statement
coverage.
- The ``docs`` environment builds a virtualenv with ``python2.6``, installs
:mod:`zope.copy`, installs ``Sphinx`` and
dependencies, and then builds the docs and exercises the doctest snippets.
This example requires that you have a working ``python2.6`` on your path,
as well as installing ``tox``:
.. code-block:: sh
$ tox -e py26
GLOB sdist-make: .../zope.copy/setup.py
py26 sdist-reinst: .../zope.copy/.tox/dist/zope.copy-4.0.2dev.zip
py26 runtests: commands[0]
...........
----------------------------------------------------------------------
Ran 11 tests in 0.000s
OK
___________________________________ summary ____________________________________
py26: commands succeeded
congratulations :)
Running ``tox`` with no arguments runs all the configured environments,
including building the docs and testing their snippets:
.. code-block:: sh
$ tox
GLOB sdist-make: .../zope.copy/setup.py
py26 sdist-reinst: .../zope.copy/.tox/dist/zope.copy-4.0.2dev.zip
py26 runtests: commands[0]
...
Doctest summary
===============
93 tests
0 failures in tests
0 failures in setup code
0 failures in cleanup code
build succeeded.
___________________________________ summary ____________________________________
py26: commands succeeded
py27: commands succeeded
py32: commands succeeded
py33: commands succeeded
py34: commands succeeded
pypy: commands succeeded
pypy3: commands succeeded
coverage: commands succeeded
docs: commands succeeded
congratulations :)
Contributing to :mod:`zope.copy`
################################
Submitting a Bug Report
-----------------------
:mod:`zope.copy` tracks its bugs on Github:
https://github.com/zopefoundation/zope.copy/issues
Please submit bug reports and feature requests there.
Sharing Your Changes
--------------------
.. note::
Please ensure that all tests are passing before you submit your code.
If possible, your submission should include new tests for new features
or bug fixes, although it is possible that you may have tested your
new code by updating existing tests.
If have made a change you would like to share, the best route is to fork
the Githb repository, check out your fork, make your changes on a branch
in your fork, and push it. You can then submit a pull request from your
branch:
https://github.com/zopefoundation/zope.copy/pulls
If you branched the code from Launchpad using Bazaar, you have another
option: you can "push" your branch to Launchpad:
.. code-block:: sh
$ bzr push lp:~jrandom/zope.copy/cool_feature
After pushing your branch, you can link it to a bug report on Github,
or request that the maintainers merge your branch using the Launchpad
"merge request" feature.
| zope.copy | /zope.copy-4.3.tar.gz/zope.copy-4.3/docs/hacking.rst | hacking.rst |
Using :mod:`zope.copy`
======================
Copying persistent objects
--------------------------
This package provides a pluggable way to copy persistent objects. It
was once extracted from the zc.copy package to contain much less
dependencies. In fact, we only depend on :mod:`zope.interface` to provide
pluggability.
The package provides a :func:`clone` function that does the object cloning
and the :func:`copy` wrapper that sets :attr:`__parent__` and
:attr:`__name__` attributes of object's copy to None. This is useful
when working with Zope's located objects (see :mod:`zope.location` package).
The :func:`copy` function actually calls the :func:`clone` function, so
we'll use the first one in the examples below. We'll also look a bit at
their differences in the end of this document.
The :func:`clone` function (and thus the :func:`copy` function that wraps it)
uses pickling to copy the object and all its subobjects recursively.
As each object and subobject is pickled, the function tries to adapt it
to :class:`zope.copy.interfaces.ICopyHook`. If a copy hook is found,
the recursive copy is halted. The hook is called with two values: the
main, top-level object that is being copied; and a callable that supports
registering functions to be called after the copy is made. The copy hook
should return the exact object or subobject that should be used at this
point in the copy, or raise :exc:`zope.copy.interfaces.ResumeCopy`
exception to resume copying the object or subobject recursively after
all.
Note that we use zope's component architecture provided by the
:mod:`zope.component` package in this document, but the
:mod:`zope.copy` package itself doesn't use or depend on it, so
you can provide another adaptation mechanism as described in
:mod:`zope.interface`'s adapter documentation.
Simple hooks
------------
First let's examine a simple use. A hook is to support the use case of
resetting the state of data that should be changed in a copy -- for
instance, a log, or freezing or versioning data. The canonical way to
do this is by storing the changable data on a special sub-object of the
object that is to be copied. We'll look at a simple case of a subobject
that should be converted to None when it is copied -- the way that the
zc.freeze copier hook works. Also see the zc.objectlog copier module
for a similar example.
So, here is a simple object that stores a boolean on a special object.
.. literalinclude:: ../src/zope/copy/examples.py
:pyobject: Demo
:prepend: # zope.copy.examples.Demo
.. literalinclude:: ../src/zope/copy/examples.py
:pyobject: Data
:prepend: # zope.copy.examples.Data
Here's what happens if we copy one of these objects without a copy hook.
.. doctest::
>>> from zope.copy.examples import Demo, Data
>>> original = Demo()
>>> original.isFrozen()
False
>>> original.freeze()
>>> original.isFrozen()
True
>>> import zope.copy
>>> copy = zope.copy.copy(original)
>>> copy is original
False
>>> copy.isFrozen()
True
Now let's make a super-simple copy hook that always returns None, no
matter what the top-level object being copied is. We'll register it and
make another copy.
.. doctest::
>>> import zope.component
>>> import zope.interface
>>> import zope.copy.interfaces
>>> def _factory(obj, register):
... return None
>>> @zope.component.adapter(Data)
... @zope.interface.implementer(zope.copy.interfaces.ICopyHook)
... def data_copyfactory(obj):
... return _factory
...
>>> zope.component.provideAdapter(data_copyfactory)
>>> copy2 = zope.copy.copy(original)
>>> copy2 is original
False
>>> copy2.isFrozen()
False
Much better.
Post-copy functions
-------------------
Now, let's look at the registration function that the hook can use. It
is useful for resetting objects within the new copy -- for instance, back
references such as __parent__ pointers. This is used concretely in the
zc.objectlog.copier module; we will come up with a similar but artificial
example here.
Imagine an object with a subobject that is "located" (i.e., zope.location) on
the parent and should be replaced whenever the main object is copied.
.. literalinclude:: ../src/zope/copy/examples.py
:pyobject: Subobject
:prepend: # zope.copy.examples.Subobject
.. doctest::
>>> import zope.location.location
>>> from zope.copy.examples import Subobject
>>> o = zope.location.location.Location()
>>> s = Subobject()
>>> o.subobject = s
>>> zope.location.location.locate(s, o, 'subobject')
>>> s.__parent__ is o
True
>>> o.subobject()
0
>>> o.subobject()
1
>>> o.subobject()
2
Without an ICopyHook, this will simply duplicate the subobject, with correct
new pointers.
.. doctest::
>>> c = zope.copy.copy(o)
>>> c.subobject.__parent__ is c
True
Note that the subobject has also copied state.
.. doctest::
>>> c.subobject()
3
>>> o.subobject()
3
Our goal will be to make the counters restart when they are copied. We'll do
that with a copy hook.
This copy hook is different: it provides an object to replace the old object,
but then it needs to set it up further after the copy is made. This is
accomplished by registering a callable, :func:`reparent` here, that sets up
the :attr:`__parent__`. The callable is passed a function that can translate
something from the original object into the equivalent on the new object.
We use this to find the new parent, so we can set it.
.. doctest::
>>> import zope.component
>>> import zope.interface
>>> import zope.copy.interfaces
>>> @zope.component.adapter(Subobject)
... @zope.interface.implementer(zope.copy.interfaces.ICopyHook)
... def subobject_copyfactory(original):
... def factory(obj, register):
... obj = Subobject()
... def reparent(translate):
... obj.__parent__ = translate(original.__parent__)
... register(reparent)
... return obj
... return factory
...
>>> zope.component.provideAdapter(subobject_copyfactory)
Now when we copy, the new subobject will have the correct, revised __parent__,
but will be otherwise reset (here, just the counter)
.. doctest::
>>> c = zope.copy.copy(o)
>>> c.subobject.__parent__ is c
True
>>> c.subobject()
0
>>> o.subobject()
4
Resuming recursive copy
-----------------------
One thing we didn't examine yet is the use of ResumeCopy exception in
the copy hooks. For example, when copying located objects we don't want
to copy referenced subobjects that are not located in the object that
is being copied. Imagine, we have a content object that has an image object,
referenced by the :attr:`cover` attribute, but located in an independent
place.
.. doctest::
>>> root = zope.location.location.Location()
>>> content = zope.location.location.Location()
>>> zope.location.location.locate(content, root, 'content')
>>> image = zope.location.location.Location()
>>> zope.location.location.locate(image, root, 'image.jpg')
>>> content.cover = image
Without any hooks, the image object will be cloned as well:
.. doctest::
>>> new = zope.copy.copy(content)
>>> new.cover is image
False
That's not what we'd expect though, so, let's provide a copy hook
to deal with that. The copy hook for this case is provided by zope.location
package, but we'll create one from scratch as we want to check out the
usage of the ResumeCopy.
.. doctest::
>>> @zope.component.adapter(zope.location.interfaces.ILocation)
... @zope.interface.implementer(zope.copy.interfaces.ICopyHook)
... def location_copyfactory(obj):
... def factory(location, register):
... if not zope.location.location.inside(obj, location):
... return obj
... raise zope.copy.interfaces.ResumeCopy
... return factory
...
>>> zope.component.provideAdapter(location_copyfactory)
This hook returns objects as they are if they are not located inside
object that's being copied, or raises ResumeCopy to signal that the
recursive copy should be continued and used for the object.
.. doctest::
>>> new = zope.copy.copy(content)
>>> new.cover is image
True
Much better :-)
:func:`clone` vs :func:`copy`
------------------------------
As we stated before, there's two functions that is used for copying
objects. The :func:`clone` - that does the job, and its wrapper, :func:`copy`
that calls :func:`clone` and then clears copy's :attr:`__parent__` and
:attr:`__name__` attribute values.
Let's create a location object with __name__ and __parent__ set.
.. doctest::
>>> root = zope.location.location.Location()
>>> folder = zope.location.location.Location()
>>> folder.__name__ = 'files'
>>> folder.__parent__ = root
The :func:`clone` function will leave those attributes as is. Note that the
referenced __parent__ won't be cloned, as we registered a hook for locations
in the previous section.
.. doctest::
>>> folder_clone = zope.copy.clone(folder)
>>> folder_clone.__parent__ is root
True
>>> folder_clone.__name__ == 'files'
True
However, the :func:`copy` function will reset those attributes to None, as
we will probably want to place our object into another container with
another name.
.. doctest::
>>> folder_clone = zope.copy.copy(folder)
>>> folder_clone.__parent__ is None
True
>>> folder_clone.__name__ is None
True
Notice, that if your object doesn't have __parent__ and __name__
attributes at all, or these attributes could'nt be got or set because of
some protections (as with zope.security's proxies, for example), you still
can use the :func:`copy` function, because it works for objects that don't
have those attributes.
It won't set them if original object doesn't have them:
.. literalinclude:: ../src/zope/copy/examples.py
:pyobject: Something
:prepend: # zope.copy.examples.Something
.. doctest::
>>> from zope.copy.examples import Something
>>> s = Something()
>>> s_copy = zope.copy.copy(s)
>>> s_copy.__parent__
Traceback (most recent call last):
...
AttributeError: ...
>>> s_copy.__name__
Traceback (most recent call last):
...
AttributeError: ...
And it won't fail if original object has them but doesn't allow to set
them.
.. literalinclude:: ../src/zope/copy/examples.py
:pyobject: Other
:prepend: # zope.copy.examples.Other
.. doctest::
>>> from zope.copy.examples import Other
>>> s = Other()
>>> s_copy = zope.copy.copy(s)
>>> s_copy.__parent__ is Other.root
True
>>> s_copy.__name__ == 'something'
True
:class:`~zope.location.pickling.LocationCopyHook`
-------------------------------------------------
The location copy hook is defined in :mod:`zope.location` but only activated
if this package is installed.
It's job is to allow copying referenced objects that are not located inside
object that's being copied.
To see the problem, imagine we want to copy an
:class:`~zope.location.interfaces.ILocation` object that
contains an attribute-based reference to another ILocation object
and the referenced object is not contained inside object being copied.
Without this hook, the referenced object will be cloned:
.. doctest::
>>> from zope.component.globalregistry import base
>>> base.__init__('base') # blow away previous registrations
>>> from zope.location.location import Location, locate
>>> root = Location()
>>> page = Location()
>>> locate(page, root, 'page')
>>> image = Location()
>>> locate(page, root, 'image')
>>> page.thumbnail = image
>>> from zope.copy import copy
>>> page_copy = copy(page)
>>> page_copy.thumbnail is image
False
But if we will provide a hook, the attribute will point to the
original object as we might want.
.. doctest::
>>> from zope.component import provideAdapter
>>> from zope.location.pickling import LocationCopyHook
>>> from zope.location.interfaces import ILocation
>>> provideAdapter(LocationCopyHook, (ILocation,))
>>> from zope.copy import copy
>>> page_copy = copy(page)
>>> page_copy.thumbnail is image
True
| zope.copy | /zope.copy-4.3.tar.gz/zope.copy-4.3/docs/narr.rst | narr.rst |
=========
Changes
=========
5.0 (2023-07-06)
================
- Add support for Python 3.11.
- Drop support for Python 2.7, 3.5, 3.6.
- Drop deprecated support for ``python setup.py test``.
4.2.1 (2022-08-25)
==================
- Fix DeprecationWarnings.
4.2.0 (2022-01-24)
==================
- Add support for Python 3.7, 3.8, 3.9, and 3.10.
- Drop support for Python 3.4.
4.1.0 (2017-08-04)
==================
- Add support for Python 3.5 and 3.6.
- Drop support for Python 2.6 and 3.3.
4.0.0 (2014-12-24)
==================
- Add support for PyPy.
- Add support for Python 3.4.
- Add support for testing on Travis.
4.0.0a1 (2013-02-24)
====================
- Add support for Python 3.3.
- Replace deprecated ``zope.component.adapts`` usage with equivalent
``zope.component.adapter`` decorator.
- Replace deprecated ``zope.interface.implements`` usage with equivalent
``zope.interface.implementer`` decorator.
- Drop support for Python 2.4 and 2.5.
- Include zcml dependencies in ``configure.zcml``, require the necessary
packages via a zcml extra, and add tests for zcml.
3.8.0 (2010-09-14)
==================
- Add a test that makes sure that dublin core meta data of folder contents
get updated when the folder gets copied. (Requires `zope.dublincore` 3.8
or above.)
3.7.0 (2010-09-14)
==================
- Honor the name given by the ``IObjectMover`` in
``OrderedContainerItemRenamer.renameItem``. It now returns the new of the
obejct, too. Thanks to Marius Gedminas for the patch, and to Justin Ryan
for the test. Fixes
https://bugs.launchpad.net/zope.copypastemove/+bug/98385.
- Add a check for name and container if the namechooser computes a
name which is the same as the current name.
Fixes https://bugs.launchpad.net/zope.copypastemove/+bug/123532
- Remove use of ``zope.testing.doctestunit`` in favor of stdlib's ``doctest``.
- Move ``zope.copypastemove``-related tests from ``zope.container`` here.
3.6.0 (2009-12-16)
==================
- Favor ``zope.principalannotation`` over its ``zope.app`` variant.
- Avoid ``zope.app.component`` and testing dependencies.
3.5.2 (2009-08-15)
==================
- Fix documentation for the ``IObjectCopier.copyTo`` method.
- Add a missing dependency on ``zope.app.component``.
3.5.1 (2009-02-09)
==================
- Use the new ``zope.copy`` package for ObjectCopier to provide pluggable
copying mechanism that is not dependent on ``zope.location`` hardly.
- Move the ``ItemNotFoundError`` exception to the interfaces module as
it's part of public API. Old import still works as we actually
use it where it was previously defined, however, the new import
place is preferred.
3.5.0 (2009-01-31)
==================
- Use ``zope.container`` instead of ``zope.app.container``.
3.4.1 (2009-01-26)
==================
- Move the test dependencies to a ``test`` extra requirement.
3.4.0 (2007-09-28)
==================
- No further changes since 3.4.0a1.
3.4.0a1 (2007-04-22)
====================
- Initial release as a separate project, corresponds to
``zope.copypastemove`` from Zope 3.4.0a1
| zope.copypastemove | /zope.copypastemove-5.0.tar.gz/zope.copypastemove-5.0/CHANGES.rst | CHANGES.rst |
========================
``zope.copypastemove``
========================
.. image:: https://img.shields.io/pypi/v/zope.copypastemove.svg
:target: https://pypi.python.org/pypi/zope.copypastemove/
:alt: Latest release
.. image:: https://img.shields.io/pypi/pyversions/zope.copypastemove.svg
:target: https://pypi.org/project/zope.copypastemove/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/zope.copypastemove/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/zope.copypastemove/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/zope.copypastemove/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/zope.copypastemove?branch=master
This package provides Copy, Paste and Move support for content
components in Zope. In particular, it defines the following
interfaces for this kind of functionality:
* ``IObjectMover``,
* ``IObjectCopier``,
* ``IContentItemRenamer``,
* ``IPrincipalClipboard``
as well as standard implementations for containers and contained
objects as known from the ``zope.container`` package.
| zope.copypastemove | /zope.copypastemove-5.0.tar.gz/zope.copypastemove-5.0/README.rst | README.rst |
"""Copy and Move support
"""
__docformat__ = 'restructuredtext'
from zope.interface import Interface
from zope.interface import implementer
class IObjectMover(Interface):
"""Use `IObjectMover(obj)` to move an object somewhere."""
def moveTo(target, new_name=None):
"""Move this object to the target given.
Returns the new name within the target.
"""
def moveable():
"""Returns ``True`` if the object is moveable, otherwise ``False``."""
def moveableTo(target, name=None):
"""Say whether the object can be moved to the given `target`.
Returns ``True`` if it can be moved there. Otherwise, returns
``False``.
"""
class IObjectCopier(Interface):
def copyTo(target, new_name=None):
"""Copy this object to the `target` given.
Returns the new name within the `target`. After the copy
is created and before adding it to the target container,
an `IObjectCopied` event is published.
"""
def copyable():
"""Returns ``True`` if the object is copyable, otherwise ``False``."""
def copyableTo(target, name=None):
"""Say whether the object can be copied to the given `target`.
Returns ``True`` if it can be copied there. Otherwise, returns
``False``.
"""
class IContainerItemRenamer(Interface):
def renameItem(oldName, newName):
"""Renames an object in the container from oldName to newName.
Raises ItemNotFoundError if oldName doesn't exist in the container.
Raises DuplicationError if newName is already used in the container.
"""
class IPrincipalClipboard(Interface):
"""Interface for adapters that store/retrieve clipboard information
for a principal.
Clipboard information consists of mappings of
``{'action':action, 'target':target}``.
"""
def clearContents():
"""Clear the contents of the clipboard"""
def addItems(action, targets):
"""Add new items to the clipboard"""
def setContents(clipboard):
"""Replace the contents of the clipboard by the given value"""
def getContents():
"""Return the contents of the clipboard"""
class IItemNotFoundError(Interface):
pass
@implementer(IItemNotFoundError)
class ItemNotFoundError(LookupError):
pass | zope.copypastemove | /zope.copypastemove-5.0.tar.gz/zope.copypastemove-5.0/src/zope/copypastemove/interfaces.py | interfaces.py |
"""Copy, Paste and Move support for content components
"""
__docformat__ = 'restructuredtext'
import zope.component
from zope.annotation.interfaces import IAnnotations
from zope.component import adapter
from zope.container.constraints import checkObject
from zope.container.interfaces import IContainer
from zope.container.interfaces import INameChooser
from zope.container.interfaces import IOrderedContainer
from zope.container.sample import SampleContainer
from zope.copy import copy
from zope.event import notify
from zope.exceptions import DuplicationError
from zope.interface import Invalid
from zope.interface import implementer
from zope.lifecycleevent import ObjectCopiedEvent
from zope.location.interfaces import IContained
from zope.location.interfaces import ISublocations
from zope.copypastemove.interfaces import IContainerItemRenamer
from zope.copypastemove.interfaces import IObjectCopier
from zope.copypastemove.interfaces import IObjectMover
from zope.copypastemove.interfaces import IPrincipalClipboard
from zope.copypastemove.interfaces import ItemNotFoundError
@adapter(IContained)
@implementer(IObjectMover)
class ObjectMover:
"""Adapter for moving objects between containers
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`.
>>> from zope.container.contained import Contained
>>> ob = Contained()
>>> container = ExampleContainer()
>>> container['foo'] = ob
>>> mover = ObjectMover(ob)
In addition to moving objects, object movers can tell you if the
object is movable:
>>> mover.moveable()
True
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:
>>> container2 = ExampleContainer()
>>> mover.moveableTo(container2)
True
>>> 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(container2)
'foo'
>>> list(container)
[]
>>> list(container2)
['foo']
>>> ob.__parent__ is container2
True
We can also specify a name:
>>> mover.moveTo(container2, 'bar')
'bar'
>>> list(container2)
['bar']
>>> ob.__parent__ is container2
True
>>> ob.__name__
'bar'
But we may not use the same name given, if the name is already in
use:
>>> container2['splat'] = 1
>>> mover.moveTo(container2, 'splat')
'splat_'
>>> l = list(container2)
>>> l.sort()
>>> l
['splat', 'splat_']
>>> ob.__name__
'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.
Do a test for preconditions:
>>> import zope.interface
>>> import zope.schema
>>> def preNoZ(container, name, ob):
... "Silly precondition example"
... if name.startswith("Z"):
... raise zope.interface.Invalid("Invalid name.")
>>> class I1(zope.interface.Interface):
... def __setitem__(name, on):
... "Add an item"
... __setitem__.precondition = preNoZ
>>> from zope.container.interfaces import IContainer
>>> @zope.interface.implementer(I1, IContainer)
... class C1(object):
... def __repr__(self):
... return 'C1'
>>> container3 = C1()
>>> mover.moveableTo(container3, 'ZDummy')
False
>>> mover.moveableTo(container3, 'newName')
True
And a test for constraints:
>>> def con1(container):
... "silly container constraint"
... if not hasattr(container, 'x'):
... return False
... return True
...
>>> class I2(zope.interface.Interface):
... __parent__ = zope.schema.Field(constraint=con1)
...
>>> @zope.interface.implementer(I2)
... class constrainedObject(object):
... def __init__(self):
... self.__name__ = 'constrainedObject'
...
>>> cO = constrainedObject()
>>> mover2 = ObjectMover(cO)
>>> mover2.moveableTo(container)
False
>>> container.x = 1
>>> mover2.moveableTo(container)
True
"""
def __init__(self, object):
self.context = object
self.__parent__ = object # TODO: see if we can automate this
def moveTo(self, target, new_name=None):
"""Move this object to the `target` given.
Returns the new name within the `target`
"""
obj = self.context
container = obj.__parent__
orig_name = obj.__name__
if new_name is None:
new_name = orig_name
checkObject(target, new_name, obj)
if target is container and new_name == orig_name:
# Nothing to do
return
chooser = INameChooser(target)
new_name = chooser.chooseName(new_name, obj)
if target is container and new_name == orig_name:
# obstinate namechooser
return
target[new_name] = obj
del container[orig_name]
return new_name
def moveable(self):
"""Returns ``True`` if the object is moveable, otherwise ``False``."""
return True
def moveableTo(self, target, name=None):
"""Say whether the object can be moved to the given target.
Returns ``True`` if it can be moved there. Otherwise, returns
``False``.
"""
if name is None:
name = self.context.__name__
try:
checkObject(target, name, self.context)
except Invalid:
return False
return True
@adapter(IContained)
@implementer(IObjectCopier)
class ObjectCopier:
"""Adapter for copying objects between containers
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`.
>>> from zope.container.contained import Contained
>>> ob = Contained()
>>> container = ExampleContainer()
>>> container['foo'] = ob
>>> copier = ObjectCopier(ob)
In addition to moving objects, object copiers can tell you if the
object is movable:
>>> copier.copyable()
True
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:
>>> container2 = ExampleContainer()
>>> copier.copyableTo(container2)
True
>>> 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(container2)
'foo'
>>> list(container)
['foo']
>>> list(container2)
['foo']
>>> ob.__parent__ is container
True
>>> container2['foo'] is ob
False
>>> container2['foo'].__parent__ is container2
True
>>> container2['foo'].__name__
'foo'
We can also specify a name:
>>> copier.copyTo(container2, 'bar')
'bar'
>>> l = list(container2)
>>> l.sort()
>>> l
['bar', 'foo']
>>> ob.__parent__ is container
True
>>> container2['bar'] is ob
False
>>> container2['bar'].__parent__ is container2
True
>>> container2['bar'].__name__
'bar'
But we may not use the same name given, if the name is already in
use:
>>> copier.copyTo(container2, 'bar')
'bar_'
>>> l = list(container2)
>>> l.sort()
>>> l
['bar', 'bar_', 'foo']
>>> container2['bar_'].__name__
'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.
Do a test for preconditions:
>>> import zope.interface
>>> import zope.schema
>>> def preNoZ(container, name, ob):
... "Silly precondition example"
... if name.startswith("Z"):
... raise zope.interface.Invalid("Invalid name.")
>>> class I1(zope.interface.Interface):
... def __setitem__(name, on):
... "Add an item"
... __setitem__.precondition = preNoZ
>>> from zope.container.interfaces import IContainer
>>> @zope.interface.implementer(I1, IContainer)
... class C1(object):
... def __repr__(self):
... return 'C1'
>>> container3 = C1()
>>> copier.copyableTo(container3, 'ZDummy')
False
>>> copier.copyableTo(container3, 'newName')
True
And a test for constraints:
>>> def con1(container):
... "silly container constraint"
... if not hasattr(container, 'x'):
... return False
... return True
...
>>> class I2(zope.interface.Interface):
... __parent__ = zope.schema.Field(constraint=con1)
...
>>> @zope.interface.implementer(I2)
... class constrainedObject(object):
... def __init__(self):
... self.__name__ = 'constrainedObject'
...
>>> cO = constrainedObject()
>>> copier2 = ObjectCopier(cO)
>>> copier2.copyableTo(container)
False
>>> container.x = 1
>>> copier2.copyableTo(container)
True
"""
def __init__(self, object):
self.context = object
self.__parent__ = object # TODO: see if we can automate this
def copyTo(self, target, new_name=None):
"""Copy this object to the `target` given.
Returns the new name within the `target`. After the copy
is created and before adding it to the target container,
an `IObjectCopied` event is published.
"""
obj = self.context
orig_name = obj.__name__
if new_name is None:
new_name = orig_name
checkObject(target, new_name, obj)
chooser = INameChooser(target)
new_name = chooser.chooseName(new_name, obj)
new = copy(obj)
notify(ObjectCopiedEvent(new, obj))
target[new_name] = new
return new_name
def copyable(self):
"""Returns True if the object is copyable, otherwise False."""
return True
def copyableTo(self, target, name=None):
"""Say whether the object can be copied to the given `target`.
Returns ``True`` if it can be copied there. Otherwise, returns
``False``.
"""
if name is None:
name = self.context.__name__
try:
checkObject(target, name, self.context)
except Invalid:
return False
return True
@adapter(IContainer)
@implementer(IContainerItemRenamer)
class ContainerItemRenamer:
"""An IContainerItemRenamer adapter for containers.
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:
>>> from zope.location.interfaces import IContained
>>> gsm = zope.component.getGlobalSiteManager()
>>> gsm.registerAdapter(ObjectMover, (IContained, ), IObjectMover)
To rename an item in a container, instantiate a ContainerItemRenamer
with the container:
>>> container = SampleContainer()
>>> renamer = ContainerItemRenamer(container)
For this example, we'll rename an item 'foo':
>>> from zope.container.contained import Contained
>>> foo = Contained()
>>> container['foo'] = foo
>>> container['foo'] is foo
True
to 'bar':
>>> renamer.renameItem('foo', 'bar')
'bar'
>>> container['foo'] is foo
Traceback (most recent call last):
KeyError: 'foo'
>>> container['bar'] is 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
"""
def __init__(self, container):
self.container = container
def renameItem(self, oldName, newName):
return self._renameItem(oldName, newName)
def _renameItem(self, oldName, newName):
object = self.container.get(oldName)
if object is None:
raise ItemNotFoundError(self.container, oldName)
mover = IObjectMover(object)
if newName in self.container:
raise DuplicationError("%s is already in use" % newName)
return mover.moveTo(self.container, newName)
@adapter(IOrderedContainer)
@implementer(IContainerItemRenamer)
class OrderedContainerItemRenamer(ContainerItemRenamer):
"""Renames items within an ordered container.
This renamer preserves the original order of the contained items.
To illustrate, we need to setup an IObjectMover, which is used in the
renaming:
>>> from zope.location.interfaces import IContained
>>> gsm = zope.component.getGlobalSiteManager()
>>> gsm.registerAdapter(ObjectMover, (IContained, ), IObjectMover)
To rename an item in an ordered container, we instantiate a
OrderedContainerItemRenamer with the container:
>>> from zope.container.ordered import OrderedContainer
>>> container = OrderedContainer()
>>> renamer = OrderedContainerItemRenamer(container)
We'll add three items to the container:
>>> container['1'] = 'Item 1'
>>> container['2'] = 'Item 2'
>>> container['3'] = 'Item 3'
>>> container.items()
[('1', 'Item 1'), ('2', 'Item 2'), ('3', 'Item 3')]
When we rename one of the items:
>>> renamer.renameItem('1', 'I')
'I'
the order is preserved:
>>> container.items()
[('I', 'Item 1'), ('2', 'Item 2'), ('3', 'Item 3')]
Renaming the other two items also preserves the origina order:
>>> renamer.renameItem('2', 'II')
'II'
>>> renamer.renameItem('3', 'III')
'III'
>>> container.items()
[('I', 'Item 1'), ('II', 'Item 2'), ('III', 'Item 3')]
As with the standard renamer, trying to rename a non-existent item raises
an error:
>>> renamer.renameItem('IV', '4') # doctest:+ELLIPSIS
Traceback (most recent call last):
ItemNotFoundError: (<...OrderedContainer...>, 'IV')
And if the new item name already exists, a DuplicationError is raised:
>>> renamer.renameItem('III', 'I')
Traceback (most recent call last):
DuplicationError: I is already in use
"""
def renameItem(self, oldName, newName):
order = list(self.container.keys())
newName = self._renameItem(oldName, newName)
order[order.index(oldName)] = newName
self.container.updateOrder(order)
return newName
@adapter(IAnnotations)
@implementer(IPrincipalClipboard)
class PrincipalClipboard:
"""Principal clipboard
Clipboard information consists of mappings of
``{'action':action, 'target':target}``.
"""
def __init__(self, annotation):
self.context = annotation
def clearContents(self):
"""Clear the contents of the clipboard"""
self.context['clipboard'] = ()
def addItems(self, action, targets):
"""Add new items to the clipboard"""
contents = self.getContents()
actions = []
for target in targets:
actions.append({'action': action, 'target': target})
self.context['clipboard'] = contents + tuple(actions)
def setContents(self, clipboard):
"""Replace the contents of the clipboard by the given value"""
self.context['clipboard'] = clipboard
def getContents(self):
"""Return the contents of the clipboard"""
return self.context.get('clipboard', ())
@implementer(INameChooser)
class ExampleContainer(SampleContainer):
# Sample container used for examples in doc stringss in this module
def chooseName(self, name, ob):
while name in self:
name += '_'
return name
def dispatchToSublocations(object, event):
"""Dispatches an event to sublocations of a given object.
This handler is used to dispatch copy events to sublocations.
To illustrate, we'll first create a hierarchy of objects:
>>> class L(object):
... def __init__(self, name):
... self.__name__ = name
... self.__parent__ = None
... def __repr__(self):
... return '%s(%s)' % (self.__class__.__name__, self.__name__)
>>> @implementer(ISublocations)
... class C(L):
... def __init__(self, name, *subs):
... L.__init__(self, name)
... self.subs = subs
... for sub in subs:
... sub.__parent__ = self
... def sublocations(self):
... return self.subs
>>> c = C(1,
... C(11,
... L(111),
... L(112),
... ),
... C(12,
... L(121),
... L(122),
... L(123),
... L(124),
... ),
... L(13),
... )
and a handler for copy events that records the objects it's seen:
>>> seen = []
>>> def handler(ob, event):
... seen.append((ob, event.object))
Finally, we need to register our handler for copy events:
>>> from zope.lifecycleevent.interfaces import IObjectCopiedEvent
>>> gsm = zope.component.getGlobalSiteManager()
>>> gsm.registerHandler(handler, [None, IObjectCopiedEvent])
and this function as a dispatcher:
>>> gsm.registerHandler(dispatchToSublocations,
... [None, IObjectCopiedEvent])
When we notify that our root object has been copied:
>>> notify(ObjectCopiedEvent(c, L('')))
we see that our handler has seen all of the subobjects:
>>> seenreprs = sorted(map(repr, seen))
>>> seenreprs #doctest: +NORMALIZE_WHITESPACE
['(C(1), C(1))', '(C(11), C(1))', '(C(12), C(1))',
'(L(111), C(1))', '(L(112), C(1))', '(L(121), C(1))',
'(L(122), C(1))', '(L(123), C(1))', '(L(124), C(1))',
'(L(13), C(1))']
"""
subs = ISublocations(object, None)
if subs is not None:
for sub in subs.sublocations():
zope.component.handle(sub, event) | zope.copypastemove | /zope.copypastemove-5.0.tar.gz/zope.copypastemove-5.0/src/zope/copypastemove/__init__.py | __init__.py |
=========
CHANGES
=========
5.0.0 (2023-04-25)
==================
- Drop support for Python 2.7, 3.5, 3.6.
- Add support for Python 3.10, 3.11.
4.3.0 (2021-02-26)
==================
- Drop support for Python 3.4.
- Add support for Python 3.7, 3.8 and 3.9.
- Prevent a ``DeprecationWarning`` in Python 3.8+ when using a parameter for
``iso8601_date``, ``rfc850_date``, or ``rfc1123_date`` which has to be
converted via its ``__int__`` method.
4.2.0 (2017-08-14)
==================
- Remove support for guessing the timezone name when a timestamp
exceeds the value supported by Python's ``localtime`` function. On
platforms with a 32-bit ``time_t``, this would involve parsed values
that do not specify a timezone and are past the year 2038. Now the
underlying exception will be propagated. Previously an undocumented
heuristic was used. This is not expected to be a common issue;
Windows, as one example, always uses a 64-bit ``time_t``, even on
32-bit platforms. See
https://github.com/zopefoundation/zope.datetime/issues/4
- Use true division on Python 2 to match Python 3, in case certain
parameters turn out to be integers instead of floating point values.
This is not expected to be user-visible, but it can arise in
artificial tests of internal functions.
- Add support for Python 3.5 and 3.6.
- Drop support for Python 2.6, 3.2 and 3.3.
4.1.0 (2014-12-26)
==================
- Add support for PyPy and PyPy3.
- Add support for Python 3.4.
- Add support for testing on Travis.
4.0.0 (2013-02-19)
==================
- Add support for Python 3.2 and 3.3.
- Drop support for Python 2.4 and 2.5.
3.4.1 (2011-11-29)
==================
- Add test cases from LP #139360 (all passed without modification to
the ``parse`` function).
- Remove unneeded ``zope.testing`` dependency.
3.4.0 (2007-07-20)
==================
- Initial release as a separate project.
| zope.datetime | /zope.datetime-5.0.0.tar.gz/zope.datetime-5.0.0/CHANGES.rst | CHANGES.rst |
===================
``zope.datetime``
===================
.. image:: https://img.shields.io/pypi/v/zope.datetime.svg
:target: https://pypi.python.org/pypi/zope.datetime/
:alt: Latest release
.. image:: https://img.shields.io/pypi/pyversions/zope.datetime.svg
:target: https://pypi.org/project/zope.datetime/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/zope.datetime/workflows/tests/badge.svg
:target: https://github.com/zopefoundation/zope.datetime/actions?query=workflow%3Atests
:alt: CI status
.. image:: https://coveralls.io/repos/github/zopefoundation/zope.datetime/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/zope.datetime?branch=master
:alt: Coverage
.. image:: https://readthedocs.org/projects/zopedatetime/badge/?version=latest
:target: https://zopedatetime.readthedocs.io/en/latest/
:alt: Documentation Status
Functions to parse and format date/time strings in common formats.
The documentation is hosted at https://zopedatetime.readthedocs.io/
| zope.datetime | /zope.datetime-5.0.0.tar.gz/zope.datetime-5.0.0/README.rst | README.rst |
import math
import re
# there is a method definition that makes just "time"
# problematic while executing a class definition
import time as _time
from datetime import datetime as _datetime
from datetime import timedelta as _timedelta
from datetime import tzinfo as _std_tzinfo
from time import tzname
from zope.datetime.timezones import historical_zone_info as _data
if str is bytes: # PY2
StringTypes = (basestring,) # noqa: F821 undefined name pragma: PY2
else:
StringTypes = (str,) # pragma: PY3
# These are needed because the various date formats below must
# be in english per the RFCs. That means we can't use strftime,
# which is affected by different locale settings.
weekday_abbr = [
'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun',
]
weekday_full = [
'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday',
]
monthname = [
None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
]
def _get_gmtime_compatible_timestamp(ts):
"""Try to convert any argument to a timestamp ``time.gmtime`` can use."""
if ts is None:
# ``time.gmtime`` uses the current time but only if not given any
# parameter. It is easier to compute current time here:
ts = _time.time()
else:
# ``time.gmtime`` ignores fractions of seconds. Before Python 3.10 it
# used to convert its argument to an ``int`` if it was not a number.
ts = int(ts)
return ts
def iso8601_date(ts=None):
"""
Return an ISO 8601 formatted date string, required
for certain DAV properties.
For example: '2000-11-10T16:21:09-08:00'
:param any ts: A timestamp as returned by :func:`time.time` (``float``),
seconds since the epoch (``int``) or any object which can be converted
to ``int`` via a ``__int__`` method returning number of seconds since
the epoch.
If not given, the current time will be used.
"""
ts = _get_gmtime_compatible_timestamp(ts)
return _time.strftime('%Y-%m-%dT%H:%M:%SZ', _time.gmtime(ts))
def rfc850_date(ts=None):
"""
Return an RFC 850 formatted date string.
For example, 'Friday, 10-Nov-00 16:21:09 GMT'.
:param any ts: A timestamp as returned by :func:`time.time` (``float``),
seconds since the epoch (``int``) or any object which can be converted
to ``int`` via a ``__int__`` method returning number of seconds since
the epoch.
"""
ts = _get_gmtime_compatible_timestamp(ts)
year, month, day, hh, mm, ss, wd, _y, _z = _time.gmtime(ts)
return "%s, %02d-%3s-%2s %02d:%02d:%02d GMT" % (
weekday_full[wd],
day, monthname[month],
str(year)[2:],
hh, mm, ss
)
def rfc1123_date(ts=None):
"""
Return an RFC 1123 format date string, required for
use in HTTP Date headers per the HTTP 1.1 spec.
For example, 'Fri, 10 Nov 2000 16:21:09 GMT'.
:param any ts: A timestamp as returned by :func:`time.time` (``float``),
seconds since the epoch (``int``) or any object which can be converted
to ``int`` via a ``__int__`` method returning number of seconds since
the epoch.
"""
ts = _get_gmtime_compatible_timestamp(ts)
year, month, day, hh, mm, ss, wd, _y, _z = _time.gmtime(ts)
return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
weekday_abbr[wd],
day, monthname[month],
year,
hh, mm, ss)
class DateTimeError(Exception):
"""
The root exception for errors raised by this module.
"""
class DateError(DateTimeError):
"""
Invalid Date Components
"""
class TimeError(DateTimeError):
"""
Invalid Time Components
"""
class SyntaxError(DateTimeError):
"""
Invalid Date-Time String
"""
# Determine machine epoch
def _calc_epoch():
tm = ((0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334),
(0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335))
yr, mo, dy, hr, mn, sc = _time.gmtime(0)[:6]
i = int(yr - 1)
to_year = int(i * 365 + i / 4 - i / 100 + i / 400 - 693960.0)
to_month = tm[yr % 4 == 0 and (yr % 100 != 0 or yr % 400 == 0)][mo]
epoch = (to_year + to_month + dy +
(hr / 24.0 + mn / 1440.0 + sc / 86400.0)) * 86400
return epoch
EPOCH = _calc_epoch()
jd1901 = 2415385
numericTimeZoneMatch = re.compile(r'[+-][0-9][0-9][0-9][0-9]').match # TS
class _timezone:
def __init__(self, data):
self.name, self.timect, self.typect, \
ttrans, self.tindex, self.tinfo, self.az = data
self.ttrans = [int(tt) for tt in ttrans]
def default_index(self):
if self.timect == 0:
return 0
for i in range(self.typect):
if self.tinfo[i][1] == 0:
return i
return 0
def index(self, t=None):
t = t if t is not None else _time.time()
if self.timect == 0:
idx = (0, 0, 0)
elif t < self.ttrans[0]:
i = self.default_index()
idx = (i, ord(self.tindex[0]), i)
elif t >= self.ttrans[-1]:
if self.timect > 1:
idx = (ord(self.tindex[-1]), ord(self.tindex[-1]),
ord(self.tindex[-2]))
else:
idx = (ord(self.tindex[-1]), ord(self.tindex[-1]),
self.default_index())
else:
for i in range(self.timect - 1):
if t < self.ttrans[i + 1]:
idx = (ord(self.tindex[i]),
ord(self.tindex[i + 1]),
self.default_index() if i == 0
else ord(self.tindex[i - 1]))
break
return idx
def info(self, t=None):
idx = self.index(t)[0]
zs = self.az[self.tinfo[idx][2]:]
return self.tinfo[idx][0], self.tinfo[idx][1], zs[: zs.find('\000')]
class _cache:
_zlst = [
'Brazil/Acre', 'Brazil/DeNoronha', 'Brazil/East',
'Brazil/West', 'Canada/Atlantic', 'Canada/Central',
'Canada/Eastern', 'Canada/East-Saskatchewan',
'Canada/Mountain', 'Canada/Newfoundland',
'Canada/Pacific', 'Canada/Yukon',
'Chile/Continental', 'Chile/EasterIsland', 'CST', 'Cuba',
'Egypt', 'EST', 'GB-Eire', 'Greenwich', 'Hongkong', 'Iceland',
'Iran', 'Israel', 'Jamaica', 'Japan', 'Mexico/BajaNorte',
'Mexico/BajaSur', 'Mexico/General', 'MST', 'Poland', 'PST',
'Singapore', 'Turkey', 'Universal', 'US/Alaska', 'US/Aleutian',
'US/Arizona', 'US/Central', 'US/Eastern', 'US/East-Indiana',
'US/Hawaii', 'US/Indiana-Starke', 'US/Michigan',
'US/Mountain', 'US/Pacific', 'US/Samoa', 'UTC', 'UCT', 'GMT',
'GMT+0100', 'GMT+0200', 'GMT+0300', 'GMT+0400', 'GMT+0500',
'GMT+0600', 'GMT+0700', 'GMT+0800', 'GMT+0900', 'GMT+1000',
'GMT+1100', 'GMT+1200', 'GMT+1300', 'GMT-0100', 'GMT-0200',
'GMT-0300', 'GMT-0400', 'GMT-0500', 'GMT-0600', 'GMT-0700',
'GMT-0800', 'GMT-0900', 'GMT-1000', 'GMT-1100', 'GMT-1200',
'GMT+1',
'GMT+0130', 'GMT+0230', 'GMT+0330', 'GMT+0430', 'GMT+0530',
'GMT+0630', 'GMT+0730', 'GMT+0830', 'GMT+0930', 'GMT+1030',
'GMT+1130', 'GMT+1230',
'GMT-0130', 'GMT-0230', 'GMT-0330', 'GMT-0430', 'GMT-0530',
'GMT-0630', 'GMT-0730', 'GMT-0830', 'GMT-0930', 'GMT-1030',
'GMT-1130', 'GMT-1230',
'UT', 'BST', 'MEST', 'SST', 'FST', 'WADT', 'EADT', 'NZDT',
'WET', 'WAT', 'AT', 'AST', 'NT', 'IDLW', 'CET', 'MET',
'MEWT', 'SWT', 'FWT', 'EET', 'EEST', 'BT', 'ZP4', 'ZP5', 'ZP6',
'WAST', 'CCT', 'JST', 'EAST', 'GST', 'NZT', 'NZST', 'IDLE'
]
_zmap = {
'aest': 'GMT+1000', 'aedt': 'GMT+1100',
'aus eastern standard time': 'GMT+1000',
'sydney standard time': 'GMT+1000',
'tasmania standard time': 'GMT+1000',
'e. australia standard time': 'GMT+1000',
'aus central standard time': 'GMT+0930',
'cen. australia standard time': 'GMT+0930',
'w. australia standard time': 'GMT+0800',
'brazil/acre': 'Brazil/Acre',
'brazil/denoronha': 'Brazil/Denoronha',
'brazil/east': 'Brazil/East', 'brazil/west': 'Brazil/West',
'canada/atlantic': 'Canada/Atlantic',
'canada/central': 'Canada/Central',
'canada/eastern': 'Canada/Eastern',
'canada/east-saskatchewan': 'Canada/East-Saskatchewan',
'canada/mountain': 'Canada/Mountain',
'canada/newfoundland': 'Canada/Newfoundland',
'canada/pacific': 'Canada/Pacific', 'canada/yukon': 'Canada/Yukon',
'central europe standard time': 'GMT+0100',
'chile/continental': 'Chile/Continental',
'chile/easterisland': 'Chile/EasterIsland',
'cst': 'US/Central', 'cuba': 'Cuba', 'est': 'US/Eastern',
'egypt': 'Egypt',
'eastern standard time': 'US/Eastern',
'us eastern standard time': 'US/Eastern',
'central standard time': 'US/Central',
'mountain standard time': 'US/Mountain',
'pacific standard time': 'US/Pacific',
'gb-eire': 'GB-Eire', 'gmt': 'GMT',
'gmt+0000': 'GMT+0', 'gmt+0': 'GMT+0',
'gmt+0100': 'GMT+1', 'gmt+0200': 'GMT+2', 'gmt+0300': 'GMT+3',
'gmt+0400': 'GMT+4', 'gmt+0500': 'GMT+5', 'gmt+0600': 'GMT+6',
'gmt+0700': 'GMT+7', 'gmt+0800': 'GMT+8', 'gmt+0900': 'GMT+9',
'gmt+1000': 'GMT+10', 'gmt+1100': 'GMT+11', 'gmt+1200': 'GMT+12',
'gmt+1300': 'GMT+13',
'gmt-0100': 'GMT-1', 'gmt-0200': 'GMT-2', 'gmt-0300': 'GMT-3',
'gmt-0400': 'GMT-4', 'gmt-0500': 'GMT-5', 'gmt-0600': 'GMT-6',
'gmt-0700': 'GMT-7', 'gmt-0800': 'GMT-8', 'gmt-0900': 'GMT-9',
'gmt-1000': 'GMT-10', 'gmt-1100': 'GMT-11', 'gmt-1200': 'GMT-12',
'gmt+1': 'GMT+1', 'gmt+2': 'GMT+2', 'gmt+3': 'GMT+3',
'gmt+4': 'GMT+4', 'gmt+5': 'GMT+5', 'gmt+6': 'GMT+6',
'gmt+7': 'GMT+7', 'gmt+8': 'GMT+8', 'gmt+9': 'GMT+9',
'gmt+10': 'GMT+10', 'gmt+11': 'GMT+11', 'gmt+12': 'GMT+12',
'gmt+13': 'GMT+13',
'gmt-1': 'GMT-1', 'gmt-2': 'GMT-2', 'gmt-3': 'GMT-3',
'gmt-4': 'GMT-4', 'gmt-5': 'GMT-5', 'gmt-6': 'GMT-6',
'gmt-7': 'GMT-7', 'gmt-8': 'GMT-8', 'gmt-9': 'GMT-9',
'gmt-10': 'GMT-10', 'gmt-11': 'GMT-11', 'gmt-12': 'GMT-12',
'gmt+130': 'GMT+0130', 'gmt+0130': 'GMT+0130',
'gmt+230': 'GMT+0230', 'gmt+0230': 'GMT+0230',
'gmt+330': 'GMT+0330', 'gmt+0330': 'GMT+0330',
'gmt+430': 'GMT+0430', 'gmt+0430': 'GMT+0430',
'gmt+530': 'GMT+0530', 'gmt+0530': 'GMT+0530',
'gmt+630': 'GMT+0630', 'gmt+0630': 'GMT+0630',
'gmt+730': 'GMT+0730', 'gmt+0730': 'GMT+0730',
'gmt+830': 'GMT+0830', 'gmt+0830': 'GMT+0830',
'gmt+930': 'GMT+0930', 'gmt+0930': 'GMT+0930',
'gmt+1030': 'GMT+1030',
'gmt+1130': 'GMT+1130',
'gmt+1230': 'GMT+1230',
'gmt-130': 'GMT-0130', 'gmt-0130': 'GMT-0130',
'gmt-230': 'GMT-0230', 'gmt-0230': 'GMT-0230',
'gmt-330': 'GMT-0330', 'gmt-0330': 'GMT-0330',
'gmt-430': 'GMT-0430', 'gmt-0430': 'GMT-0430',
'gmt-530': 'GMT-0530', 'gmt-0530': 'GMT-0530',
'gmt-630': 'GMT-0630', 'gmt-0630': 'GMT-0630',
'gmt-730': 'GMT-0730', 'gmt-0730': 'GMT-0730',
'gmt-830': 'GMT-0830', 'gmt-0830': 'GMT-0830',
'gmt-930': 'GMT-0930', 'gmt-0930': 'GMT-0930',
'gmt-1030': 'GMT-1030',
'gmt-1130': 'GMT-1130',
'gmt-1230': 'GMT-1230',
'greenwich': 'Greenwich', 'hongkong': 'Hongkong',
'iceland': 'Iceland', 'iran': 'Iran', 'israel': 'Israel',
'jamaica': 'Jamaica', 'japan': 'Japan',
'mexico/bajanorte': 'Mexico/BajaNorte',
'mexico/bajasur': 'Mexico/BajaSur', 'mexico/general': 'Mexico/General',
'mst': 'US/Mountain', 'pst': 'US/Pacific', 'poland': 'Poland',
'singapore': 'Singapore', 'turkey': 'Turkey', 'universal': 'Universal',
'utc': 'Universal', 'uct': 'Universal', 'us/alaska': 'US/Alaska',
'us/aleutian': 'US/Aleutian', 'us/arizona': 'US/Arizona',
'us/central': 'US/Central', 'us/eastern': 'US/Eastern',
'us/east-indiana': 'US/East-Indiana', 'us/hawaii': 'US/Hawaii',
'us/indiana-starke': 'US/Indiana-Starke', 'us/michigan': 'US/Michigan',
'us/mountain': 'US/Mountain', 'us/pacific': 'US/Pacific',
'us/samoa': 'US/Samoa',
'ut': 'Universal',
'bst': 'GMT+1', 'mest': 'GMT+2', 'sst': 'GMT+2',
'fst': 'GMT+2', 'wadt': 'GMT+8', 'eadt': 'GMT+11', 'nzdt': 'GMT+13',
'wet': 'GMT', 'wat': 'GMT-1', 'at': 'GMT-2', 'ast': 'GMT-4',
'nt': 'GMT-11', 'idlw': 'GMT-12', 'cet': 'GMT+1', 'cest': 'GMT+2',
'met': 'GMT+1',
'mewt': 'GMT+1', 'swt': 'GMT+1', 'fwt': 'GMT+1', 'eet': 'GMT+2',
'eest': 'GMT+3',
'bt': 'GMT+3', 'zp4': 'GMT+4', 'zp5': 'GMT+5', 'zp6': 'GMT+6',
'wast': 'GMT+7', 'cct': 'GMT+8', 'jst': 'GMT+9', 'east': 'GMT+10',
'gst': 'GMT+10', 'nzt': 'GMT+12', 'nzst': 'GMT+12', 'idle': 'GMT+12',
'ret': 'GMT+4'
}
def __init__(self):
self._db = _data
self._d, self._zidx = {}, self._zmap.keys()
def __getitem__(self, k):
try:
n = self._zmap[k.lower()]
except KeyError:
if numericTimeZoneMatch(k) is None:
raise DateTimeError('Unrecognized timezone: %s' % k)
return k
try:
return self._d[n]
except KeyError:
z = self._d[n] = _timezone(self._db[n])
return z
def _findLocalTimeZoneName(isDST):
if not _time.daylight: # pragma: no cover
# Daylight savings does not occur in this time zone.
isDST = 0
try:
# Get the name of the current time zone depending
# on DST.
_localzone = _cache._zmap[tzname[isDST].lower()]
except KeyError:
try:
# Generate a GMT-offset zone name.
localzone = _time.altzone if isDST else _time.timezone
offset = (-localzone / (60 * 60))
majorOffset = int(offset)
minorOffset = 0
if majorOffset != 0: # pragma: no cover
minorOffset = abs(int((offset % majorOffset) * 60.0))
m = '+' if majorOffset >= 0 else ''
lz = '%s%0.02d%0.02d' % (m, majorOffset, minorOffset)
_localzone = _cache._zmap[('GMT%s' % lz).lower()]
except Exception:
_localzone = ''
return _localzone
# Some utility functions for calculating dates:
def _calcSD(t):
# Returns timezone-independent days since epoch and the fractional
# part of the days.
dd = t + EPOCH - 86400.0
d = dd / 86400.0
s = d - math.floor(d)
return s, d
def _calcDependentSecond(tz, t):
# Calculates the timezone-dependent second (integer part only)
# from the timezone-independent second.
fset = _tzoffset(tz, t)
return fset + int(math.floor(t)) + EPOCH - 86400
def _calcDependentSecond2(yr, mo, dy, hr, mn, sc):
# Calculates the timezone-dependent second (integer part only)
# from the date given.
ss = int(hr) * 3600 + int(mn) * 60 + int(sc)
x = int(_julianday(yr, mo, dy) - jd1901) * 86400 + ss
return x
def _calcIndependentSecondEtc(tz, x, ms):
# Derive the timezone-independent second from the timezone
# dependent second.
fsetAtEpoch = _tzoffset(tz, 0.0)
nearTime = x - fsetAtEpoch - EPOCH + 86400 + ms
# nearTime is now within an hour of being correct.
# Recalculate t according to DST.
fset = _tzoffset(tz, nearTime)
x_adjusted = x - fset + ms
d = x_adjusted / 86400.0
t = x_adjusted - EPOCH + 86400
millis = (x + 86400 - fset) * 1000 + ms * 1000 - EPOCH * 1000
s = d - math.floor(d)
return s, d, t, millis
def _calcHMS(x, ms):
# hours, minutes, seconds from integer and float.
hr = x // 3600
x = x - hr * 3600
mn = x // 60
sc = x - mn * 60 + ms
return hr, mn, sc
def _julianday(y, m, d):
if m > 12:
y = y + m // 12
m = m % 12
elif m < 1:
m = -m
y = y - m // 12 - 1
m = 12 - m % 12
if y > 0:
yr_correct = 0
else:
yr_correct = 3
if m < 3:
y, m = y - 1, m + 12
if y * 10000 + m * 100 + d > 15821014:
b = 2 - y // 100 + y // 400
else:
b = 0
return (1461 * y - yr_correct) // 4 + 306001 * \
(m + 1) // 10000 + d + 1720994 + b
def _tzoffset(tz, t):
try:
return DateTimeParser._tzinfo[tz].info(t)[0]
except Exception:
if numericTimeZoneMatch(tz) is not None:
offset = int(tz[1:3]) * 3600 + int(tz[3:5]) * 60
if tz[0] == '-':
return -offset
return offset
else:
return 0 # Assume UTC
def _correctYear(year):
# Y2K patch.
if year >= 0 and year < 100:
# 00-69 means 2000-2069, 70-99 means 1970-1999.
if year < 70:
year = 2000 + year
else:
year = 1900 + year
return year
def safegmtime(t):
'''gmtime with a safety zone.'''
try:
return _time.gmtime(t)
except (ValueError, OverflowError): # Py2/Py3 respectively
raise TimeError('The time %r is beyond the range '
'of this Python implementation.' % t)
def safelocaltime(t):
'''localtime with a safety zone.'''
try:
return _time.localtime(t)
except (ValueError, OverflowError): # Py2/Py3 respectively
raise TimeError('The time %r is beyond the range '
'of this Python implementation.' % t)
class DateTimeParser:
def parse(self, arg, local=True):
"""
Parse a string containing some sort of date-time data into a tuple.
As a general rule, any date-time representation that is
recognized and unambigous to a resident of North America is
acceptable.(The reason for this qualification is that
in North America, a date like: 2/1/1994 is interpreted
as February 1, 1994, while in some parts of the world,
it is interpreted as January 2, 1994.) A date/time
string consists of two components, a date component and
an optional time component, separated by one or more
spaces. If the time component is omited, 12:00am is
assumed. Any recognized timezone name specified as the
final element of the date/time string will be used for
computing the date/time value. (If you create a DateTime
with the string 'Mar 9, 1997 1:45pm US/Pacific', the
value will essentially be the same as if you had captured
time.time() at the specified date and time on a machine in
that timezone)::
x = parse('1997/3/9 1:45pm')
# returns specified time, represented in local machine zone.
y = parse('Mar 9, 1997 13:45:00')
# y is equal to x
The function automatically detects and handles `ISO8601
compliant dates <http://www.w3.org/TR/NOTE-datetime>`_
(YYYY-MM-DDThh:ss:mmTZD).
The date component consists of year, month, and day
values. The year value must be a one-, two-, or
four-digit integer. If a one- or two-digit year is
used, the year is assumed to be in the twentieth
century. The month may an integer, from 1 to 12, a
month name, or a month abreviation, where a period may
optionally follow the abreviation. The day must be an
integer from 1 to the number of days in the month. The
year, month, and day values may be separated by
periods, hyphens, forward, shashes, or spaces. Extra
spaces are permitted around the delimiters. Year,
month, and day values may be given in any order as long
as it is possible to distinguish the components. If all
three components are numbers that are less than 13,
then a a month-day-year ordering is assumed.
The time component consists of hour, minute, and second
values separated by colons. The hour value must be an
integer between 0 and 23 inclusively. The minute value
must be an integer between 0 and 59 inclusively. The
second value may be an integer value between 0 and
59.999 inclusively. The second value or both the minute
and second values may be ommitted. The time may be
followed by am or pm in upper or lower case, in which
case a 12-hour clock is assumed.
:keyword bool local: If no timezone can be parsed from the string,
figure out what timezone it is in the local area
on the given date and return that.
:return: This function returns a tuple (year, month, day, hour, minute,
second, timezone_string).
:raises SyntaxError:
If a string argument passed to the DateTime constructor cannot be
parsed (for example, it is empty).
:raises DateError:
If the date components are invalid.
:raises DateTimeError:
If the time or timezone components are invalid.
:raises TypeError:
If the argument is not a string.
"""
if not isinstance(arg, StringTypes):
raise TypeError('Expected a string argument')
if not arg:
raise SyntaxError(arg)
if arg.find(' ') == -1 and len(arg) >= 5 and arg[4] == '-':
yr, mo, dy, hr, mn, sc, tz = self._parse_iso8601(arg)
else:
yr, mo, dy, hr, mn, sc, tz = self._parse(arg, local)
if not self._validDate(yr, mo, dy):
raise DateError(arg, yr, mo, dy)
if not self._validTime(hr, mn, int(sc)):
raise TimeError(arg)
return yr, mo, dy, hr, mn, sc, tz
def time(self, arg):
"""
Parse a string containing some sort of date-time data and return
the value in seconds since the Epoch.
:return: A floating point number representing the time in
seconds since the Epoch (in UTC).
:raises DateTimeError: If a timezone was parsed from the argument,
but it wasn't a known named or numeric timezone.
.. seealso:: :meth:`parse` for the description of allowed input values.
"""
yr, mo, dy, hr, mn, sc, tz = self.parse(arg)
ms = sc - math.floor(sc)
x = _calcDependentSecond2(yr, mo, dy, hr, mn, sc)
if tz:
try:
tz = self._tzinfo._zmap[tz.lower()]
except KeyError:
if numericTimeZoneMatch(tz) is None:
raise DateTimeError('Unknown time zone in date: %s' % arg)
else:
tz = self._calcTimezoneName(x, ms)
_s, _d, t, _millisecs = _calcIndependentSecondEtc(tz, x, ms)
return t
int_pattern = re.compile(r'([0-9]+)') # AJ
flt_pattern = re.compile(r':([0-9]+\.[0-9]+)') # AJ
name_pattern = re.compile(r'([a-zA-Z]+)', re.I) # AJ
space_chars = ' \t\n'
delimiters = '-/.:,+'
_month_len = (
(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
(0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
)
_until_month = (
(0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334),
(0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335)
)
_monthmap = {
'january': 1, 'jan': 1,
'february': 2, 'feb': 2,
'march': 3, 'mar': 3,
'april': 4, 'apr': 4,
'may': 5,
'june': 6, 'jun': 6,
'july': 7, 'jul': 7,
'august': 8, 'aug': 8,
'september': 9, 'sep': 9, 'sept': 9,
'october': 10, 'oct': 10,
'november': 11, 'nov': 11,
'december': 12, 'dec': 12
}
_daymap = {
'sunday': 1, 'sun': 1,
'monday': 2, 'mon': 2,
'tuesday': 3, 'tues': 3, 'tue': 3,
'wednesday': 4, 'wed': 4,
'thursday': 5, 'thurs': 5, 'thur': 5, 'thu': 5,
'friday': 6, 'fri': 6,
'saturday': 7, 'sat': 7
}
_localzone0 = _findLocalTimeZoneName(0)
_localzone1 = _findLocalTimeZoneName(1)
_multipleZones = (_localzone0 != _localzone1)
# For backward compatibility only:
_isDST = _time.localtime()[8]
_localzone = _localzone1 if _isDST else _localzone0
_tzinfo = _cache()
def localZone(self, ltm=None):
'''Returns the time zone on the given date. The time zone
can change according to daylight savings.'''
if not self._multipleZones:
return self._localzone0
ltm = _time.localtime() if ltm is None else ltm
isDST = ltm[8]
lz = self._localzone1 if isDST else self._localzone0
return lz
def _calcTimezoneName(self, x, ms):
# Derive the name of the local time zone at the given
# timezone-dependent second.
if not self._multipleZones:
return self._localzone0
fsetAtEpoch = _tzoffset(self._localzone0, 0.0)
nearTime = x - fsetAtEpoch - EPOCH + 86400 + ms
# nearTime is within an hour of being correct.
ltm = safelocaltime(nearTime)
tz = self.localZone(ltm)
return tz
def _parse(self, string, local=True):
# Parse date-time components from a string
month = year = tz = tm = None
spaces = self.space_chars
intpat = self.int_pattern
fltpat = self.flt_pattern
wordpat = self.name_pattern
delimiters = self.delimiters
MonthNumbers = self._monthmap
DayOfWeekNames = self._daymap
ValidZones = self._tzinfo._zidx
TimeModifiers = ['am', 'pm']
string = string.strip()
# Find timezone first, since it should always be the last
# element, and may contain a slash, confusing the parser.
# First check for time zone of form +dd:dd
tz = _iso_tz_re.search(string)
if tz:
tz = tz.start(0)
tz, string = string[tz:], string[:tz].strip()
tz = tz[:3] + tz[4:]
else:
# Look at last token
sp = string.split()
tz = sp[-1]
if tz and (tz.lower() in ValidZones):
string = ' '.join(sp[:-1])
else:
tz = None # Decide later, since the default time zone
# could depend on the date.
ints = []
i, len_string = 0, len(string)
while i < len_string:
while i < len_string and string[i] in spaces:
i = i + 1
if i < len_string and string[i] in delimiters:
d = string[i]
i = i + 1
else:
d = ''
while i < len_string and string[i] in spaces:
i = i + 1
# The float pattern needs to look back 1 character, because it
# actually looks for a preceding colon like ':33.33'. This is
# needed to avoid accidentally matching the date part of a
# dot-separated date string such as '1999.12.31'.
if i > 0:
b = i - 1
else:
b = i
ts_results = fltpat.match(string, b)
if ts_results:
s = ts_results.group(1)
i = i + len(s)
ints.append(float(s))
continue
# AJ
ts_results = intpat.match(string, i)
if ts_results:
s = ts_results.group(0)
ls = len(s)
i = i + ls
if (ls == 4 and d and d in '+-' and
(len(ints) + (not not month) >= 3)):
tz = '{}{}'.format(d, s)
else:
v = int(s)
ints.append(v)
continue
ts_results = wordpat.match(string, i)
if ts_results:
o = ts_results.group(0)
s = o.lower()
i = i + len(s)
if i < len_string and string[i] == '.':
i = i + 1
# Check for month name:
if s in MonthNumbers:
v = MonthNumbers[s]
if month is None:
month = v
else:
raise SyntaxError(string)
continue # pragma: no cover
# Check for time modifier:
if s in TimeModifiers:
if tm is None:
tm = s
else:
raise SyntaxError(string)
continue # pragma: no cover
# Check for and skip day of week:
if s in DayOfWeekNames:
continue
raise SyntaxError(string)
day = None
if ints[-1] > 60 and d not in ['.', ':'] and len(ints) > 2:
year = ints[-1]
del ints[-1]
if month:
day = ints[0]
del ints[:1]
else:
month = ints[0]
day = ints[1]
del ints[:2]
elif month:
if len(ints) > 1:
if ints[0] > 31:
year = ints[0]
day = ints[1]
else:
year = ints[1]
day = ints[0]
del ints[:2]
elif len(ints) > 2:
if ints[0] > 31:
year = ints[0]
if ints[1] > 12:
day = ints[1]
month = ints[2]
else:
day = ints[2]
month = ints[1]
if ints[1] > 31:
year = ints[1]
if ints[0] > 12 and ints[2] <= 12:
day = ints[0]
month = ints[2]
elif ints[2] > 12 and ints[0] <= 12:
day = ints[2]
month = ints[0]
elif ints[2] > 31:
year = ints[2]
if ints[0] > 12:
day = ints[0]
month = ints[1]
else:
day = ints[1]
month = ints[0]
elif ints[0] <= 12:
month = ints[0]
day = ints[1]
year = ints[2]
del ints[:3]
if day is None:
# Use today's date.
year, month, day = _time.localtime()[:3]
year = _correctYear(year)
if year < 1000:
raise SyntaxError(string)
leap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
try:
if not day or day > self._month_len[leap][month]:
raise DateError(string)
except IndexError:
raise DateError(string)
tod = 0
if ints:
i = ints[0]
# Modify hour to reflect am/pm
if tm and (tm == 'pm') and i < 12:
i = i + 12
if tm and (tm == 'am') and i == 12:
i = 0
if i > 24:
raise DateTimeError(string)
tod = tod + int(i) * 3600
del ints[0]
if ints:
i = ints[0]
if i > 60:
raise DateTimeError(string)
tod = tod + int(i) * 60
del ints[0]
if ints:
i = ints[0]
if i > 60:
raise DateTimeError(string)
tod = tod + i
del ints[0]
if ints:
raise SyntaxError(string)
tod_int = int(math.floor(tod))
ms = tod - tod_int
hr, mn, sc = _calcHMS(tod_int, ms)
if local and not tz:
# Figure out what time zone it is in the local area
# on the given date.
x = _calcDependentSecond2(year, month, day, hr, mn, sc)
tz = self._calcTimezoneName(x, ms)
return year, month, day, hr, mn, sc, tz
def _validDate(self, y, m, d):
if m < 1 or m > 12 or y < 0 or d < 1 or d > 31:
return 0
is_leap_year = y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)
return d <= self._month_len[is_leap_year][m]
def _validTime(self, h, m, s):
return h >= 0 and h <= 23 and m >= 0 and m <= 59 and s >= 0 and s < 60
def _parse_iso8601(self, s):
try:
return self.__parse_iso8601(s)
except IndexError:
raise DateError(
'Not an ISO 8601 compliant date string: "%s"' % s)
def __parse_iso8601(self, s):
"""Parse an ISO 8601 compliant date.
TODO: Not all allowed formats are recognized (for some examples see
http://www.cl.cam.ac.uk/~mgk25/iso-time.html).
"""
year = 0
month = day = 1
hour = minute = seconds = hour_off = min_off = 0
tzsign = '+'
datereg = re.compile(
'([0-9]{4})(-([0-9][0-9]))?(-([0-9][0-9]))?')
timereg = re.compile(
r'([0-9]{2})(:([0-9][0-9]))?(:([0-9][0-9]))?(\.[0-9]{1,20})?'
r'(\s*([-+])([0-9]{2})(:?([0-9]{2}))?)?')
# Date part
fields = datereg.split(s.strip())
if fields[1]:
year = int(fields[1])
if fields[3]:
month = int(fields[3])
if fields[5]:
day = int(fields[5])
if s.find('T') > -1:
fields = timereg.split(s[s.find('T') + 1:])
if fields[1]:
hour = int(fields[1])
if fields[3]:
minute = int(fields[3])
if fields[5]:
seconds = int(fields[5])
if fields[6]:
seconds = seconds + float(fields[6])
if fields[8]:
tzsign = fields[8]
if fields[9]:
hour_off = int(fields[9])
if fields[11]:
min_off = int(fields[11])
return (year, month, day, hour, minute, seconds,
'%s%02d%02d' % (tzsign, hour_off, min_off))
parser = DateTimeParser()
parse = parser.parse
time = parser.time
######################################################################
# Time-zone info based soley on offsets
#
# Share tzinfos for the same offset
class _tzinfo(_std_tzinfo):
def __init__(self, minutes):
if abs(minutes) > 1439:
raise ValueError("Time-zone offset is too large,", minutes)
self.__minutes = minutes
self.__offset = _timedelta(minutes=minutes)
def utcoffset(self, dt):
return self.__offset
def __reduce__(self):
return tzinfo, (self.__minutes, )
def dst(self, dt):
return None
def tzname(self, dt):
return None
def __repr__(self): # pragma: no cover
return 'tzinfo(%d)' % self.__minutes
_tzinfos = {}
def tzinfo(offset):
info = _tzinfos.get(offset)
if info is None:
# We haven't seen this one before. we need to save it.
# Use setdefault to avoid a race condition and make sure we have
# only one
info = _tzinfos.setdefault(offset, _tzinfo(offset))
return info
tzinfo.__safe_for_unpickling__ = True
#
######################################################################
def parseDatetimetz(string, local=True):
"""Parse the given string using :func:`parse`.
Return a :class:`datetime.datetime` instance.
"""
y, mo, d, h, m, s, tz = parse(string, local)
s, micro = divmod(s, 1.0)
micro = round(micro * 1000000)
if tz:
offset = _tzoffset(tz, None) / 60
_tzinfo = tzinfo(offset)
else:
_tzinfo = None
return _datetime(y, mo, d, int(h), int(m), int(s), int(micro), _tzinfo)
_iso_tz_re = re.compile(r"[-+]\d\d:\d\d$") | zope.datetime | /zope.datetime-5.0.0.tar.gz/zope.datetime-5.0.0/src/zope/datetime/__init__.py | __init__.py |
historical_zone_info = {
'Brazil/Acre': ('Brazil/Acre', 101, 2,
['561970800', '571644000', '593420400', '603093600', '625561200',
'634543200', '656924400', '665992800', '688374000', '697442400',
'719823600', '729496800', '751273200', '760946400', '782722800',
'792396000', '814863600', '823845600', '846226800', '855295200',
'877676400', '887436000', '909126000', '918799200', '940575600',
'950248800', '972716400', '981698400', '1004079600', '1013148000',
'1035529200', '1044597600', '1066978800', '1076738400', '1098428400',
'1108101600', '1129878000', '1139551200', '1162018800', '1171000800',
'1193382000', '1202450400', '1224831600', '1234591200', '1256281200',
'1265954400', '1287730800', '1297404000', '1319180400', '1328853600',
'1351234800', '1360303200', '1382684400', '1391752800', '1414134000',
'1423893600', '1445583600', '1455256800', '1477033200', '1486706400',
'1509174000', '1518156000', '1540537200', '1549605600', '1571986800',
'1581055200', '1603436400', '1613109600', '1634886000', '1644559200',
'1666335600', '1676008800', '1698476400', '1707458400', '1729839600',
'1738908000', '1761289200', '1771048800', '1792738800', '1802412000',
'1824188400', '1833861600', '1856329200', '1865311200', '1887692400',
'1896760800', '1919142000', '1928210400', '1950591600', '1960351200',
'1982041200', '1991714400', '2013490800', '2023164000', '2045631600',
'2054613600', '2076994800', '2086063200', '2108444400', '2118204000',
'2139894000',
],
'\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-18000, 0, 0), (-14400, 1, 4)], 'AST\x00ADT\x00'),
'Brazil/DeNoronha': ('Brazil/DeNoronha', 101, 2,
['561960000', '571633200', '593409600', '603082800', '625550400',
'634532400', '656913600', '665982000', '688363200', '697431600',
'719812800', '729486000', '751262400', '760935600', '782712000',
'792385200', '814852800', '823834800', '846216000', '855284400',
'877665600', '887425200', '909115200', '918788400', '940564800',
'950238000', '972705600', '981687600', '1004068800', '1013137200',
'1035518400', '1044586800', '1066968000', '1076727600', '1098417600',
'1108090800', '1129867200', '1139540400', '1162008000', '1170990000',
'1193371200', '1202439600', '1224820800', '1234580400', '1256270400',
'1265943600', '1287720000', '1297393200', '1319169600', '1328842800',
'1351224000', '1360292400', '1382673600', '1391742000', '1414123200',
'1423882800', '1445572800', '1455246000', '1477022400', '1486695600',
'1509163200', '1518145200', '1540526400', '1549594800', '1571976000',
'1581044400', '1603425600', '1613098800', '1634875200', '1644548400',
'1666324800', '1675998000', '1698465600', '1707447600', '1729828800',
'1738897200', '1761278400', '1771038000', '1792728000', '1802401200',
'1824177600', '1833850800', '1856318400', '1865300400', '1887681600',
'1896750000', '1919131200', '1928199600', '1950580800', '1960340400',
'1982030400', '1991703600', '2013480000', '2023153200', '2045620800',
'2054602800', '2076984000', '2086052400', '2108433600', '2118193200',
'2139883200',
],
'\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-7200, 0, 0), (-3600, 1, 4)], 'FST\x00FDT\x00'),
'Brazil/East': ('Brazil/East', 101, 2,
['561963600', '571636800', '593413200', '603086400', '625554000',
'634536000', '656917200', '665985600', '688366800', '697435200',
'719816400', '729489600', '751266000', '760939200', '782715600',
'792388800', '814856400', '823838400', '846219600', '855288000',
'877669200', '887428800', '909118800', '918792000', '940568400',
'950241600', '972709200', '981691200', '1004072400', '1013140800',
'1035522000', '1044590400', '1066971600', '1076731200', '1098421200',
'1108094400', '1129870800', '1139544000', '1162011600', '1170993600',
'1193374800', '1202443200', '1224824400', '1234584000', '1256274000',
'1265947200', '1287723600', '1297396800', '1319173200', '1328846400',
'1351227600', '1360296000', '1382677200', '1391745600', '1414126800',
'1423886400', '1445576400', '1455249600', '1477026000', '1486699200',
'1509166800', '1518148800', '1540530000', '1549598400', '1571979600',
'1581048000', '1603429200', '1613102400', '1634878800', '1644552000',
'1666328400', '1676001600', '1698469200', '1707451200', '1729832400',
'1738900800', '1761282000', '1771041600', '1792731600', '1802404800',
'1824181200', '1833854400', '1856322000', '1865304000', '1887685200',
'1896753600', '1919134800', '1928203200', '1950584400', '1960344000',
'1982034000', '1991707200', '2013483600', '2023156800', '2045624400',
'2054606400', '2076987600', '2086056000', '2108437200', '2118196800',
'2139886800',
],
'\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-10800, 0, 0), (-7200, 1, 4)], 'EST\x00EDT\x00'),
'Brazil/West': ('Brazil/West', 101, 2,
['561967200', '571640400', '593416800', '603090000', '625557600',
'634539600', '656920800', '665989200', '688370400', '697438800',
'719820000', '729493200', '751269600', '760942800', '782719200',
'792392400', '814860000', '823842000', '846223200', '855291600',
'877672800', '887432400', '909122400', '918795600', '940572000',
'950245200', '972712800', '981694800', '1004076000', '1013144400',
'1035525600', '1044594000', '1066975200', '1076734800', '1098424800',
'1108098000', '1129874400', '1139547600', '1162015200', '1170997200',
'1193378400', '1202446800', '1224828000', '1234587600', '1256277600',
'1265950800', '1287727200', '1297400400', '1319176800', '1328850000',
'1351231200', '1360299600', '1382680800', '1391749200', '1414130400',
'1423890000', '1445580000', '1455253200', '1477029600', '1486702800',
'1509170400', '1518152400', '1540533600', '1549602000', '1571983200',
'1581051600', '1603432800', '1613106000', '1634882400', '1644555600',
'1666332000', '1676005200', '1698472800', '1707454800', '1729836000',
'1738904400', '1761285600', '1771045200', '1792735200', '1802408400',
'1824184800', '1833858000', '1856325600', '1865307600', '1887688800',
'1896757200', '1919138400', '1928206800', '1950588000', '1960347600',
'1982037600', '1991710800', '2013487200', '2023160400', '2045628000',
'2054610000', '2076991200', '2086059600', '2108440800', '2118200400',
'2139890400',
],
'\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-14400, 0, 0), (-10800, 1, 4)], 'WST\x00WDT\x00'),
'Canada/Atlantic': ('Canada/Atlantic', 138, 2,
['-21492000', '-5770800', '9957600', '25678800', '41407200',
'57733200', '73461600', '89182800', '104911200', '120632400',
'136360800', '152082000', '167810400', '183531600', '199260000',
'215586000', '230709600', '247035600', '262764000', '278485200',
'294213600', '309934800', '325663200', '341384400', '357112800',
'372834000', '388562400', '404888400', '420012000', '436338000',
'452066400', '467787600', '483516000', '499237200', '514965600',
'530686800', '544600800', '562136400', '576050400', '594190800',
'607500000', '625640400', '638949600', '657090000', '671004000',
'688539600', '702453600', '719989200', '733903200', '752043600',
'765352800', '783493200', '796802400', '814942800', '828856800',
'846392400', '860306400', '877842000', '891756000', '909291600',
'923205600', '941346000', '954655200', '972795600', '986104800',
'1004245200', '1018159200', '1035694800', '1049608800', '1067144400',
'1081058400', '1099198800', '1112508000', '1130648400', '1143957600',
'1162098000', '1175407200', '1193547600', '1207461600', '1224997200',
'1238911200', '1256446800', '1270360800', '1288501200', '1301810400',
'1319950800', '1333260000', '1351400400', '1365314400', '1382850000',
'1396764000', '1414299600', '1428213600', '1445749200', '1459663200',
'1477803600', '1491112800', '1509253200', '1522562400', '1540702800',
'1554616800', '1572152400', '1586066400', '1603602000', '1617516000',
'1635656400', '1648965600', '1667106000', '1680415200', '1698555600',
'1712469600', '1730005200', '1743919200', '1761454800', '1775368800',
'1792904400', '1806818400', '1824958800', '1838268000', '1856408400',
'1869717600', '1887858000', '1901772000', '1919307600', '1933221600',
'1950757200', '1964671200', '1982811600', '1996120800', '2014261200',
'2027570400', '2045710800', '2059020000', '2077160400', '2091074400',
'2108610000', '2122524000', '2140059600',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-10800, 1, 0), (-14400, 0, 4)], 'ADT\x00AST\x00'),
'Canada/Central': ('Canada/Central', 138, 2,
['-21484800', '-5763600', '9964800', '25686000', '41414400',
'57740400', '73468800', '89190000', '104918400', '120639600',
'136368000', '152089200', '167817600', '183538800', '199267200',
'215593200', '230716800', '247042800', '262771200', '278492400',
'294220800', '309942000', '325670400', '341391600', '357120000',
'372841200', '388569600', '404895600', '420019200', '436345200',
'452073600', '467794800', '483523200', '499244400', '514972800',
'530694000', '544608000', '562143600', '576057600', '594198000',
'607507200', '625647600', '638956800', '657097200', '671011200',
'688546800', '702460800', '719996400', '733910400', '752050800',
'765360000', '783500400', '796809600', '814950000', '828864000',
'846399600', '860313600', '877849200', '891763200', '909298800',
'923212800', '941353200', '954662400', '972802800', '986112000',
'1004252400', '1018166400', '1035702000', '1049616000', '1067151600',
'1081065600', '1099206000', '1112515200', '1130655600', '1143964800',
'1162105200', '1175414400', '1193554800', '1207468800', '1225004400',
'1238918400', '1256454000', '1270368000', '1288508400', '1301817600',
'1319958000', '1333267200', '1351407600', '1365321600', '1382857200',
'1396771200', '1414306800', '1428220800', '1445756400', '1459670400',
'1477810800', '1491120000', '1509260400', '1522569600', '1540710000',
'1554624000', '1572159600', '1586073600', '1603609200', '1617523200',
'1635663600', '1648972800', '1667113200', '1680422400', '1698562800',
'1712476800', '1730012400', '1743926400', '1761462000', '1775376000',
'1792911600', '1806825600', '1824966000', '1838275200', '1856415600',
'1869724800', '1887865200', '1901779200', '1919314800', '1933228800',
'1950764400', '1964678400', '1982818800', '1996128000', '2014268400',
'2027577600', '2045718000', '2059027200', '2077167600', '2091081600',
'2108617200', '2122531200', '2140066800',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-18000, 1, 0), (-21600, 0, 4)], 'CDT\x00CST\x00'),
'Canada/East-Saskatchewan': ('Canada/East-Saskatchewan', 0, 1,
[],
'',
[(-21600, 0, 0)], 'CST\x00'),
'Canada/Eastern': ('Canada/Eastern', 138, 2,
['-21488400', '-5767200', '9961200', '25682400', '41410800',
'57736800', '73465200', '89186400', '104914800', '120636000',
'136364400', '152085600', '167814000', '183535200', '199263600',
'215589600', '230713200', '247039200', '262767600', '278488800',
'294217200', '309938400', '325666800', '341388000', '357116400',
'372837600', '388566000', '404892000', '420015600', '436341600',
'452070000', '467791200', '483519600', '499240800', '514969200',
'530690400', '544604400', '562140000', '576054000', '594194400',
'607503600', '625644000', '638953200', '657093600', '671007600',
'688543200', '702457200', '719992800', '733906800', '752047200',
'765356400', '783496800', '796806000', '814946400', '828860400',
'846396000', '860310000', '877845600', '891759600', '909295200',
'923209200', '941349600', '954658800', '972799200', '986108400',
'1004248800', '1018162800', '1035698400', '1049612400', '1067148000',
'1081062000', '1099202400', '1112511600', '1130652000', '1143961200',
'1162101600', '1175410800', '1193551200', '1207465200', '1225000800',
'1238914800', '1256450400', '1270364400', '1288504800', '1301814000',
'1319954400', '1333263600', '1351404000', '1365318000', '1382853600',
'1396767600', '1414303200', '1428217200', '1445752800', '1459666800',
'1477807200', '1491116400', '1509256800', '1522566000', '1540706400',
'1554620400', '1572156000', '1586070000', '1603605600', '1617519600',
'1635660000', '1648969200', '1667109600', '1680418800', '1698559200',
'1712473200', '1730008800', '1743922800', '1761458400', '1775372400',
'1792908000', '1806822000', '1824962400', '1838271600', '1856412000',
'1869721200', '1887861600', '1901775600', '1919311200', '1933225200',
'1950760800', '1964674800', '1982815200', '1996124400', '2014264800',
'2027574000', '2045714400', '2059023600', '2077164000', '2091078000',
'2108613600', '2122527600', '2140063200',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-14400, 1, 0), (-18000, 0, 4)], 'EDT\x00EST\x00'),
'Canada/Mountain': ('Canada/Mountain', 138, 2,
['-21481200', '-5760000', '9968400', '25689600', '41418000',
'57744000', '73472400', '89193600', '104922000', '120643200',
'136371600', '152092800', '167821200', '183542400', '199270800',
'215596800', '230720400', '247046400', '262774800', '278496000',
'294224400', '309945600', '325674000', '341395200', '357123600',
'372844800', '388573200', '404899200', '420022800', '436348800',
'452077200', '467798400', '483526800', '499248000', '514976400',
'530697600', '544611600', '562147200', '576061200', '594201600',
'607510800', '625651200', '638960400', '657100800', '671014800',
'688550400', '702464400', '720000000', '733914000', '752054400',
'765363600', '783504000', '796813200', '814953600', '828867600',
'846403200', '860317200', '877852800', '891766800', '909302400',
'923216400', '941356800', '954666000', '972806400', '986115600',
'1004256000', '1018170000', '1035705600', '1049619600', '1067155200',
'1081069200', '1099209600', '1112518800', '1130659200', '1143968400',
'1162108800', '1175418000', '1193558400', '1207472400', '1225008000',
'1238922000', '1256457600', '1270371600', '1288512000', '1301821200',
'1319961600', '1333270800', '1351411200', '1365325200', '1382860800',
'1396774800', '1414310400', '1428224400', '1445760000', '1459674000',
'1477814400', '1491123600', '1509264000', '1522573200', '1540713600',
'1554627600', '1572163200', '1586077200', '1603612800', '1617526800',
'1635667200', '1648976400', '1667116800', '1680426000', '1698566400',
'1712480400', '1730016000', '1743930000', '1761465600', '1775379600',
'1792915200', '1806829200', '1824969600', '1838278800', '1856419200',
'1869728400', '1887868800', '1901782800', '1919318400', '1933232400',
'1950768000', '1964682000', '1982822400', '1996131600', '2014272000',
'2027581200', '2045721600', '2059030800', '2077171200', '2091085200',
'2108620800', '2122534800', '2140070400',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-21600, 1, 0), (-25200, 0, 4)], 'MDT\x00MST\x00'),
'Canada/Newfoundland': ('Canada/Newfoundland', 138, 2,
['-21493800', '-5772600', '9955800', '25677000', '41405400',
'57731400', '73459800', '89181000', '104909400', '120630600',
'136359000', '152080200', '167808600', '183529800', '199258200',
'215584200', '230707800', '247033800', '262762200', '278483400',
'294211800', '309933000', '325661400', '341382600', '357111000',
'372832200', '388560600', '404886600', '420010200', '436336200',
'452064600', '467785800', '483514200', '499235400', '514963800',
'530685000', '544599000', '562134600', '576048600', '594189000',
'607498200', '625638600', '638947800', '657088200', '671002200',
'688537800', '702451800', '719987400', '733901400', '752041800',
'765351000', '783491400', '796800600', '814941000', '828855000',
'846390600', '860304600', '877840200', '891754200', '909289800',
'923203800', '941344200', '954653400', '972793800', '986103000',
'1004243400', '1018157400', '1035693000', '1049607000', '1067142600',
'1081056600', '1099197000', '1112506200', '1130646600', '1143955800',
'1162096200', '1175405400', '1193545800', '1207459800', '1224995400',
'1238909400', '1256445000', '1270359000', '1288499400', '1301808600',
'1319949000', '1333258200', '1351398600', '1365312600', '1382848200',
'1396762200', '1414297800', '1428211800', '1445747400', '1459661400',
'1477801800', '1491111000', '1509251400', '1522560600', '1540701000',
'1554615000', '1572150600', '1586064600', '1603600200', '1617514200',
'1635654600', '1648963800', '1667104200', '1680413400', '1698553800',
'1712467800', '1730003400', '1743917400', '1761453000', '1775367000',
'1792902600', '1806816600', '1824957000', '1838266200', '1856406600',
'1869715800', '1887856200', '1901770200', '1919305800', '1933219800',
'1950755400', '1964669400', '1982809800', '1996119000', '2014259400',
'2027568600', '2045709000', '2059018200', '2077158600', '2091072600',
'2108608200', '2122522200', '2140057800',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-9000, 1, 0), (-12600, 0, 4)], 'NDT\x00NST\x00'),
'Canada/Pacific': ('Canada/Pacific', 138, 2,
['-21477600', '-5756400', '9972000', '25693200', '41421600',
'57747600', '73476000', '89197200', '104925600', '120646800',
'136375200', '152096400', '167824800', '183546000', '199274400',
'215600400', '230724000', '247050000', '262778400', '278499600',
'294228000', '309949200', '325677600', '341398800', '357127200',
'372848400', '388576800', '404902800', '420026400', '436352400',
'452080800', '467802000', '483530400', '499251600', '514980000',
'530701200', '544615200', '562150800', '576064800', '594205200',
'607514400', '625654800', '638964000', '657104400', '671018400',
'688554000', '702468000', '720003600', '733917600', '752058000',
'765367200', '783507600', '796816800', '814957200', '828871200',
'846406800', '860320800', '877856400', '891770400', '909306000',
'923220000', '941360400', '954669600', '972810000', '986119200',
'1004259600', '1018173600', '1035709200', '1049623200', '1067158800',
'1081072800', '1099213200', '1112522400', '1130662800', '1143972000',
'1162112400', '1175421600', '1193562000', '1207476000', '1225011600',
'1238925600', '1256461200', '1270375200', '1288515600', '1301824800',
'1319965200', '1333274400', '1351414800', '1365328800', '1382864400',
'1396778400', '1414314000', '1428228000', '1445763600', '1459677600',
'1477818000', '1491127200', '1509267600', '1522576800', '1540717200',
'1554631200', '1572166800', '1586080800', '1603616400', '1617530400',
'1635670800', '1648980000', '1667120400', '1680429600', '1698570000',
'1712484000', '1730019600', '1743933600', '1761469200', '1775383200',
'1792918800', '1806832800', '1824973200', '1838282400', '1856422800',
'1869732000', '1887872400', '1901786400', '1919322000', '1933236000',
'1950771600', '1964685600', '1982826000', '1996135200', '2014275600',
'2027584800', '2045725200', '2059034400', '2077174800', '2091088800',
'2108624400', '2122538400', '2140074000',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-25200, 1, 0), (-28800, 0, 4)], 'PDT\x00PST\x00'),
'Canada/Yukon': ('Canada/Yukon', 138, 2,
['-21474000', '-5752800', '9975600', '25696800', '41425200',
'57751200', '73479600', '89200800', '104929200', '120650400',
'136378800', '152100000', '167828400', '183549600', '199278000',
'215604000', '230727600', '247053600', '262782000', '278503200',
'294231600', '309952800', '325681200', '341402400', '357130800',
'372852000', '388580400', '404906400', '420030000', '436356000',
'452084400', '467805600', '483534000', '499255200', '514983600',
'530704800', '544618800', '562154400', '576068400', '594208800',
'607518000', '625658400', '638967600', '657108000', '671022000',
'688557600', '702471600', '720007200', '733921200', '752061600',
'765370800', '783511200', '796820400', '814960800', '828874800',
'846410400', '860324400', '877860000', '891774000', '909309600',
'923223600', '941364000', '954673200', '972813600', '986122800',
'1004263200', '1018177200', '1035712800', '1049626800', '1067162400',
'1081076400', '1099216800', '1112526000', '1130666400', '1143975600',
'1162116000', '1175425200', '1193565600', '1207479600', '1225015200',
'1238929200', '1256464800', '1270378800', '1288519200', '1301828400',
'1319968800', '1333278000', '1351418400', '1365332400', '1382868000',
'1396782000', '1414317600', '1428231600', '1445767200', '1459681200',
'1477821600', '1491130800', '1509271200', '1522580400', '1540720800',
'1554634800', '1572170400', '1586084400', '1603620000', '1617534000',
'1635674400', '1648983600', '1667124000', '1680433200', '1698573600',
'1712487600', '1730023200', '1743937200', '1761472800', '1775386800',
'1792922400', '1806836400', '1824976800', '1838286000', '1856426400',
'1869735600', '1887876000', '1901790000', '1919325600', '1933239600',
'1950775200', '1964689200', '1982829600', '1996138800', '2014279200',
'2027588400', '2045728800', '2059038000', '2077178400', '2091092400',
'2108628000', '2122542000', '2140077600',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-28800, 1, 0), (-32400, 0, 4)], 'YDT\x00YST\x00'),
'Chile/Continental': ('Chile/Continental', 121, 2,
['245217600', '258519600', '276667200', '289969200', '308721600',
'321418800', '340171200', '352868400', '371620800', '384922800',
'403070400', '416372400', '434520000', '447822000', '466574400',
'479271600', '498024000', '510721200', '529473600', '542170800',
'560923200', '574225200', '592372800', '605674800', '623822400',
'637124400', '655876800', '668574000', '687326400', '700023600',
'718776000', '732078000', '750225600', '763527600', '781675200',
'794977200', '813124800', '826426800', '845179200', '857876400',
'876628800', '889326000', '908078400', '921380400', '939528000',
'952830000', '970977600', '984279600', '1003032000', '1015729200',
'1034481600', '1047178800', '1065931200', '1079233200', '1097380800',
'1110682800', '1128830400', '1142132400', '1160280000', '1173582000',
'1192334400', '1205031600', '1223784000', '1236481200', '1255233600',
'1268535600', '1286683200', '1299985200', '1318132800', '1331434800',
'1350187200', '1362884400', '1381636800', '1394334000', '1413086400',
'1425783600', '1444536000', '1457838000', '1475985600', '1489287600',
'1507435200', '1520737200', '1539489600', '1552186800', '1570939200',
'1583636400', '1602388800', '1615690800', '1633838400', '1647140400',
'1665288000', '1678590000', '1696737600', '1710039600', '1728792000',
'1741489200', '1760241600', '1772938800', '1791691200', '1804993200',
'1823140800', '1836442800', '1854590400', '1867892400', '1886644800',
'1899342000', '1918094400', '1930791600', '1949544000', '1962846000',
'1980993600', '1994295600', '2012443200', '2025745200', '2043892800',
'2057194800', '2075947200', '2088644400', '2107396800', '2120094000',
'2138846400',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00',
[(-10800, 1, 0), (-14400, 0, 4)], 'CDT\x00CST\x00'),
'Chile/EasterIsland': ('Chile/EasterIsland', 121, 2,
['245224800', '258526800', '276674400', '289976400', '308728800',
'321426000', '340178400', '352875600', '371628000', '384930000',
'403077600', '416379600', '434527200', '447829200', '466581600',
'479278800', '498031200', '510728400', '529480800', '542178000',
'560930400', '574232400', '592380000', '605682000', '623829600',
'637131600', '655884000', '668581200', '687333600', '700030800',
'718783200', '732085200', '750232800', '763534800', '781682400',
'794984400', '813132000', '826434000', '845186400', '857883600',
'876636000', '889333200', '908085600', '921387600', '939535200',
'952837200', '970984800', '984286800', '1003039200', '1015736400',
'1034488800', '1047186000', '1065938400', '1079240400', '1097388000',
'1110690000', '1128837600', '1142139600', '1160287200', '1173589200',
'1192341600', '1205038800', '1223791200', '1236488400', '1255240800',
'1268542800', '1286690400', '1299992400', '1318140000', '1331442000',
'1350194400', '1362891600', '1381644000', '1394341200', '1413093600',
'1425790800', '1444543200', '1457845200', '1475992800', '1489294800',
'1507442400', '1520744400', '1539496800', '1552194000', '1570946400',
'1583643600', '1602396000', '1615698000', '1633845600', '1647147600',
'1665295200', '1678597200', '1696744800', '1710046800', '1728799200',
'1741496400', '1760248800', '1772946000', '1791698400', '1805000400',
'1823148000', '1836450000', '1854597600', '1867899600', '1886652000',
'1899349200', '1918101600', '1930798800', '1949551200', '1962853200',
'1981000800', '1994302800', '2012450400', '2025752400', '2043900000',
'2057202000', '2075954400', '2088651600', '2107404000', '2120101200',
'2138853600',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00',
[(-18000, 1, 0), (-21600, 0, 4)], 'EDT\x00EST\x00'),
'Cuba': ('Cuba', 118, 2,
['290581200', '308721600', '322030800', '340171200', '358318800',
'371620800', '389768400', '403070400', '421218000', '434520000',
'453272400', '466574400', '484722000', '498024000', '516171600',
'529473600', '547621200', '560923200', '579070800', '592372800',
'611125200', '623822400', '642574800', '655876800', '674024400',
'687326400', '705474000', '718776000', '736923600', '750225600',
'768373200', '781675200', '800427600', '813124800', '831877200',
'845179200', '863326800', '876628800', '894776400', '908078400',
'926226000', '939528000', '958280400', '970977600', '989730000',
'1003032000', '1021179600', '1034481600', '1052629200', '1065931200',
'1084078800', '1097380800', '1115528400', '1128830400', '1147582800',
'1160280000', '1179032400', '1192334400', '1210482000', '1223784000',
'1241931600', '1255233600', '1273381200', '1286683200', '1304830800',
'1318132800', '1336885200', '1350187200', '1368334800', '1381636800',
'1399784400', '1413086400', '1431234000', '1444536000', '1462683600',
'1475985600', '1494738000', '1507435200', '1526187600', '1539489600',
'1557637200', '1570939200', '1589086800', '1602388800', '1620536400',
'1633838400', '1651986000', '1665288000', '1684040400', '1696737600',
'1715490000', '1728792000', '1746939600', '1760241600', '1778389200',
'1791691200', '1809838800', '1823140800', '1841893200', '1854590400',
'1873342800', '1886644800', '1904792400', '1918094400', '1936242000',
'1949544000', '1967691600', '1980993600', '1999141200', '2012443200',
'2031195600', '2043892800', '2062645200', '2075947200', '2094094800',
'2107396800', '2125544400', '2138846400',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-14400, 1, 0), (-18000, 0, 4)], 'CDT\x00CST\x00'),
'Egypt': ('Egypt', 152, 2,
['-305164800', '-291949200', '-273628800', '-260413200', '-242092800',
'-228877200', '-210556800', '-197341200', '-178934400', '-165718800',
'-147398400', '-134182800', '-115862400', '-102646800', '-84326400',
'-71110800', '-52704000', '-39488400', '-21168000', '-7952400',
'10368000', '23583600', '41904000', '55119600', '73526400',
'86742000', '105062400', '118278000', '136598400', '149814000',
'168134400', '181350000', '199756800', '212972400', '231292800',
'244508400', '262828800', '276044400', '294364800', '307580400',
'325987200', '339202800', '420595200', '433810800', '452217600',
'465433200', '483753600', '496969200', '515289600', '528505200',
'546825600', '560041200', '578448000', '591663600', '609984000',
'623199600', '641520000', '654735600', '673056000', '686271600',
'704678400', '717894000', '736214400', '749430000', '767750400',
'780966000', '799286400', '812502000', '830908800', '844124400',
'862444800', '875660400', '893980800', '907196400', '925516800',
'938732400', '957139200', '970354800', '988675200', '1001890800',
'1020211200', '1033426800', '1051747200', '1064962800', '1083369600',
'1096585200', '1114905600', '1128121200', '1146441600', '1159657200',
'1177977600', '1191193200', '1209600000', '1222815600', '1241136000',
'1254351600', '1272672000', '1285887600', '1304208000', '1317423600',
'1335830400', '1349046000', '1367366400', '1380582000', '1398902400',
'1412118000', '1430438400', '1443654000', '1462060800', '1475276400',
'1493596800', '1506812400', '1525132800', '1538348400', '1556668800',
'1569884400', '1588291200', '1601506800', '1619827200', '1633042800',
'1651363200', '1664578800', '1682899200', '1696114800', '1714521600',
'1727737200', '1746057600', '1759273200', '1777593600', '1790809200',
'1809129600', '1822345200', '1840752000', '1853967600', '1872288000',
'1885503600', '1903824000', '1917039600', '1935360000', '1948575600',
'1966982400', '1980198000', '1998518400', '2011734000', '2030054400',
'2043270000', '2061590400', '2074806000', '2093212800', '2106428400',
'2124748800', '2137964400',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(10800, 1, 0), (7200, 0, 8)], 'EET DST\x00EET\x00'),
'GB-Eire': ('GB-Eire', 241, 4,
['-1697238000', '-1680476400', '-1664146800', '-1650150000', '-1633906800',
'-1617490800', '-1601852400', '-1586041200', '-1570402800', '-1552172400',
'-1538348400', '-1522537200', '-1507503600', '-1490569200', '-1473634800',
'-1458342000', '-1441321200', '-1428879600', '-1410735600', '-1396220400',
'-1379286000', '-1364770800', '-1347836400', '-1333321200', '-1316386800',
'-1301266800', '-1284332400', '-1269817200', '-1252882800', '-1238367600',
'-1221433200', '-1206918000', '-1189983600', '-1175468400', '-1158534000',
'-1144018800', '-1127084400', '-1111964400', '-1095030000', '-1080514800',
'-1063580400', '-1049065200', '-1032130800', '-1017615600', '-1000681200',
'-986166000', '-969231600', '-950482800', '-942015600', '-904518000',
'-896050800', '-875487600', '-864601200', '-844038000', '-832546800',
'-812588400', '-798073200', '-781052400', '-772066800', '-764809200',
'-748479600', '-733359600', '-719449200', '-717030000', '-706748400',
'-699490800', '-687999600', '-668041200', '-654735600', '-636591600',
'-622076400', '-605746800', '-590626800', '-574297200', '-558572400',
'-542242800', '-527122800', '-512607600', '-496278000', '-481158000',
'-464223600', '-449708400', '-432774000', '-417654000', '-401324400',
'-386204400', '-369270000', '-354754800', '-337820400', '-323305200',
'-306975600', '-291855600', '-276735600', '-257986800', '-245286000',
'-226537200', '-213231600', '-195087600', '-182386800', '-163638000',
'-150937200', '-132188400', '-119487600', '-100738800', '-88038000',
'-68684400', '-59007600', '-37238400', '57715200', '69814800',
'89168400', '101264400', '120618000', '132714000', '152067600',
'164163600', '183517200', '196218000', '214966800', '227667600',
'246416400', '259117200', '278470800', '290566800', '309920400',
'322016400', '341370000', '354675600', '372819600', '386125200',
'404269200', '417574800', '435718800', '449024400', '467773200',
'481078800', '499222800', '512528400', '530672400', '543978000',
'562122000', '575427600', '593571600', '606877200', '625626000',
'638326800', '657075600', '670381200', '688525200', '701830800',
'719974800', '733280400', '751424400', '764730000', '782874000',
'796179600', '814928400', '828234000', '846378000', '859683600',
'877827600', '891133200', '909277200', '922582800', '940726800',
'954032400', '972781200', '985482000', '1004230800', '1017536400',
'1035680400', '1048986000', '1067130000', '1080435600', '1098579600',
'1111885200', '1130029200', '1143334800', '1162083600', '1174784400',
'1193533200', '1206838800', '1224982800', '1238288400', '1256432400',
'1269738000', '1287882000', '1301187600', '1319331600', '1332637200',
'1351386000', '1364691600', '1382835600', '1396141200', '1414285200',
'1427590800', '1445734800', '1459040400', '1477184400', '1490490000',
'1509238800', '1521939600', '1540688400', '1553994000', '1572138000',
'1585443600', '1603587600', '1616893200', '1635037200', '1648342800',
'1666486800', '1679792400', '1698541200', '1711846800', '1729990800',
'1743296400', '1761440400', '1774746000', '1792890000', '1806195600',
'1824339600', '1837645200', '1856394000', '1869094800', '1887843600',
'1901149200', '1919293200', '1932598800', '1950742800', '1964048400',
'1982192400', '1995498000', '2013642000', '2026947600', '2045696400',
'2058397200', '2077146000', '2090451600', '2108595600', '2121901200',
'2140045200',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x02\x00\x02\x00\x02\x00\x02\x00\x02\x00\x01\x00\x01\x00\x02\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x03\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(3600, 1, 0), (0, 0, 4), (7200, 1, 8), (3600, 0, 0)], 'BST\x00GMT\x00DST\x00'),
'GMT': ('GMT', 0, 1,
[],
'',
[(0, 0, 0)], 'GMT\x00'),
'GMT+0': ('GMT+0', 0, 1,
[],
'',
[(0, 0, 0)], 'GMT+0000\x00'),
'GMT+0130': ('GMT+0130', 0, 1,
[],
'',
[(5400, 0, 0)], 'GMT+0130\x00'),
'GMT+0230': ('GMT+0230', 0, 1,
[],
'',
[(9000, 0, 0)], 'GMT+0230\x00'),
'GMT+0330': ('GMT+0330', 0, 1,
[],
'',
[(12600, 0, 0)], 'GMT+0330\x00'),
'GMT+0430': ('GMT+0430', 0, 1,
[],
'',
[(16200, 0, 0)], 'GMT+0430\x00'),
'GMT+0530': ('GMT+0530', 0, 1,
[],
'',
[(19800, 0, 0)], 'GMT+0530\x00'),
'GMT+0630': ('GMT+0630', 0, 1,
[],
'',
[(23400, 0, 0)], 'GMT+0630\x00'),
'GMT+0730': ('GMT+0730', 0, 1,
[],
'',
[(27000, 0, 0)], 'GMT+0730\x00'),
'GMT+0830': ('GMT+0830', 0, 1,
[],
'',
[(30600, 0, 0)], 'GMT+0830\x00'),
'GMT+0930': ('GMT+0930', 0, 1,
[],
'',
[(34200, 0, 0)], 'GMT+0930\x00'),
'GMT+1': ('GMT+1', 0, 1,
[],
'',
[(3600, 0, 0)], 'GMT+0100\x00'),
'GMT+10': ('GMT+10', 0, 1,
[],
'',
[(36000, 0, 0)], 'GMT+1000\x00'),
'GMT+1030': ('GMT+1030', 0, 1,
[],
'',
[(37800, 0, 0)], 'GMT+1030\x00'),
'GMT+11': ('GMT+11', 0, 1,
[],
'',
[(39600, 0, 0)], 'GMT+1100\x00'),
'GMT+1130': ('GMT+1130', 0, 1,
[],
'',
[(41400, 0, 0)], 'GMT+1130\x00'),
'GMT+12': ('GMT+12', 0, 1,
[],
'',
[(43200, 0, 0)], 'GMT+1200\x00'),
'GMT+1230': ('GMT+1230', 0, 1,
[],
'',
[(45000, 0, 0)], 'GMT+1230\x00'),
'GMT+13': ('GMT+13', 0, 1,
[],
'',
[(46800, 0, 0)], 'GMT+1300\x00'),
'GMT+2': ('GMT+2', 0, 1,
[],
'',
[(7200, 0, 0)], 'GMT+0200\x00'),
'GMT+3': ('GMT+3', 0, 1,
[],
'',
[(10800, 0, 0)], 'GMT+0300\x00'),
'GMT+4': ('GMT+4', 0, 1,
[],
'',
[(14400, 0, 0)], 'GMT+0400\x00'),
'GMT+5': ('GMT+5', 0, 1,
[],
'',
[(18000, 0, 0)], 'GMT+0500\x00'),
'GMT+6': ('GMT+6', 0, 1,
[],
'',
[(21600, 0, 0)], 'GMT+0600\x00'),
'GMT+7': ('GMT+7', 0, 1,
[],
'',
[(25200, 0, 0)], 'GMT+0700\x00'),
'GMT+8': ('GMT+8', 0, 1,
[],
'',
[(28800, 0, 0)], 'GMT+0800\x00'),
'GMT+9': ('GMT+9', 0, 1,
[],
'',
[(32400, 0, 0)], 'GMT+0900\x00'),
'GMT-0130': ('GMT-0130', 0, 1,
[],
'',
[(-5400, 0, 0)], 'GMT-0130\x00'),
'GMT-0230': ('GMT-0230', 0, 1,
[],
'',
[(-9000, 0, 0)], 'GMT-0230\x00'),
'GMT-0330': ('GMT-0330', 0, 1,
[],
'',
[(-12600, 0, 0)], 'GMT-0330\x00'),
'GMT-0430': ('GMT-0430', 0, 1,
[],
'',
[(-16200, 0, 0)], 'GMT-0430\x00'),
'GMT-0530': ('GMT-0530', 0, 1,
[],
'',
[(-19800, 0, 0)], 'GMT-0530\x00'),
'GMT-0630': ('GMT-0630', 0, 1,
[],
'',
[(-23400, 0, 0)], 'GMT-0630\x00'),
'GMT-0730': ('GMT-0730', 0, 1,
[],
'',
[(-27000, 0, 0)], 'GMT-0730\x00'),
'GMT-0830': ('GMT-0830', 0, 1,
[],
'',
[(-30600, 0, 0)], 'GMT-0830\x00'),
'GMT-0930': ('GMT-0930', 0, 1,
[],
'',
[(-34200, 0, 0)], 'GMT-0930\x00'),
'GMT-1': ('GMT-1', 0, 1,
[],
'',
[(-3600, 0, 0)], 'GMT-0100\x00'),
'GMT-10': ('GMT-10', 0, 1,
[],
'',
[(-36000, 0, 0)], 'GMT-1000\x00'),
'GMT-1030': ('GMT-1030', 0, 1,
[],
'',
[(-37800, 0, 0)], 'GMT-1030\x00'),
'GMT-11': ('GMT-11', 0, 1,
[],
'',
[(-39600, 0, 0)], 'GMT-1100\x00'),
'GMT-1130': ('GMT-1130', 0, 1,
[],
'',
[(-41400, 0, 0)], 'GMT-1130\x00'),
'GMT-12': ('GMT-12', 0, 1,
[],
'',
[(-43200, 0, 0)], 'GMT-1200\x00'),
'GMT-1230': ('GMT-1230', 0, 1,
[],
'',
[(-45000, 0, 0)], 'GMT-1230\x00'),
'GMT-2': ('GMT-2', 0, 1,
[],
'',
[(-7200, 0, 0)], 'GMT-0200\x00'),
'GMT-3': ('GMT-3', 0, 1,
[],
'',
[(-10800, 0, 0)], 'GMT-0300\x00'),
'GMT-4': ('GMT-4', 0, 1,
[],
'',
[(-14400, 0, 0)], 'GMT-0400\x00'),
'GMT-5': ('GMT-5', 0, 1,
[],
'',
[(-18000, 0, 0)], 'GMT-0500\x00'),
'GMT-6': ('GMT-6', 0, 1,
[],
'',
[(-21600, 0, 0)], 'GMT-0600\x00'),
'GMT-7': ('GMT-7', 0, 1,
[],
'',
[(-25200, 0, 0)], 'GMT-0700\x00'),
'GMT-8': ('GMT-8', 0, 1,
[],
'',
[(-28800, 0, 0)], 'GMT-0800\x00'),
'GMT-9': ('GMT-9', 0, 1,
[],
'',
[(-32400, 0, 0)], 'GMT-0900\x00'),
'Greenwich': ('Greenwich', 0, 1,
[],
'',
[(0, 0, 0)], 'GMT\x00'),
'Hongkong': ('Hongkong', 0, 1,
[],
'',
[(28800, 0, 0)], 'HKT\x00'),
'Iceland': ('Iceland', 0, 1,
[],
'',
[(0, 0, 0)], 'WET\x00'),
'Iran': ('Iran', 100, 2,
['575418600', '590535000', '606868200', '621984600', '638317800',
'653434200', '670372200', '684883800', '701821800', '716938200',
'733271400', '748387800', '764721000', '779837400', '796170600',
'811287000', '828225000', '842736600', '859674600', '874791000',
'891124200', '906240600', '922573800', '937690200', '954023400',
'969139800', '985473000', '1000589400', '1017527400', '1032039000',
'1048977000', '1064093400', '1080426600', '1095543000', '1111876200',
'1126992600', '1143325800', '1158442200', '1174775400', '1189891800',
'1206829800', '1221946200', '1238279400', '1253395800', '1269729000',
'1284845400', '1301178600', '1316295000', '1332628200', '1347744600',
'1364682600', '1379194200', '1396132200', '1411248600', '1427581800',
'1442698200', '1459031400', '1474147800', '1490481000', '1505597400',
'1521930600', '1537047000', '1553985000', '1568496600', '1585434600',
'1600551000', '1616884200', '1632000600', '1648333800', '1663450200',
'1679783400', '1694899800', '1711837800', '1726349400', '1743287400',
'1758403800', '1774737000', '1789853400', '1806186600', '1821303000',
'1837636200', '1852752600', '1869085800', '1884202200', '1901140200',
'1915651800', '1932589800', '1947706200', '1964039400', '1979155800',
'1995489000', '2010605400', '2026938600', '2042055000', '2058388200',
'2073504600', '2090442600', '2105559000', '2121892200', '2137008600',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(16200, 1, 0), (12600, 0, 4)], 'IDT\x00IST\x00'),
'Israel': ('Israel', 42, 2,
['609890400', '622587600', '640735200', '653432400', '670975200',
'683672400', '704239200', '716936400', '735084000', '747781200',
'765324000', '778021200', '798588000', '811285200', '829432800',
'842130000', '862696800', '875394000', '892936800', '905634000',
'923781600', '936478800', '957045600', '969742800', '987285600',
'999982800', '1018130400', '1030827600', '1051394400', '1064091600',
'1082239200', '1094936400', '1114898400', '1127595600', '1145743200',
'1158440400', '1176588000', '1189285200', '1209247200', '1221944400',
'1240092000', '1252789200',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(10800, 1, 0), (7200, 0, 4)], 'IDT\x00IST\x00'),
'Jamaica': ('Jamaica', 148, 3,
['-1633280400', '-1615140000', '-1601830800', '-1583690400', '-880218000',
'-765396000', '-84387600', '-68666400', '-52938000', '-37216800',
'-21488400', '-5767200', '9961200', '25682400', '41410800',
'57736800', '73465200', '89186400', '104914800', '120636000',
'126687600', '152085600', '162370800', '183535200', '199263600',
'215589600', '230713200', '247039200', '262767600', '278488800',
'294217200', '309938400', '325666800', '341388000', '357116400',
'372837600', '388566000', '404892000', '420015600', '436341600',
'452070000', '467791200', '483519600', '499240800', '514969200',
'530690400', '544604400', '562140000', '576054000', '594194400',
'607503600', '625644000', '638953200', '657093600', '671007600',
'688543200', '702457200', '719992800', '733906800', '752047200',
'765356400', '783496800', '796806000', '814946400', '828860400',
'846396000', '860310000', '877845600', '891759600', '909295200',
'923209200', '941349600', '954658800', '972799200', '986108400',
'1004248800', '1018162800', '1035698400', '1049612400', '1067148000',
'1081062000', '1099202400', '1112511600', '1130652000', '1143961200',
'1162101600', '1175410800', '1193551200', '1207465200', '1225000800',
'1238914800', '1256450400', '1270364400', '1288504800', '1301814000',
'1319954400', '1333263600', '1351404000', '1365318000', '1382853600',
'1396767600', '1414303200', '1428217200', '1445752800', '1459666800',
'1477807200', '1491116400', '1509256800', '1522566000', '1540706400',
'1554620400', '1572156000', '1586070000', '1603605600', '1617519600',
'1635660000', '1648969200', '1667109600', '1680418800', '1698559200',
'1712473200', '1730008800', '1743922800', '1761458400', '1775372400',
'1792908000', '1806822000', '1824962400', '1838271600', '1856412000',
'1869721200', '1887861600', '1901775600', '1919311200', '1933225200',
'1950760800', '1964674800', '1982815200', '1996124400', '2014264800',
'2027574000', '2045714400', '2059023600', '2077164000', '2091078000',
'2108613600', '2122527600', '2140063200',
],
'\x00\x01\x00\x01\x02\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-14400, 1, 0), (-18000, 0, 4), (-14400, 1, 8)], 'EDT\x00EST\x00EWT\x00'),
'Japan': ('Japan', 0, 1,
[],
'',
[(32400, 0, 0)], 'JST\x00'),
'Mexico/BajaNorte': ('Mexico/BajaNorte', 102, 2,
['544615200', '562150800', '576064800', '594205200', '607514400',
'625654800', '638964000', '657104400', '671018400', '688554000',
'702468000', '720003600', '733917600', '752058000', '765367200',
'783507600', '796816800', '814957200', '828871200', '846406800',
'860320800', '877856400', '891770400', '909306000', '923220000',
'941360400', '954669600', '972810000', '986119200', '1004259600',
'1018173600', '1035709200', '1049623200', '1067158800', '1081072800',
'1099213200', '1112522400', '1130662800', '1143972000', '1162112400',
'1175421600', '1193562000', '1207476000', '1225011600', '1238925600',
'1256461200', '1270375200', '1288515600', '1301824800', '1319965200',
'1333274400', '1351414800', '1365328800', '1382864400', '1396778400',
'1414314000', '1428228000', '1445763600', '1459677600', '1477818000',
'1491127200', '1509267600', '1522576800', '1540717200', '1554631200',
'1572166800', '1586080800', '1603616400', '1617530400', '1635670800',
'1648980000', '1667120400', '1680429600', '1698570000', '1712484000',
'1730019600', '1743933600', '1761469200', '1775383200', '1792918800',
'1806832800', '1824973200', '1838282400', '1856422800', '1869732000',
'1887872400', '1901786400', '1919322000', '1933236000', '1950771600',
'1964685600', '1982826000', '1996135200', '2014275600', '2027584800',
'2045725200', '2059034400', '2077174800', '2091088800', '2108624400',
'2122538400', '2140074000',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-25200, 1, 0), (-28800, 0, 4)], 'PDT\x00PST\x00'),
'Mexico/BajaSur': ('Mexico/BajaSur', 0, 1,
[],
'',
[(-25200, 0, 0)], 'MST\x00'),
'Mexico/General': ('Mexico/General', 0, 1,
[],
'',
[(-21600, 0, 0)], 'CST\x00'),
'Poland': ('Poland', 104, 2,
['512524800', '528249600', '543974400', '559699200', '575424000',
'591148800', '606873600', '622598400', '638323200', '654652800',
'670377600', '686102400', '701827200', '717552000', '733276800',
'749001600', '764726400', '780451200', '796176000', '811900800',
'828230400', '843955200', '859680000', '875404800', '891129600',
'906854400', '922579200', '938304000', '954028800', '969753600',
'985478400', '1001808000', '1017532800', '1033257600', '1048982400',
'1064707200', '1080432000', '1096156800', '1111881600', '1127606400',
'1143331200', '1159056000', '1174780800', '1191110400', '1206835200',
'1222560000', '1238284800', '1254009600', '1269734400', '1285459200',
'1301184000', '1316908800', '1332633600', '1348963200', '1364688000',
'1380412800', '1396137600', '1411862400', '1427587200', '1443312000',
'1459036800', '1474761600', '1490486400', '1506211200', '1521936000',
'1538265600', '1553990400', '1569715200', '1585440000', '1601164800',
'1616889600', '1632614400', '1648339200', '1664064000', '1679788800',
'1695513600', '1711843200', '1727568000', '1743292800', '1759017600',
'1774742400', '1790467200', '1806192000', '1821916800', '1837641600',
'1853366400', '1869091200', '1885420800', '1901145600', '1916870400',
'1932595200', '1948320000', '1964044800', '1979769600', '1995494400',
'2011219200', '2026944000', '2042668800', '2058393600', '2074723200',
'2090448000', '2106172800', '2121897600', '2137622400',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(7200, 1, 0), (3600, 0, 8)], 'MET DST\x00MET\x00'),
'Singapore': ('Singapore', 0, 1,
[],
'',
[(28800, 0, 0)], 'SST\x00'),
'Turkey': ('Turkey', 104, 2,
['512517600', '528238800', '543967200', '559688400', '575416800',
'591138000', '606866400', '622587600', '638316000', '654642000',
'670370400', '686091600', '701820000', '717541200', '733269600',
'748990800', '764719200', '780440400', '796168800', '811890000',
'828223200', '843944400', '859672800', '875394000', '891122400',
'906843600', '922572000', '938293200', '954021600', '969742800',
'985471200', '1001797200', '1017525600', '1033246800', '1048975200',
'1064696400', '1080424800', '1096146000', '1111874400', '1127595600',
'1143324000', '1159045200', '1174773600', '1191099600', '1206828000',
'1222549200', '1238277600', '1253998800', '1269727200', '1285448400',
'1301176800', '1316898000', '1332626400', '1348952400', '1364680800',
'1380402000', '1396130400', '1411851600', '1427580000', '1443301200',
'1459029600', '1474750800', '1490479200', '1506200400', '1521928800',
'1538254800', '1553983200', '1569704400', '1585432800', '1601154000',
'1616882400', '1632603600', '1648332000', '1664053200', '1679781600',
'1695502800', '1711836000', '1727557200', '1743285600', '1759006800',
'1774735200', '1790456400', '1806184800', '1821906000', '1837634400',
'1853355600', '1869084000', '1885410000', '1901138400', '1916859600',
'1932588000', '1948309200', '1964037600', '1979758800', '1995487200',
'2011208400', '2026936800', '2042658000', '2058386400', '2074712400',
'2090440800', '2106162000', '2121890400', '2137611600',
],
'\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(14400, 1, 0), (10800, 0, 8)], 'EET DST\x00EET\x00'),
'US/Alaska': ('US/Alaska', 148, 3,
['-1633266000', '-1615125600', '-1601816400', '-1583676000', '-880203600',
'-765381600', '-84373200', '-68652000', '-52923600', '-37202400',
'-21474000', '-5752800', '9975600', '25696800', '41425200',
'57751200', '73479600', '89200800', '104929200', '120650400',
'126702000', '152100000', '162385200', '183549600', '199278000',
'215604000', '230727600', '247053600', '262782000', '278503200',
'294231600', '309952800', '325681200', '341402400', '357130800',
'372852000', '388580400', '404906400', '420030000', '436356000',
'452084400', '467805600', '483534000', '499255200', '514983600',
'530704800', '544618800', '562154400', '576068400', '594208800',
'607518000', '625658400', '638967600', '657108000', '671022000',
'688557600', '702471600', '720007200', '733921200', '752061600',
'765370800', '783511200', '796820400', '814960800', '828874800',
'846410400', '860324400', '877860000', '891774000', '909309600',
'923223600', '941364000', '954673200', '972813600', '986122800',
'1004263200', '1018177200', '1035712800', '1049626800', '1067162400',
'1081076400', '1099216800', '1112526000', '1130666400', '1143975600',
'1162116000', '1175425200', '1193565600', '1207479600', '1225015200',
'1238929200', '1256464800', '1270378800', '1288519200', '1301828400',
'1319968800', '1333278000', '1351418400', '1365332400', '1382868000',
'1396782000', '1414317600', '1428231600', '1445767200', '1459681200',
'1477821600', '1491130800', '1509271200', '1522580400', '1540720800',
'1554634800', '1572170400', '1586084400', '1603620000', '1617534000',
'1635674400', '1648983600', '1667124000', '1680433200', '1698573600',
'1712487600', '1730023200', '1743937200', '1761472800', '1775386800',
'1792922400', '1806836400', '1824976800', '1838286000', '1856426400',
'1869735600', '1887876000', '1901790000', '1919325600', '1933239600',
'1950775200', '1964689200', '1982829600', '1996138800', '2014279200',
'2027588400', '2045728800', '2059038000', '2077178400', '2091092400',
'2108628000', '2122542000', '2140077600',
],
'\x00\x01\x00\x01\x02\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-28800, 1, 0), (-32400, 0, 5), (-28800, 1, 10)], 'AKDT\x00AKST\x00AKWT\x00'),
'US/Aleutian': ('US/Aleutian', 149, 5,
['-1633262400', '-1615122000', '-1601812800', '-1583672400', '-880200000',
'-765378000', '-84369600', '-68648400', '-52920000', '-37198800',
'-21470400', '-5749200', '9979200', '25700400', '41428800',
'57754800', '73483200', '89204400', '104932800', '120654000',
'126705600', '152103600', '162388800', '183553200', '199281600',
'215607600', '230731200', '247057200', '262785600', '278506800',
'294235200', '309956400', '325684800', '341406000', '357134400',
'372855600', '388584000', '404910000', '420033600', '436359600',
'439034400', '452088000', '467809200', '483537600', '499258800',
'514987200', '530708400', '544622400', '562158000', '576072000',
'594212400', '607521600', '625662000', '638971200', '657111600',
'671025600', '688561200', '702475200', '720010800', '733924800',
'752065200', '765374400', '783514800', '796824000', '814964400',
'828878400', '846414000', '860328000', '877863600', '891777600',
'909313200', '923227200', '941367600', '954676800', '972817200',
'986126400', '1004266800', '1018180800', '1035716400', '1049630400',
'1067166000', '1081080000', '1099220400', '1112529600', '1130670000',
'1143979200', '1162119600', '1175428800', '1193569200', '1207483200',
'1225018800', '1238932800', '1256468400', '1270382400', '1288522800',
'1301832000', '1319972400', '1333281600', '1351422000', '1365336000',
'1382871600', '1396785600', '1414321200', '1428235200', '1445770800',
'1459684800', '1477825200', '1491134400', '1509274800', '1522584000',
'1540724400', '1554638400', '1572174000', '1586088000', '1603623600',
'1617537600', '1635678000', '1648987200', '1667127600', '1680436800',
'1698577200', '1712491200', '1730026800', '1743940800', '1761476400',
'1775390400', '1792926000', '1806840000', '1824980400', '1838289600',
'1856430000', '1869739200', '1887879600', '1901793600', '1919329200',
'1933243200', '1950778800', '1964692800', '1982833200', '1996142400',
'2014282800', '2027592000', '2045732400', '2059041600', '2077182000',
'2091096000', '2108631600', '2122545600', '2140081200',
],
'\x00\x01\x00\x01\x02\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03\x04\x03',
[(-32400, 1, 0), (-36000, 0, 5), (-32400, 1, 10), (-36000, 0, 15), (-32400, 1, 20)], 'AHDT\x00AHST\x00AHWT\x00HAST\x00HADT\x00'),
'US/Arizona': ('US/Arizona', 6, 3,
['-1633273200', '-1615132800', '-1601823600', '-1583683200', '-880210800',
'-765388800',
],
'\x00\x01\x00\x01\x02\x01',
[(-21600, 1, 0), (-25200, 0, 4), (-21600, 1, 8)], 'MDT\x00MST\x00MWT\x00'),
'US/Central': ('US/Central', 148, 3,
['-1633276800', '-1615136400', '-1601827200', '-1583686800', '-880214400',
'-765392400', '-84384000', '-68662800', '-52934400', '-37213200',
'-21484800', '-5763600', '9964800', '25686000', '41414400',
'57740400', '73468800', '89190000', '104918400', '120639600',
'126691200', '152089200', '162374400', '183538800', '199267200',
'215593200', '230716800', '247042800', '262771200', '278492400',
'294220800', '309942000', '325670400', '341391600', '357120000',
'372841200', '388569600', '404895600', '420019200', '436345200',
'452073600', '467794800', '483523200', '499244400', '514972800',
'530694000', '544608000', '562143600', '576057600', '594198000',
'607507200', '625647600', '638956800', '657097200', '671011200',
'688546800', '702460800', '719996400', '733910400', '752050800',
'765360000', '783500400', '796809600', '814950000', '828864000',
'846399600', '860313600', '877849200', '891763200', '909298800',
'923212800', '941353200', '954662400', '972802800', '986112000',
'1004252400', '1018166400', '1035702000', '1049616000', '1067151600',
'1081065600', '1099206000', '1112515200', '1130655600', '1143964800',
'1162105200', '1175414400', '1193554800', '1207468800', '1225004400',
'1238918400', '1256454000', '1270368000', '1288508400', '1301817600',
'1319958000', '1333267200', '1351407600', '1365321600', '1382857200',
'1396771200', '1414306800', '1428220800', '1445756400', '1459670400',
'1477810800', '1491120000', '1509260400', '1522569600', '1540710000',
'1554624000', '1572159600', '1586073600', '1603609200', '1617523200',
'1635663600', '1648972800', '1667113200', '1680422400', '1698562800',
'1712476800', '1730012400', '1743926400', '1761462000', '1775376000',
'1792911600', '1806825600', '1824966000', '1838275200', '1856415600',
'1869724800', '1887865200', '1901779200', '1919314800', '1933228800',
'1950764400', '1964678400', '1982818800', '1996128000', '2014268400',
'2027577600', '2045718000', '2059027200', '2077167600', '2091081600',
'2108617200', '2122531200', '2140066800',
],
'\x00\x01\x00\x01\x02\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-18000, 1, 0), (-21600, 0, 4), (-18000, 1, 8)], 'CDT\x00CST\x00CWT\x00'),
'US/East-Indiana': ('US/East-Indiana', 6, 3,
['-1633280400', '-1615140000', '-1601830800', '-1583690400', '-880218000',
'-765396000',
],
'\x00\x01\x00\x01\x02\x01',
[(-14400, 1, 0), (-18000, 0, 4), (-14400, 1, 8)], 'EDT\x00EST\x00EWT\x00'),
'US/Eastern': ('US/Eastern', 148, 3,
['-1633280400', '-1615140000', '-1601830800', '-1583690400', '-880218000',
'-765396000', '-84387600', '-68666400', '-52938000', '-37216800',
'-21488400', '-5767200', '9961200', '25682400', '41410800',
'57736800', '73465200', '89186400', '104914800', '120636000',
'126687600', '152085600', '162370800', '183535200', '199263600',
'215589600', '230713200', '247039200', '262767600', '278488800',
'294217200', '309938400', '325666800', '341388000', '357116400',
'372837600', '388566000', '404892000', '420015600', '436341600',
'452070000', '467791200', '483519600', '499240800', '514969200',
'530690400', '544604400', '562140000', '576054000', '594194400',
'607503600', '625644000', '638953200', '657093600', '671007600',
'688543200', '702457200', '719992800', '733906800', '752047200',
'765356400', '783496800', '796806000', '814946400', '828860400',
'846396000', '860310000', '877845600', '891759600', '909295200',
'923209200', '941349600', '954658800', '972799200', '986108400',
'1004248800', '1018162800', '1035698400', '1049612400', '1067148000',
'1081062000', '1099202400', '1112511600', '1130652000', '1143961200',
'1162101600', '1175410800', '1193551200', '1207465200', '1225000800',
'1238914800', '1256450400', '1270364400', '1288504800', '1301814000',
'1319954400', '1333263600', '1351404000', '1365318000', '1382853600',
'1396767600', '1414303200', '1428217200', '1445752800', '1459666800',
'1477807200', '1491116400', '1509256800', '1522566000', '1540706400',
'1554620400', '1572156000', '1586070000', '1603605600', '1617519600',
'1635660000', '1648969200', '1667109600', '1680418800', '1698559200',
'1712473200', '1730008800', '1743922800', '1761458400', '1775372400',
'1792908000', '1806822000', '1824962400', '1838271600', '1856412000',
'1869721200', '1887861600', '1901775600', '1919311200', '1933225200',
'1950760800', '1964674800', '1982815200', '1996124400', '2014264800',
'2027574000', '2045714400', '2059023600', '2077164000', '2091078000',
'2108613600', '2122527600', '2140063200',
],
'\x00\x01\x00\x01\x02\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-14400, 1, 0), (-18000, 0, 4), (-14400, 1, 8)], 'EDT\x00EST\x00EWT\x00'),
'US/Hawaii': ('US/Hawaii', 9, 4,
['-1633260600', '-1615120200', '-1601811000', '-1583670600', '-1157283000',
'-1157200200', '-880198200', '-765376200', '-712150200',
],
'\x00\x01\x00\x01\x00\x01\x02\x01\x03',
[(-34200, 1, 0), (-37800, 0, 4), (-34200, 1, 8), (-36000, 0, 4)], 'HDT\x00HST\x00HWT\x00'),
'US/Indiana-Starke': ('US/Indiana-Starke', 56, 4,
['-1633276800', '-1615136400', '-1601827200', '-1583686800', '-880214400',
'-765392400', '-84384000', '-68662800', '-52934400', '-37213200',
'-21484800', '-5763600', '9964800', '25686000', '41414400',
'57740400', '73468800', '89190000', '104918400', '120639600',
'126691200', '152089200', '162374400', '183538800', '199267200',
'215593200', '230716800', '247042800', '262771200', '278492400',
'294220800', '309942000', '325670400', '341391600', '357120000',
'372841200', '388569600', '404895600', '420019200', '436345200',
'452073600', '467794800', '483523200', '499244400', '514972800',
'530694000', '544608000', '562143600', '576057600', '594198000',
'607507200', '625647600', '638956800', '657097200', '671011200',
'688546800',
],
'\x00\x01\x00\x01\x02\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x03',
[(-18000, 1, 0), (-21600, 0, 4), (-18000, 1, 8), (-18000, 0, 12)], 'CDT\x00CST\x00CWT\x00EST\x00'),
'US/Michigan': ('US/Michigan', 138, 3,
['-1633280400', '-1615140000', '-1601830800', '-1583690400', '-880218000',
'-765396000', '-84387600', '-68666400', '104914800', '120636000',
'126687600', '152085600', '162370800', '183535200', '199263600',
'215589600', '230713200', '247039200', '262767600', '278488800',
'294217200', '309938400', '325666800', '341388000', '357116400',
'372837600', '388566000', '404892000', '420015600', '436341600',
'452070000', '467791200', '483519600', '499240800', '514969200',
'530690400', '544604400', '562140000', '576054000', '594194400',
'607503600', '625644000', '638953200', '657093600', '671007600',
'688543200', '702457200', '719992800', '733906800', '752047200',
'765356400', '783496800', '796806000', '814946400', '828860400',
'846396000', '860310000', '877845600', '891759600', '909295200',
'923209200', '941349600', '954658800', '972799200', '986108400',
'1004248800', '1018162800', '1035698400', '1049612400', '1067148000',
'1081062000', '1099202400', '1112511600', '1130652000', '1143961200',
'1162101600', '1175410800', '1193551200', '1207465200', '1225000800',
'1238914800', '1256450400', '1270364400', '1288504800', '1301814000',
'1319954400', '1333263600', '1351404000', '1365318000', '1382853600',
'1396767600', '1414303200', '1428217200', '1445752800', '1459666800',
'1477807200', '1491116400', '1509256800', '1522566000', '1540706400',
'1554620400', '1572156000', '1586070000', '1603605600', '1617519600',
'1635660000', '1648969200', '1667109600', '1680418800', '1698559200',
'1712473200', '1730008800', '1743922800', '1761458400', '1775372400',
'1792908000', '1806822000', '1824962400', '1838271600', '1856412000',
'1869721200', '1887861600', '1901775600', '1919311200', '1933225200',
'1950760800', '1964674800', '1982815200', '1996124400', '2014264800',
'2027574000', '2045714400', '2059023600', '2077164000', '2091078000',
'2108613600', '2122527600', '2140063200',
],
'\x00\x01\x00\x01\x02\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-14400, 1, 0), (-18000, 0, 4), (-14400, 1, 8)], 'EDT\x00EST\x00EWT\x00'),
'US/Mountain': ('US/Mountain', 148, 3,
['-1633273200', '-1615132800', '-1601823600', '-1583683200', '-880210800',
'-765388800', '-84380400', '-68659200', '-52930800', '-37209600',
'-21481200', '-5760000', '9968400', '25689600', '41418000',
'57744000', '73472400', '89193600', '104922000', '120643200',
'126694800', '152092800', '162378000', '183542400', '199270800',
'215596800', '230720400', '247046400', '262774800', '278496000',
'294224400', '309945600', '325674000', '341395200', '357123600',
'372844800', '388573200', '404899200', '420022800', '436348800',
'452077200', '467798400', '483526800', '499248000', '514976400',
'530697600', '544611600', '562147200', '576061200', '594201600',
'607510800', '625651200', '638960400', '657100800', '671014800',
'688550400', '702464400', '720000000', '733914000', '752054400',
'765363600', '783504000', '796813200', '814953600', '828867600',
'846403200', '860317200', '877852800', '891766800', '909302400',
'923216400', '941356800', '954666000', '972806400', '986115600',
'1004256000', '1018170000', '1035705600', '1049619600', '1067155200',
'1081069200', '1099209600', '1112518800', '1130659200', '1143968400',
'1162108800', '1175418000', '1193558400', '1207472400', '1225008000',
'1238922000', '1256457600', '1270371600', '1288512000', '1301821200',
'1319961600', '1333270800', '1351411200', '1365325200', '1382860800',
'1396774800', '1414310400', '1428224400', '1445760000', '1459674000',
'1477814400', '1491123600', '1509264000', '1522573200', '1540713600',
'1554627600', '1572163200', '1586077200', '1603612800', '1617526800',
'1635667200', '1648976400', '1667116800', '1680426000', '1698566400',
'1712480400', '1730016000', '1743930000', '1761465600', '1775379600',
'1792915200', '1806829200', '1824969600', '1838278800', '1856419200',
'1869728400', '1887868800', '1901782800', '1919318400', '1933232400',
'1950768000', '1964682000', '1982822400', '1996131600', '2014272000',
'2027581200', '2045721600', '2059030800', '2077171200', '2091085200',
'2108620800', '2122534800', '2140070400',
],
'\x00\x01\x00\x01\x02\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-21600, 1, 0), (-25200, 0, 4), (-21600, 1, 8)], 'MDT\x00MST\x00MWT\x00'),
'US/Pacific': ('US/Pacific', 148, 3,
['-1633269600', '-1615129200', '-1601820000', '-1583679600', '-880207200',
'-765385200', '-84376800', '-68655600', '-52927200', '-37206000',
'-21477600', '-5756400', '9972000', '25693200', '41421600',
'57747600', '73476000', '89197200', '104925600', '120646800',
'126698400', '152096400', '162381600', '183546000', '199274400',
'215600400', '230724000', '247050000', '262778400', '278499600',
'294228000', '309949200', '325677600', '341398800', '357127200',
'372848400', '388576800', '404902800', '420026400', '436352400',
'452080800', '467802000', '483530400', '499251600', '514980000',
'530701200', '544615200', '562150800', '576064800', '594205200',
'607514400', '625654800', '638964000', '657104400', '671018400',
'688554000', '702468000', '720003600', '733917600', '752058000',
'765367200', '783507600', '796816800', '814957200', '828871200',
'846406800', '860320800', '877856400', '891770400', '909306000',
'923220000', '941360400', '954669600', '972810000', '986119200',
'1004259600', '1018173600', '1035709200', '1049623200', '1067158800',
'1081072800', '1099213200', '1112522400', '1130662800', '1143972000',
'1162112400', '1175421600', '1193562000', '1207476000', '1225011600',
'1238925600', '1256461200', '1270375200', '1288515600', '1301824800',
'1319965200', '1333274400', '1351414800', '1365328800', '1382864400',
'1396778400', '1414314000', '1428228000', '1445763600', '1459677600',
'1477818000', '1491127200', '1509267600', '1522576800', '1540717200',
'1554631200', '1572166800', '1586080800', '1603616400', '1617530400',
'1635670800', '1648980000', '1667120400', '1680429600', '1698570000',
'1712484000', '1730019600', '1743933600', '1761469200', '1775383200',
'1792918800', '1806832800', '1824973200', '1838282400', '1856422800',
'1869732000', '1887872400', '1901786400', '1919322000', '1933236000',
'1950771600', '1964685600', '1982826000', '1996135200', '2014275600',
'2027584800', '2045725200', '2059034400', '2077174800', '2091088800',
'2108624400', '2122538400', '2140074000',
],
'\x00\x01\x00\x01\x02\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01',
[(-25200, 1, 0), (-28800, 0, 4), (-25200, 1, 8)], 'PDT\x00PST\x00PWT\x00'),
'US/Samoa': ('US/Samoa', 2, 3,
['-86878800', '439038000',
],
'\x01\x02',
[(-39600, 0, 0), (-39600, 0, 4), (-39600, 0, 8)], 'NST\x00BST\x00SST\x00'),
'Universal': ('Universal', 0, 1,
[],
'',
[(0, 0, 0)], 'GMT\x00'),
}
def dumpTimezoneInfo(_data, out=None):
if out is None: # pragma: no cover
import sys
out = sys.stdout
print("historical_zone_info = {", file=out)
items = sorted(_data.items())
for key, value in items:
v1, v2, v3, ilist, bitmap, two_by_three, two_nullterm = value
print("'{}': ('{}', {}, {},".format(key, v1, v2, v3), file=out)
print("[", end='', file=out)
while ilist:
next_5, ilist = ilist[:5], ilist[5:]
line = ", ".join(["'%s'" % x for x in next_5])
print("%s," % line, file=out)
print("], ", file=out)
print("%s," % repr(bitmap), file=out)
print("{}, {}),".format(repr(two_by_three), repr(two_nullterm)), file=out)
print("}", file=out)
if __name__ == '__main__':
dumpTimezoneInfo(historical_zone_info) | zope.datetime | /zope.datetime-5.0.0.tar.gz/zope.datetime-5.0.0/src/zope/datetime/timezones.py | timezones.py |
=====
API
=====
.. currentmodule:: zope.datetime
Parsing Strings
===============
This module defines three functions for parsing strings.
.. autofunction:: parse(string, local=True) -> tuple
.. autofunction:: parseDatetimetz
.. autofunction:: time(string) -> float
The functions :func:`parse` and :func:`time` are both methods of an
instance of the :class:`DateTimeParser` class. This is an immutable,
stateless class.
.. autoclass:: DateTimeParser
:exclude-members: parse, time
.. function:: parse(self, string, local=True)
The same as :func:`parse`.
.. function:: time(self, string)
The same as :func:`time`.
Formatting Strings
==================
This module defines a few convenience functions for producing
formatted date strings.
.. autofunction:: iso8601_date
.. autofunction:: rfc850_date
.. autofunction:: rfc1123_date
Exceptions
==========
This module defines an exception tree that it uses to report errors.
.. autoclass:: DateTimeError
.. autoclass:: DateError
.. autoclass:: TimeError
.. autoclass:: SyntaxError
| zope.datetime | /zope.datetime-5.0.0.tar.gz/zope.datetime-5.0.0/docs/api.rst | api.rst |
=========
Changes
=========
5.0 (2023-06-29)
================
- Drop support for Python 2.7, 3.5, 3.6.
- Add support for Python 3.11.
4.4 (2021-12-10)
================
- Add support for Python 3.8, 3.9 and 3.10.
- Drop support for Python 3.4.
4.3.1 (2019-08-05)
==================
- Avoid race condition in ``deferredmodule.ModuleProxy.__getattr__``
`#8 <https://github.com/zopefoundation/zope.deferredimport/issues/8>`_.
4.3 (2018-10-05)
================
- Add support for Python 3.7.
4.2.1 (2017-10-24)
==================
- Preserve the docstrings of proxied modules created with
``deprecatedFrom``, ``deferredFrom``, etc. See `issue 5
<https://github.com/zopefoundation/zope.deferredimport/issues/5>`_.
4.2.0 (2017-08-08)
==================
- Add support for Python 3.5 and 3.6.
- Drop support for Python 2.6 and 3.3.
- Convert doctests to Sphinx documentation, including building docs
and running doctest snippets under ``tox``.
4.1.0 (2014-12-26)
==================
- Add support for PyPy. PyPy3 support is blocked on release of fix for:
https://bitbucket.org/pypy/pypy/issue/1946
- Add support for Python 3.4.
- Add support for testing on Travis.
4.0.0 (2013-02-28)
==================
- Add support for Python 3.3.
- Drop support for Python 2.4 and 2.5.
3.5.3 (2010-09-25)
==================
- Add test extra to declare test dependency on ``zope.testing``.
3.5.2 (2010-05-24)
==================
- Fix unit tests broken under Python 2.4 by the switch to the standard
library ``doctest`` module.
3.5.1 (2010-04-30)
==================
- Prefer the standard library's ``doctest`` module to the one from
``zope.testing``.
3.5.0 (2009-02-04)
==================
- Add support to bootstrap on Jython.
- Add reference documentation.
3.4.0 (2007-07-19)
==================
- Finish release of ``zope.deferredimport``.
3.4.0b1 (2007-07-09)
====================
- Initial release as a separate project, corresponding to the
``zope.deferredimport`` from Zope 3.4.0b1.
| zope.deferredimport | /zope.deferredimport-5.0.tar.gz/zope.deferredimport-5.0/CHANGES.rst | CHANGES.rst |
=========================
``zope.deferredimport``
=========================
.. image:: https://img.shields.io/pypi/v/zope.deferredimport.svg
:target: https://pypi.python.org/pypi/zope.deferredimport/
:alt: Latest release
.. image:: https://img.shields.io/pypi/pyversions/zope.deferredimport.svg
:target: https://pypi.org/project/zope.deferredimport/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/zope.deferredimport/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/zope.deferredimport/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/zope.deferredimport/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/zope.deferredimport?branch=master
.. image:: https://readthedocs.org/projects/zopedeferredimport/badge/?version=latest
:target: http://zopedeferredimport.readthedocs.io/en/latest/
:alt: Documentation Status
Often, especially for package modules, you want to import names for
convenience, but not actually perform the imports until necessary.
The zope.deferredimport package provided facilities for defining names
in modules that will be imported from somewhere else when used. You
can also cause deprecation warnings to be issued when a variable is
used.
Documentation is hosted at https://zopedeferredimport.readthedocs.io/
| zope.deferredimport | /zope.deferredimport-5.0.tar.gz/zope.deferredimport-5.0/README.rst | README.rst |
"""Modules with defered attributes
"""
import sys
import warnings
import zope.proxy
class Deferred:
def __init__(self, name, specifier):
self.__name__ = name
self.specifier = specifier
_import_chicken = {}, {}, ['*']
def get(self):
specifier = self.specifier
if ':' in specifier:
module, name = specifier.split(':')
else:
module, name = specifier, ''
v = __import__(module, *self._import_chicken)
if name:
for n in name.split('.'):
v = getattr(v, n)
return v
class DeferredAndDeprecated(Deferred):
def __init__(self, name, specifier, message):
super().__init__(name, specifier)
self.message = message
def get(self):
warnings.warn(
self.__name__ + " is deprecated. " + self.message,
DeprecationWarning, stacklevel=3)
return super().get()
class ModuleProxy(zope.proxy.ProxyBase):
__slots__ = ('__deferred_definitions__', '__doc__')
def __init__(self, module):
super().__init__(module)
self.__deferred_definitions__ = {}
self.__doc__ = module.__doc__
def __getattr__(self, name):
try:
get = self.__deferred_definitions__[name]
except KeyError:
raise AttributeError(name)
v = get.get()
setattr(self, name, v)
try:
del self.__deferred_definitions__[name]
except KeyError: # pragma: no cover
pass
return v
def initialize(level=1):
"""Prepare a module to support deferred imports.
Modules do not need to call this directly, because the
`define*` and `deprecated*` functions call it.
This is intended to be called from the module to be prepared.
The implementation wraps a proxy around the module and replaces
the entry in sys.modules with the proxy. It does no harm to
call this function more than once for a given module, because
this function does not re-wrap a proxied module.
The level parameter specifies a relative stack depth.
When this function is called directly by the module, level should be 1.
When this function is called by a helper function, level should
increase with the depth of the stack.
Returns nothing when level is 1; otherwise returns the proxied module.
"""
__name__ = sys._getframe(level).f_globals['__name__']
module = sys.modules[__name__]
if type(module) is not ModuleProxy:
module = ModuleProxy(module)
sys.modules[__name__] = module
if level == 1:
return
return module
def define(**names):
"""Define deferred imports using keyword parameters.
Each parameter specifies the importable name and how to import it.
Use `module:name` syntax to import a name from a module, or `module`
(no colon) to import a module.
"""
module = initialize(2)
__deferred_definitions__ = module.__deferred_definitions__
for name, specifier in names.items():
__deferred_definitions__[name] = Deferred(name, specifier)
def defineFrom(from_name, *names):
"""Define deferred imports from a particular module.
The from_name specifies which module to import.
The rest of the parameters specify names to import from that module.
"""
module = initialize(2)
__deferred_definitions__ = module.__deferred_definitions__
for name in names:
specifier = from_name + ':' + name
__deferred_definitions__[name] = Deferred(name, specifier)
def deprecated(message, **names):
"""Define deferred and deprecated imports using keyword parameters.
The first use of each name will generate a deprecation warning with
the given message.
Each parameter specifies the importable name and how to import it.
Use `module:name` syntax to import a name from a module, or `module`
(no colon) to import a module.
"""
module = initialize(2)
__deferred_definitions__ = module.__deferred_definitions__
for name, specifier in names.items():
__deferred_definitions__[name] = DeferredAndDeprecated(
name, specifier, message)
def deprecatedFrom(message, from_name, *names):
"""Define deferred and deprecated imports from a particular module.
The first use of each name will generate a deprecation warning with
the given message.
The from_name specifies which module to import.
The rest of the parameters specify names to import from that module.
"""
module = initialize(2)
__deferred_definitions__ = module.__deferred_definitions__
for name in names:
specifier = from_name + ':' + name
__deferred_definitions__[name] = DeferredAndDeprecated(
name, specifier, message) | zope.deferredimport | /zope.deferredimport-5.0.tar.gz/zope.deferredimport-5.0/src/zope/deferredimport/deferredmodule.py | deferredmodule.py |
==================
Deferred Imports
==================
.. testsetup::
import os
import sys
import warnings
import zope.deferredimport
__file__ = 'docs/narrative.rst'
class OutErr(object):
@staticmethod
def write(message):
sys.stdout.write(message)
oldstderr, sys.stderr = sys.stderr, OutErr()
tmp_d = os.path.join(
os.path.dirname(zope.deferredimport.__file__), 'samples')
zope.deferredimport.__path__.append(tmp_d)
created_modules = []
def create_module(**modules): #**
for name, src in modules.items():
fn = os.path.join(tmp_d, name + '.py')
needs_update = True
if os.path.exists(fn):
with open(fn, 'r') as file:
needs_update = file.read() != src
if needs_update:
with open(fn, 'w') as file:
file.write(src)
created_modules.append(name)
def warn(message, type_, stacklevel):
frame = sys._getframe(stacklevel)
path = frame.f_globals['__file__']
file = open(path)
lineno = frame.f_lineno
for i in range(lineno):
line = file.readline()
file.close()
print("%s:%s: %s: %s\n %s" % (
path,
frame.f_lineno,
type_.__name__,
message,
line.strip(),
))
oldwarn, warnings.warn = warnings.warn, warn
Often, especially for package modules, you want to import names for
convenience, but not actually perform the imports until necessary.
The zope.deferredimport package provided facilities for defining names
in modules that will be imported from somewhere else when used. You
can also cause deprecation warnings to be issued when a variable is
used, but we'll get to that later.
The :func:`zope.deferredimport.define` function can be used to define one or
more names to be imported when they are accessed. Simply provide
names as keyword arguments with import specifiers as values. The
import specifiers are given as strings of the form "module:name",
where module is the dotted name of the module and name is a, possibly
dotted, name of an object within the module.
To see how this works, we'll create some sample modules within the
zope.deferredimport package. We'll actually use a helper function
specific to this document to define the modules inline so we can
easily see what's in them. Let's start by defining a module, sample1,
that defined some things to be imported:
.. doctest::
>>> create_module(sample1 = '''
... print("Sampe 1 imported!")
...
... x = 1
...
...
... class C:
... y = 2
...
...
... z = 3
... q = 4
... ''')
Note that the module starts by printing a message. This allows us to
see when the module is actually imported. Now, let's define a module
that imports some names from this module:
.. doctest::
>>> create_module(sample2 = '''
... import zope.deferredimport
...
... zope.deferredimport.define(
... sample1='zope.deferredimport.sample1',
... one='zope.deferredimport.sample1:x',
... two='zope.deferredimport.sample1:C.y',
... )
...
... three = 3
... x = 4
...
...
... def getx():
... return x
... ''')
In this example, we defined the name 'sample1' as the module
zope.deferredimport.sample1. The module isn't imported immediately,
but will be imported when needed. Similarly, the name 'one' is
defined as the 'x' attribute of sample1.
The sample1 module prints a message when it is
imported. When we import sample2, we don't see a message until we
access a variable:
.. doctest::
>>> import zope.deferredimport.sample2
>>> print(zope.deferredimport.sample2.one)
Sampe 1 imported!
1
>>> import zope.deferredimport.sample1
>>> zope.deferredimport.sample2.sample1 is zope.deferredimport.sample1
True
Note that a deferred attribute appears in a module's dictionary *after*
it is accessed the first time:
.. doctest::
>>> 'two' in zope.deferredimport.sample2.__dict__
False
>>> zope.deferredimport.sample2.two
2
>>> 'two' in zope.deferredimport.sample2.__dict__
True
When deferred imports are used, the original module is replaced with a
proxy.
.. doctest::
>>> type(zope.deferredimport.sample2)
<class 'zope.deferredimport.deferredmodule.ModuleProxy'>
But we can use the proxy just like the original. We can even update
it.
.. doctest::
>>> zope.deferredimport.sample2.x=5
>>> zope.deferredimport.sample2.getx()
5
And the inspect module thinks it's a module:
.. doctest::
>>> import inspect
>>> inspect.ismodule(zope.deferredimport.sample2)
True
In the example above, the modules were fairly simple. Let's look at a
more complicated example.
.. doctest::
# >>> create_module(sample3 = '''
# ...
# ... import zope.deferredimport
# ... import zope.deferredimport.sample4
# ...
# ... zope.deferredimport.define(
# ... sample1 = 'zope.deferredimport.sample1',
# ... one = 'zope.deferredimport.sample1:x',
# ... two = 'zope.deferredimport.sample1:C.y',
# ... )
# ...
# ... x = 1
# ...
# ... ''')
# >>> create_module(sample4 = '''
# ... import sample3
# ...
# ... def getone():
# ... return sample3.one
# ...
# ... ''')
Here, we have a circular import between sample3 and sample4. When
sample3 is imported, it imports sample 4, which then imports sample3.
Let's see what happens when we use these modules in an unfortunate
order:
.. code-block:: python
# XXX: Relative imports like this are not possible on Python 3 anymore.
# PY2
#
# >>> import zope.deferredimport.sample3
# >>> import zope.deferredimport.sample4
#
# >>> zope.deferredimport.sample4.getone()
# Traceback (most recent call last):
# ...
# AttributeError: 'module' object has no attribute 'one'
#
#Hm. Let's try accessing one through sample3:
#
# >>> zope.deferredimport.sample3.one
# 1
#
#Funny, let's try getone again:
#
# >>> zope.deferredimport.sample4.getone()
# 1
The problem is that sample4 obtained sample3 before sample4 was
replaced by a proxy. This example is slightly pathological because it
requires a circular import and a relative import, but the bug
introduced is very subtle. To guard against this, you should define
deferred imports before importing any other modules. Alternatively,
you can call the initialize function before importing any other
modules, as in:
.. doctest::
>>> create_module(sample5 = '''
... import zope.deferredimport
... zope.deferredimport.initialize()
...
... import zope.deferredimport.sample6 # noqa: E402 import not at top
...
... zope.deferredimport.define(
... sample1='zope.deferredimport.sample1',
... one='zope.deferredimport.sample1:x',
... two='zope.deferredimport.sample1:C.y',
... )
...
... x = 1
... ''')
>>> create_module(sample6 = '''
... import zope.deferredimport.sample5
...
...
... def getone():
... return zope.deferredimport.sample5.one
... ''')
>>> import zope.deferredimport.sample5
>>> import zope.deferredimport.sample6
>>> zope.deferredimport.sample6.getone()
1
Deprecation
===========
Deferred attributes can also be marked as deprecated, in which case, a
message will be printed the first time they are accessed.
Lets define a module that has deprecated attributes defined as
deferred imports:
.. doctest::
>>> create_module(sample7 = '''
... import zope.deferredimport
... zope.deferredimport.initialize()
...
... zope.deferredimport.deprecated(
... "Import from sample1 instead",
... x='zope.deferredimport.sample1:x',
... y='zope.deferredimport.sample1:C.y',
... z='zope.deferredimport.sample1:z',
... )
... ''')
Now, if we use one of these variables, we'll get a deprecation
warning:
.. doctest::
>>> import zope.deferredimport.sample7
>>> zope.deferredimport.sample7.x # doctest: +NORMALIZE_WHITESPACE
docs/narrative.rst:1: DeprecationWarning:
x is deprecated. Import from sample1 instead
==================
1
but only the first time:
.. doctest::
>>> zope.deferredimport.sample7.x
1
Importing multiple names from the same module
=============================================
Sometimes, you want to get multiple things from the same module. You
can use :func:`~.defineFrom` or :func:`~.deprecatedFrom` to do that:
.. doctest::
>>> create_module(sample8 = '''
... import zope.deferredimport
...
... zope.deferredimport.deprecatedFrom(
... "Import from sample1 instead",
... 'zope.deferredimport.sample1',
... 'x', 'z', 'q',
... )
...
... zope.deferredimport.defineFrom(
... 'zope.deferredimport.sample9',
... 'a', 'b', 'c',
... )
... ''')
>>> create_module(sample9 = '''
... print('Imported sample 9')
... a, b, c = range(10, 13)
... ''')
>>> import zope.deferredimport.sample8
>>> zope.deferredimport.sample8.q #doctest: +NORMALIZE_WHITESPACE
docs/narrative.rst:1: DeprecationWarning:
q is deprecated. Import from sample1 instead
==================
4
>>> zope.deferredimport.sample8.c
Imported sample 9
12
Note, as in the example above, that you can make multiple
deferred-import calls in a module.
.. testcleanup::
sys.stderr = oldstderr
warnings.warn = oldwarn
zope.deferredimport.__path__.pop()
for name in created_modules:
sys.modules.pop(name, None)
| zope.deferredimport | /zope.deferredimport-5.0.tar.gz/zope.deferredimport-5.0/docs/narrative.rst | narrative.rst |
import sys
import token
import tokenize
from zope.dependencytool.dependency import Dependency
START = "<start>"
FROM = "<from>"
FROM_IMPORT = "<from-import>"
IMPORT = "<import>"
COLLECTING = "<collecting>"
SWALLOWING = "<swallowing>" # used to swallow "as foo"
TOK_COMMA = (token.OP, ",")
TOK_IMPORT = (token.NAME, "import")
TOK_FROM = (token.NAME, "from")
TOK_NEWLINE = (token.NEWLINE, "\n")
TOK_ENDMARK = (token.ENDMARKER, "")
dotjoin = ".".join
class ImportFinder(object):
def __init__(self, packages=False):
"""Initialize the import finder.
`packages` -- if true, reports package names rather than
module names
"""
self.packages = packages
self.module_checks = {}
self.deps = []
self.imported_names = {}
def get_imports(self):
return self.deps
def find_imports(self, f, path, package=None):
"""Find all the imported names in a source file.
`f` -- open file
`path` -- path of the source file
`package` -- Python package the source file is contained in, or None
"""
self.path = path
self.package = package
self.state = START
self.post_name_state = None
prevline = None
try:
for t in tokenize.generate_tokens(f.readline):
type, string, start, end, line = t
self.transition(type, string, start[0])
except:
print >>sys.stderr, "error finding imports in", path
raise
def add_import(self, name, lineno):
"""Record an import for `name`.
`name` -- full dotted name as found in an import statement
(may still be relative)
`lineno` -- line number the import was found on
"""
# is this a relative import?
if self.package:
fullname = "%s.%s" % (self.package, name)
self.check_module_name(fullname)
if not self.module_checks[fullname]:
fullname = fullname[:fullname.rfind(".")]
self.check_module_name(fullname)
if self.module_checks[fullname]:
# this was a relative import; use the full name:
name = fullname
if name not in self.module_checks:
self.check_module_name(name)
if not self.module_checks[name] and "." in name:
# if "." isn't in name, I'd be very surprised!
# i'd also be surprised if the result *isn't* a module
name = dotjoin(name.split(".")[:-1])
self.check_module_name(name)
# A few oddball cases import __main__ (support for
# command-line scripts), so we need to filter that out.
if self.module_checks[name] and name != "__main__":
if self.packages:
name = package_for_module(name)
if name is None:
# just drop it on the floor, since we're not
# interested in bare modules
return
self.deps.append(Dependency(name, self.path, lineno))
def check_module_name(self, name):
"""Check whether 'name' is a module name. Update module_checks."""
try:
__import__(name)
except ImportError:
self.module_checks[name] = False
else:
self.module_checks[name] = name in sys.modules
def transition(self, type, string, lineno):
if type == tokenize.COMMENT:
return
entry = self.state_table.get((self.state, (type, string)))
if entry is not None:
self.state = entry[0]
for action in entry[2:]:
meth = getattr(self, "action_" + action)
meth(type, string, lineno)
if entry[1] is not None:
self.post_name_state = entry[1]
# gotta figure out what to do:
elif self.state == COLLECTING:
# watch for "as" used as syntax
name = self.name
if type == token.NAME and name and not name.endswith("."):
self.state = SWALLOWING
if self.prefix:
self.name = "%s.%s" % (self.prefix, name)
else:
self.name += string
elif self.state in (START, SWALLOWING):
pass
else:
raise RuntimeError(
"invalid transition: %s %r" % (self.state, (type, string)))
state_table = {
# (state, token): (new_state, saved_state, action...),
(START, TOK_IMPORT): (COLLECTING, IMPORT, "reset"),
(START, TOK_FROM): (COLLECTING, FROM, "reset"),
(FROM, TOK_IMPORT): (COLLECTING, FROM_IMPORT, "setprefix"),
(FROM_IMPORT, TOK_COMMA): (COLLECTING, FROM_IMPORT),
(IMPORT, TOK_COMMA): (COLLECTING, IMPORT),
(COLLECTING, TOK_COMMA): (COLLECTING, None, "save", "poststate"),
(COLLECTING, TOK_IMPORT): (COLLECTING, FROM_IMPORT, "setprefix"),
(SWALLOWING, TOK_COMMA): (None, None, "save", "poststate"),
# Commented-out transitions are syntax errors, so shouldn't
# ever be seen in working code.
# end of line:
#(START, TOK_NEWLINE): (START, None, "save", "reset"),
#(FROM, TOK_NEWLINE): (START, None, "save", "reset"),
(FROM_IMPORT, TOK_NEWLINE): (START, None, "save", "reset"),
#(IMPORT, TOK_NEWLINE): (START, None, "save", "reset"),
(COLLECTING, TOK_NEWLINE): (START, None, "save", "reset"),
(SWALLOWING, TOK_NEWLINE): (START, None, "save", "reset"),
# end of input:
#(START, TOK_ENDMARK): (START, None, "save", "reset"),
#(FROM, TOK_ENDMARK): (START, None, "save", "reset"),
(FROM_IMPORT, TOK_ENDMARK): (START, None, "save", "reset"),
#(IMPORT, TOK_ENDMARK): (START, None, "save", "reset"),
(COLLECTING, TOK_ENDMARK): (START, None, "save", "reset"),
(SWALLOWING, TOK_ENDMARK): (START, None, "save", "reset"),
}
def action_reset(self, type, string, lineno):
self.name = ''
self.prefix = None
def action_save(self, type, string, lineno):
if self.name:
assert not self.name.endswith("."), repr(self.name)
name = self.name
if self.prefix:
name = "%s.%s" % (self.prefix, name)
self.add_import(name, lineno)
self.name = ""
def action_setprefix(self, type, string, lineno):
assert self.name, repr(self.name)
assert not self.name.endswith("."), repr(self.name)
self.prefix = self.name
self.name = ""
def action_collect(self, type, string, lineno):
self.name += string
def action_poststate(self, type, string, lineno):
self.state = self.post_name_state
self.post_name_state = None
self.transition(type, string, lineno)
def package_for_module(name):
"""Return the package name for the module named `name`."""
__import__(name)
module = sys.modules[name]
if not hasattr(module, "__path__"):
if "." in name:
name = name[:name.rfind(".")]
else:
name = None
return name
def module_for_importable(name):
"""Return the module name for the importable object `name`."""
try:
__import__(name)
except ImportError:
while "." in name:
name = name[:name.rfind(".")]
try:
__import__(name)
except ImportError:
pass
else:
break
else:
return None
return name | zope.dependencytool | /zope.dependencytool-3.4.0.tar.gz/zope.dependencytool-3.4.0/src/zope/dependencytool/importfinder.py | importfinder.py |
import errno
import getopt
import os
import re
import sys
import zope
from zope.dependencytool.dependency import Dependency
from zope.dependencytool import importfinder
# Get the Zope base path
ZOPESRC = os.path.dirname(os.path.dirname(os.path.dirname(
zope.dependencytool.__file__)))
ZOPESRCPREFIX = os.path.join(ZOPESRC, "")
# Matching expression for python files.
pythonfile = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*\.py$')
zcmlfile = re.compile(r'[a-zA-Z][a-zA-Z0-9_]*\.zcml$')
# Matching expressions of dotted paths in XML
dottedName = re.compile(r'"[a-zA-Z\.][a-zA-Z0-9_\.]*"')
def stripZopePrefix(path):
"""Remove the '.../src/' prefix from path, if present."""
if path.startswith(ZOPESRCPREFIX):
return path[len(ZOPESRCPREFIX):]
else:
return path
def usage(code, msg=''):
"""Display help."""
print >> sys.stderr, '\n'.join(__doc__.split('\n')[:-2])
if msg:
print >> sys.stderr, '** Error: ' + str(msg) + ' **'
sys.exit(code)
def makeDottedName(path):
"""Convert a path to a dotted module name, using sys.path."""
dirname, basename = os.path.split(path)
basename = os.path.splitext(basename)[0]
path = os.path.join(dirname, basename)
syspaths = sys.path[:]
if "" in syspaths:
# This is the directory that contains the driver script; there
# are no modules there.
syspaths.remove("")
for syspath in syspaths:
syspath = os.path.join(syspath, '')
if path.startswith(syspath):
return path[len(syspath):].replace(os.sep, ".")
raise ValueError('Cannot create dotted name for %r' % path)
def getDependenciesOfPythonFile(path, packages):
finder = importfinder.ImportFinder(packages)
module_name = makeDottedName(path)
if '.' in module_name:
package = module_name[:module_name.rfind('.')]
else:
package = None
finder.find_imports(open(path, 'rU'), path, package)
return finder.get_imports()
def resolveRelative(path, package):
pat = re.compile('\.+')
match = pat.match(path)
if match is None:
return path
dots = match.end()
path = path[dots:]
end = 0-dots+1
if end < 0:
package = '.'.join(package.split('.')[:end])
return package + '.' + path
def getDependenciesOfZCMLFile(path, packages):
"""Get dependencies from ZCML file."""
s = makeDottedName(path)
localPackage = s[:s.rfind(".")]
deps = []
lineno = 0
for line in open(path, 'r'):
lineno += 1
match = dottedName.findall(line)
if match:
match[0] = match[0][1:-1]
for name in match:
name = resolveRelative(name, localPackage)
name = importfinder.module_for_importable(name)
if packages:
name = importfinder.package_for_module(name)
deps.append(Dependency(name, path, lineno))
return deps
def filterStandardModules(deps):
"""Try to remove modules from the standard Python library.
Modules are considered part of the standard library if their
__file__ is located in the tree rooted at the parent of the
site-packages directory, but not in the sub-tree in site-packages.
"""
from distutils import sysconfig
site_packages = sysconfig.get_python_lib()
standard_lib = os.path.dirname(site_packages)
site_packages = os.path.join(site_packages, "")
standard_lib = os.path.join(standard_lib, "")
filteredDeps = []
for dep in deps:
try:
__import__(dep.name)
except ImportError:
continue
except TypeError:
continue
module = sys.modules[dep.name]
# built-ins (like sys) do not have a file associated
if not hasattr(module, '__file__'):
continue
starts = module.__file__.startswith
if starts(standard_lib) and not starts(site_packages):
continue
filteredDeps.append(dep)
return filteredDeps
def makeUnique(deps):
"""Remove entries that appear multiple times"""
uniqueDeps = {}
for dep in deps:
if dep.name in uniqueDeps:
uniqueDeps[dep.name].addOccurence(*dep.occurences[0])
else:
uniqueDeps[dep.name] = dep
return uniqueDeps.values()
def getDependencies(path, zcml=False, packages=False):
"""Get all dependencies of a package or module.
If the path is a package, all Python source files are searched inside it.
"""
if os.path.isdir(path):
deps = []
for file in os.listdir(path):
filePath = os.path.join(path, file)
if pythonfile.match(file):
deps += getDependenciesOfPythonFile(filePath, packages)
elif zcml and zcmlfile.match(file):
deps += getDependenciesOfZCMLFile(filePath, packages)
elif os.path.isdir(filePath):
filenames = os.listdir(filePath)
if ( 'PUBLICATION.cfg' not in filenames
and 'SETUP.cfg' not in filenames
and 'DEPENDENCIES.cfg' not in filenames
and '__init__.py' in filenames):
deps += getDependencies(filePath, zcml, packages)
elif os.path.isfile(path):
# return a empty list if no extension will fit
deps = []
ext = os.path.splitext(path)[1]
if ext == ".py":
deps = getDependenciesOfPythonFile(path, packages)
elif ext == ".zcml":
deps = getDependenciesOfZCMLFile(path, packages)
# TODO: Issue: 459, check this
# It doesn't make sense to exit here, check why we run into this
# and make sure this whan't happen in the future. I guess we need
# more 'elif' case where will handle other extensions too
#else:
# print >>sys.stderr, ("dependencies can only be"
# " extracted from Python and ZCML files")
# sys.exit(1)
else:
# TODO: Issue: 459, why do we exit here? I think the dependency tool
# should report dependeny and not exit at all. It doesn't make sense
# to abort on any error because we should report as much as possible
# Perhaps we should add another script like 'findmissing' or
# something like that, where is able to find missing imported packages.
print >>sys.stderr, path, "does not exist"
sys.exit(1)
return deps
def getCleanedDependencies(path, zcml=False, packages=False):
"""Return clean dependency list."""
deps = getDependencies(path, zcml, packages)
deps = filterStandardModules(deps)
deps = makeUnique(deps)
deps.sort()
return deps
# TODO: Issue: 459, check changed constructor
def getAllCleanedDependencies(path, zcml=False, deps=[], paths=[],
packages=False):
"""Return a list of all cleaned dependencies in a path."""
# TODO: Issue: 459, remove this comment and make sure we now what we like
# to do here
# zope and zope/app are too general to be considered.
# TODO: why? dependencies are dependencies.
# Because otherwise it would just pick up zope as a dependency, but
# nothing else. We need a way to detect packages.
# TODO: Issue: 459, implement a better path check method
# there's a t east me useing windows ;-)
if path.endswith('src/zope/') or path.endswith('src/zope/app/') or \
path.endswith('src\\zope\\') or path.endswith('src\\zope\\app\\'):
return deps
newdeps = getCleanedDependencies(path, zcml, packages)
for dep in newdeps:
if dep.name not in paths:
deps.append(dep)
paths.append(dep.name)
modulePath = __import__(dep.name).__file__
dirname, basename = os.path.split(modulePath)
if basename in ('__init__.py', '__init__.pyc', '__init__.pyo'):
modulePath = os.path.join(dirname, '')
getAllCleanedDependencies(modulePath, zcml, deps, paths, packages)
deps.sort()
return deps
def showDependencies(path, zcml=False, long=False, all=False, packages=False):
"""Show the dependencies of a module on the screen."""
if all:
deps = getAllCleanedDependencies(path, zcml, packages=packages)
else:
deps = getCleanedDependencies(path, zcml, packages)
if long:
print '='*(8+len(path))
print "Module: " + path
print '='*(8+len(path))
for dep in deps:
print dep.name
if long:
print '-'*len(dep.name)
for file, lineno in dep.occurences:
file = stripZopePrefix(file)
if len(file) >= 69:
file = '...' + file[:69-3]
print ' %s, Line %s' %(file, lineno)
print
class DependencyOptions(object):
all = False
long = False
packages = False
path = None
zcml = False
def parse_args(argv):
try:
opts, args = getopt.getopt(
argv[1:],
'd:m:pahlz',
['all', 'help', 'dir=', 'module=', 'long', 'packages', 'zcml'])
except getopt.error, msg:
usage(1, msg)
options = DependencyOptions()
for opt, arg in opts:
if opt in ('-a', '--all'):
options.all = True
elif opt in ('-h', '--help'):
usage(0)
elif opt in ('-l', '--long'):
options.long = True
elif opt in ('-d', '--dir'):
cwd = os.getcwd()
# This is for symlinks. Thanks to Fred for this trick.
# I often sym-link directories from other locations into the Zope
# source tree. This code is a bit Unix (or even bash) specific,
# but it is better than nothing. If you don't like it, ignore it.
if os.environ.has_key('PWD'):
cwd = os.environ['PWD']
options.path = os.path.normpath(os.path.join(cwd, arg))
elif opt in ('-m', '--module'):
try:
__import__(arg)
module = sys.modules[arg]
options.path = os.path.dirname(module.__file__)
except ImportError:
usage(1, "Could not import module %s" % arg)
elif opt in ('-p', '--packages'):
options.packages = True
elif opt in ('-z', '--zcml'):
options.zcml = True
if options.path is None:
usage(1, 'The module must be specified either by path, '
'dotted name or ZCML file.')
return options
def main(argv=None):
try:
if argv is None:
argv = sys.argv
options = parse_args(argv)
showDependencies(options.path, options.zcml, options.long,
options.all, options.packages)
except IOError, e:
# Ignore EPIPE since that really only indicates some
# application on the other end of piped output exited early.
if e.errno != errno.EPIPE:
raise
except KeyboardInterrupt:
sys.exit(1) | zope.dependencytool | /zope.dependencytool-3.4.0.tar.gz/zope.dependencytool-3.4.0/src/zope/dependencytool/finddeps.py | finddeps.py |
================================
``zope.deprecation`` Changelog
================================
5.0 (2023-03-29)
================
- Drop support for Python 2.7, 3.4, 3.5, 3.6.
- Drop support for deprecated ``python setup.py test``.
- Add support for Python 3.8, 3.9, 3.10, 3.11.
4.4.0 (2018-12-03)
==================
- Add support for Python 3.7.
4.3.0 (2017-08-07)
==================
- Allow custom warning classes to be specified to override the default
``DeprecationWarning``.
See https://github.com/zopefoundation/zope.deprecation/pull/7
- Add support for Python 3.6.
- Drop support for Python 3.3.
4.2.0 (2016-11-07)
==================
- Drop support for Python 2.6 and 3.2.
- Add support for Python 3.5.
4.1.2 (2015-01-13)
==================
- Do not require a ``self`` parameter for deprecated functions. See:
https://github.com/zopefoundation/zope.deprecation/pull/1
4.1.1 (2014-03-19)
==================
- Added explicit support for Python 3.4.
4.1.0 (2013-12-20)
==================
- Added a ``Suppressor`` context manager, allowing scoped suppression of
deprecation warnings.
- Updated ``boostrap.py`` to version 2.2.
4.0.2 (2012-12-31)
==================
- Fleshed out PyPI Trove classifiers.
4.0.1 (2012-11-21)
==================
- Added support for Python 3.3.
4.0.0 (2012-05-16)
==================
- Automated build of Sphinx HTML docs and running doctest snippets via tox.
- Added Sphinx documentation:
- API docs moved from package-data README into ``docs/api.rst``.
- Snippets can be tested by running 'make doctest'.
- Updated support for continuous integration using ``tox`` and ``jenkins``.
- 100% unit test coverage.
- Added ``setup.py dev`` alias (runs ``setup.py develop`` plus installs
``nose`` and ``coverage``).
- Added ``setup.py docs`` alias (installs ``Sphinx`` and dependencies).
- Removed spurious dependency on ``zope.testing``.
- Dropped explicit support for Python 2.4 / 2.5 / 3.1.
3.5.1 (2012-03-15)
==================
- Revert a move of `README.txt` to unbreak ``zope.app.apidoc``.
3.5.0 (2011-09-05)
==================
- Replaced doctesting with unit testing.
- Python 3 compatibility.
3.4.1 (2011-06-07)
==================
- Removed import cycle for ``__show__`` by defining it in the
``zope.deprecation.deprecation`` module.
- Added support to bootstrap on Jython.
- Fix ``zope.deprecation.warn()`` to make the signature identical to
``warnings.warn()`` and to check for .pyc and .pyo files.
3.4.0 (2007-07-19)
==================
- Release 3.4 final, corresponding to Zope 3.4.
3.3.0 (2007-02-18)
==================
- Corresponds to the version of the ``zope.deprecation`` package shipped as
part of the Zope 3.3.0 release.
| zope.deprecation | /zope.deprecation-5.0.tar.gz/zope.deprecation-5.0/CHANGES.rst | CHANGES.rst |
======================
``zope.deprecation``
======================
.. image:: https://img.shields.io/pypi/v/zope.deprecation.svg
:target: https://pypi.python.org/pypi/zope.deprecation/
:alt: Latest release
.. image:: https://img.shields.io/pypi/pyversions/zope.deprecation.svg
:target: https://pypi.org/project/zope.deprecation/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/zope.deprecation/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/zope.deprecation/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/zope.deprecation/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/zope.deprecation?branch=master
.. image:: https://readthedocs.org/projects/zopedeprecation/badge/?version=latest
:target: https://zopedeprecation.readthedocs.io/en/latest/
:alt: Documentation Status
This package provides a simple function called ``deprecated(names, reason)``
to mark deprecated modules, classes, functions, methods and properties.
Please see https://zopedeprecation.readthedocs.io for the documentation.
| zope.deprecation | /zope.deprecation-5.0.tar.gz/zope.deprecation-5.0/README.rst | README.rst |
__docformat__ = "reStructuredText"
import sys
import types
import warnings
str_and_sequence_types = (str, list, tuple)
class ShowSwitch:
"""Simple stack-based switch."""
def __init__(self):
self.stack = []
def on(self):
self.stack.pop()
def off(self):
self.stack.append(False)
def reset(self):
self.stack = []
def __call__(self):
return self.stack == []
def __repr__(self):
return '<ShowSwitch %s>' % (self() and 'on' or 'off')
# This attribute can be used to temporarily deactivate deprecation
# warnings, so that backward-compatibility code can import other
# backward-compatibility components without warnings being produced.
__show__ = ShowSwitch()
class Suppressor:
def __enter__(self):
__show__.off()
def __exit__(self, *ignored):
__show__.on()
ogetattr = object.__getattribute__
class DeprecationProxy:
def __init__(self, module):
self.__original_module = module
self.__deprecated = {}
def deprecate(self, names, message, cls=DeprecationWarning):
"""Deprecate the given names."""
if not isinstance(names, (tuple, list)):
names = (names,)
for name in names:
self.__deprecated[name] = (message, cls)
def __getattribute__(self, name):
if name == 'deprecate' or name.startswith('_DeprecationProxy__'):
return ogetattr(self, name)
if name == '__class__':
return types.ModuleType
if name in ogetattr(self, '_DeprecationProxy__deprecated'):
if __show__():
msg, cls = self.__deprecated[name]
warnings.warn(name + ': ' + msg, cls, 2)
return getattr(ogetattr(self, '_DeprecationProxy__original_module'),
name)
def __setattr__(self, name, value):
if name.startswith('_DeprecationProxy__'):
return object.__setattr__(self, name, value)
setattr(self.__original_module, name, value)
def __delattr__(self, name):
if name.startswith('_DeprecationProxy__'):
return object.__delattr__(self, name)
delattr(self.__original_module, name)
class DeprecatedModule:
def __init__(self, module, msg, cls=DeprecationWarning):
self.__original_module = module
self.__msg = msg
self.__cls = cls
def __getattribute__(self, name):
if name.startswith('_DeprecatedModule__'):
return ogetattr(self, name)
if name == '__class__':
return types.ModuleType
if __show__():
warnings.warn(self.__msg, self.__cls, 2)
return getattr(ogetattr(self, '_DeprecatedModule__original_module'),
name)
def __setattr__(self, name, value):
if name.startswith('_DeprecatedModule__'):
return object.__setattr__(self, name, value)
setattr(self.__original_module, name, value)
def __delattr__(self, name):
if name.startswith('_DeprecatedModule__'):
return object.__delattr__(self, name)
delattr(self.__original_module, name)
class DeprecatedGetProperty:
def __init__(self, prop, message, cls=DeprecationWarning):
self.message = message
self.prop = prop
self.cls = cls
def __get__(self, inst, klass):
if __show__():
warnings.warn(self.message, self.cls, 2)
return self.prop.__get__(inst, klass)
class DeprecatedGetSetProperty(DeprecatedGetProperty):
def __set__(self, inst, prop):
if __show__():
warnings.warn(self.message, self.cls, 2)
self.prop.__set__(inst, prop)
class DeprecatedGetSetDeleteProperty(DeprecatedGetSetProperty):
def __delete__(self, inst):
if __show__():
warnings.warn(self.message, self.cls, 2)
self.prop.__delete__(inst)
def DeprecatedMethod(method, message, cls=DeprecationWarning):
def deprecated_method(*args, **kw):
if __show__():
warnings.warn(message, cls, 2)
return method(*args, **kw)
return deprecated_method
def deprecated(specifier, message, cls=DeprecationWarning):
"""Deprecate the given names."""
# A string specifier (or list of strings) means we're called
# top-level in a module and are to deprecate things inside this
# module
if isinstance(specifier, str_and_sequence_types):
globals = sys._getframe(1).f_globals
modname = globals['__name__']
if not isinstance(sys.modules[modname], DeprecationProxy):
sys.modules[modname] = DeprecationProxy(sys.modules[modname])
sys.modules[modname].deprecate(specifier, message, cls)
# Anything else can mean the specifier is a function/method,
# module, or just an attribute of a class
elif isinstance(specifier, types.FunctionType):
return DeprecatedMethod(specifier, message, cls)
elif isinstance(specifier, types.ModuleType):
return DeprecatedModule(specifier, message, cls)
else:
prop = specifier
if hasattr(prop, '__get__') and hasattr(prop, '__set__') and \
hasattr(prop, '__delete__'):
return DeprecatedGetSetDeleteProperty(prop, message, cls)
elif hasattr(prop, '__get__') and hasattr(prop, '__set__'):
return DeprecatedGetSetProperty(prop, message, cls)
elif hasattr(prop, '__get__'):
return DeprecatedGetProperty(prop, message, cls)
class deprecate:
"""Deprecation decorator"""
def __init__(self, msg, cls=DeprecationWarning):
self.msg = msg
self.cls = cls
def __call__(self, func):
return DeprecatedMethod(func, self.msg, self.cls)
def moved(to_location, unsupported_in=None, cls=DeprecationWarning):
old = sys._getframe(1).f_globals['__name__']
message = '{} has moved to {}.'.format(old, to_location)
if unsupported_in:
message += " Import of {} will become unsupported in {}".format(
old, unsupported_in)
warnings.warn(message, cls, 3)
__import__(to_location)
fromdict = sys.modules[to_location].__dict__
tomod = sys.modules[old]
tomod.__doc__ = message
for name, v in fromdict.items():
if name not in tomod.__dict__:
setattr(tomod, name, v) | zope.deprecation | /zope.deprecation-5.0.tar.gz/zope.deprecation-5.0/src/zope/deprecation/deprecation.py | deprecation.py |
=============================
:mod:`zope.deprecation` API
=============================
Deprecating objects inside a module
===================================
Let's start with a demonstration of deprecating any name inside a module. To
demonstrate the functionality, First, let's set up an example module containing
fixtures we will use:
.. doctest::
>>> import os
>>> import tempfile
>>> import zope.deprecation
>>> tmp_d = tempfile.mkdtemp('deprecation')
>>> zope.deprecation.__path__.append(tmp_d)
>>> doctest_ex = '''\
... from . import deprecated
...
... def demo1():
... return 1
... deprecated('demo1', 'demo1 is no more.')
...
... def demo2():
... return 2
... deprecated('demo2', 'demo2 is no more.')
...
... def demo3():
... return 3
... deprecated('demo3', 'demo3 is no more.')
...
... def demo4():
... return 4
... def deprecatedemo4():
... """Demonstrate that deprecated() also works in a local scope."""
... deprecated('demo4', 'demo4 is no more.')
... '''
>>> with open(os.path.join(tmp_d, 'doctest_ex.py'), 'w') as f:
... _ = f.write(doctest_ex)
The first argument to the ``deprecated()`` function is a list of names that
should be declared deprecated. If the first argument is a string, it is
interpreted as one name. The second argument is the reason the particular name
has been deprecated. It is good practice to also list the version in which the
name will be removed completely.
Let's now see how the deprecation warnings are displayed.
.. doctest::
>>> import warnings
>>> from zope.deprecation import doctest_ex
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... doctest_ex.demo1()
1
>>> print(log[0].category.__name__)
DeprecationWarning
>>> print(log[0].message)
demo1: demo1 is no more.
>>> import zope.deprecation.doctest_ex
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... zope.deprecation.doctest_ex.demo2()
2
>>> print(log[0].message)
demo2: demo2 is no more.
You can see that merely importing the affected module or one of its parents
does not cause a deprecation warning. Only when we try to access the name in
the module, we get a deprecation warning. On the other hand, if we import the
name directly, the deprecation warning will be raised immediately.
.. doctest::
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... from zope.deprecation.doctest_ex import demo3
>>> print(log[0].message)
demo3: demo3 is no more.
Deprecation can also happen inside a function. When we first access
``demo4``, it can be accessed without problems, then we call a
function that sets the deprecation message and we get the message upon
the next access:
.. doctest::
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... doctest_ex.demo4()
4
>>> len(log)
0
>>> doctest_ex.deprecatedemo4()
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... doctest_ex.demo4()
4
>>> print(log[0].message)
demo4: demo4 is no more.
Deprecating methods and properties
==================================
New let's see how properties and methods can be deprecated. We are going to
use the same function as before, except that this time, we do not pass in names
as first argument, but the method or attribute itself. The function then
returns a wrapper that sends out a deprecation warning when the attribute or
method is accessed.
.. doctest::
>>> from zope.deprecation import deprecation
>>> class MyComponent(object):
... foo = property(lambda self: 1)
... foo = deprecation.deprecated(foo, 'foo is no more.')
...
... bar = 2
...
... def blah(self):
... return 3
... blah = deprecation.deprecated(blah, 'blah() is no more.')
...
... def splat(self):
... return 4
...
... @deprecation.deprecate("clap() is no more.")
... def clap(self):
... return 5
And here is the result:
.. doctest::
>>> my = MyComponent()
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... my.foo
1
>>> print(log[0].message)
foo is no more.
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... my.bar
2
>>> len(log)
0
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... my.blah()
3
>>> print(log[0].message)
blah() is no more.
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... my.splat()
4
>>> len(log)
0
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... my.clap()
5
>>> print(log[0].message)
clap() is no more.
Deprecating modules
===================
It is also possible to deprecate whole modules. This is useful when
creating module aliases for backward compatibility. Let's imagine,
the ``zope.deprecation`` module used to be called ``zope.wanda`` and
we'd like to retain backward compatibility:
.. doctest::
>>> import sys
>>> sys.modules['zope.wanda'] = deprecation.deprecated(
... zope.deprecation, 'A module called Wanda is now zope.deprecation.')
Now we can import ``wanda``, but when accessing things from it, we get
our deprecation message as expected:
.. doctest::
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... from zope.wanda import deprecated
>>> print(log[0].message)
A module called Wanda is now zope.deprecation.
Before we move on, we should clean up:
.. doctest::
>>> del deprecated
>>> del sys.modules['zope.wanda']
Moving modules
==============
When a module is moved, you often want to support importing from the
old location for a while, generating a deprecation warning when
someone uses the old location. This can be done using the moved
function.
To see how this works, we'll use a helper function to create two fake
modules in the zope.deprecation package. First will create a module
in the "old" location that used the moved function to indicate the a
module on the new location should be used:
.. doctest::
>>> import os
>>> created_modules = []
>>> def create_module(modules=(), **kw): #** highlightfail
... modules = dict(modules)
... modules.update(kw)
... for name, src in sorted(modules.items()):
... pname = name.split('.')
... if pname[-1] == '__init__':
... os.mkdir(os.path.join(tmp_d, *pname[:-1])) #* highlightfail
... name = '.'.join(pname[:-1])
... with open(os.path.join(tmp_d, *pname) + '.py', 'w') as f:
... f.write(src) #* hf
... created_modules.append(name)
... import importlib
... if hasattr(importlib, 'invalidate_caches'):
... importlib.invalidate_caches()
>>> create_module(old_location=
... '''
... import zope.deprecation
... zope.deprecation.moved('zope.deprecation.new_location', 'version 2')
... ''')
and we define the module in the new location:
.. doctest::
>>> create_module(new_location=
... '''\
... print("new module imported")
... x = 42
... ''')
Now, if we import the old location, we'll see the output of importing
the old location:
.. doctest::
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... import zope.deprecation.old_location
new module imported
>>> print(log[0].message)
... # doctest: +NORMALIZE_WHITESPACE
zope.deprecation.old_location has moved to zope.deprecation.new_location.
Import of zope.deprecation.old_location will become unsupported
in version 2
>>> zope.deprecation.old_location.x
42
Moving packages
===============
When moving packages, you need to leave placeholders for each
module. Let's look at an example:
.. doctest::
>>> create_module({
... 'new_package.__init__': '''\
... print(__name__ + ' imported')
... x=0
... ''',
... 'new_package.m1': '''\
... print(__name__ + ' imported')
... x=1
... ''',
... 'new_package.m2': '''\
... print(__name__ + ' imported')
... def x():
... pass
... ''',
... 'new_package.m3': '''\
... print(__name__ + ' imported')
... x=3
... ''',
... 'old_package.__init__': '''\
... import zope.deprecation
... zope.deprecation.moved('zope.deprecation.new_package', 'version 2')
... ''',
... 'old_package.m1': '''\
... import zope.deprecation
... zope.deprecation.moved('zope.deprecation.new_package.m1', 'version 2')
... ''',
... 'old_package.m2': '''\
... import zope.deprecation
... zope.deprecation.moved('zope.deprecation.new_package.m2', 'version 2')
... ''',
... })
Now, if we import the old modules, we'll get warnings:
.. doctest::
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... import zope.deprecation.old_package
zope.deprecation.new_package imported
>>> print(log[0].message)
... # doctest: +NORMALIZE_WHITESPACE
zope.deprecation.old_package has moved to zope.deprecation.new_package.
Import of zope.deprecation.old_package will become unsupported in version 2
>>> zope.deprecation.old_package.x
0
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... import zope.deprecation.old_package.m1
zope.deprecation.new_package.m1 imported
>>> print(log[0].message)
... # doctest: +NORMALIZE_WHITESPACE
zope.deprecation.old_package.m1 has moved to zope.deprecation.new_package.m1.
Import of zope.deprecation.old_package.m1 will become unsupported in
version 2
>>> zope.deprecation.old_package.m1.x
1
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... import zope.deprecation.old_package.m2
zope.deprecation.new_package.m2 imported
>>> print(log[0].message)
... # doctest: +NORMALIZE_WHITESPACE
zope.deprecation.old_package.m2 has moved to zope.deprecation.new_package.m2.
Import of zope.deprecation.old_package.m2 will become unsupported in
version 2
>>> zope.deprecation.old_package.m2.x is zope.deprecation.new_package.m2.x
True
>>> (zope.deprecation.old_package.m2.x.__globals__
... is zope.deprecation.new_package.m2.__dict__)
True
>>> zope.deprecation.old_package.m2.x.__module__
'zope.deprecation.new_package.m2'
We'll get an error if we try to import m3, because we didn't create a
placeholder for it (Python 3.6 started raising ModuleNotFoundError, a
subclass of ImportError with a different error message than earlier
releases so we can't see that directly):
.. doctest::
>>> try:
... import zope.deprecation.old_package.m3
... except ImportError as e:
... print("No module named" in str(e))
... print("m3" in str(e))
True
True
Before we move on, let's clean up the temporary modules / packages:
.. doctest::
>>> zope.deprecation.__path__.remove(tmp_d)
>>> import shutil
>>> shutil.rmtree(tmp_d)
Temporarily turning off deprecation warnings
============================================
In some cases it is desireable to turn off the deprecation warnings for a
short time.
To support such a feature, the ``zope.deprecation`` package
provides a context manager class, :class:`zope.deprecation.Suppressor`.
Code running inside the scope of a ``Suppressor`` will not emit deprecation
warnings.
.. doctest::
>>> from zope.deprecation import Suppressor
>>> class Foo(object):
... bar = property(lambda self: 1)
... bar = deprecation.deprecated(bar, 'bar is no more.')
... blah = property(lambda self: 1)
... blah = deprecation.deprecated(blah, 'blah is no more.')
>>> foo = Foo()
>>> with Suppressor():
... foo.blah
1
Note that no warning is emitted when ``foo.blah`` is accessed inside
the suppressor's scope.:
The suppressor is implemented in terms of a ``__show__`` object.
One can ask for its status by calling it:
.. doctest::
>>> from zope.deprecation import __show__
>>> __show__()
True
Inside a suppressor's scope, that status is always false:
.. doctest::
>>> with Suppressor():
... __show__()
False
.. doctest::
>>> with warnings.catch_warnings(record=True) as log:
... del warnings.filters[:]
... foo.bar
1
>>> print(log[0].message)
bar is no more.
If needed, your code can manage the depraction warnings manually using
the ``on()`` and ``off()`` methods of the ``__show__`` object:
.. doctest::
>>> __show__.off()
>>> __show__()
False
>>> foo.blah
1
Now, you can also nest several turn-offs, so that calling ``off()`` multiple
times is meaningful:
.. doctest::
>>> __show__.stack
[False]
>>> __show__.off()
>>> __show__.stack
[False, False]
>>> __show__.on()
>>> __show__.stack
[False]
>>> __show__()
False
>>> __show__.on()
>>> __show__.stack
[]
>>> __show__()
True
You can also reset ``__show__`` to ``True``:
.. doctest::
>>> __show__.off()
>>> __show__.off()
>>> __show__()
False
>>> __show__.reset()
>>> __show__()
True
Finally, you cannot call ``on()`` without having called ``off()`` before:
.. doctest::
>>> __show__.on()
Traceback (most recent call last):
...
IndexError: pop from empty list
| zope.deprecation | /zope.deprecation-5.0.tar.gz/zope.deprecation-5.0/docs/api.rst | api.rst |
Hacking on :mod:`zope.deprecation`
==================================
Getting the Code
################
The main repository for :mod:`zope.deprecation` is in the Zope Foundation
Github repository:
https://github.com/zopefoundation/zope.deprecation
You can get a read-only checkout from there:
.. code-block:: sh
$ git clone https://github.com/zopefoundation/zope.deprecation.git
or fork it and get a writeable checkout of your fork:
.. code-block:: sh
$ git clone [email protected]/jrandom/zope.deprecation.git
The project also mirrors the trunk from the Github repository as a
Bazaar branch on Launchpad:
https://code.launchpad.net/zope.deprecation
You can branch the trunk from there using Bazaar:
.. code-block:: sh
$ bzr branch lp:zope.deprecation
Working in a ``virtualenv``
###########################
Installing
----------
If you use the ``virtualenv`` package to create lightweight Python
development environments, you can run the tests using nothing more
than the ``python`` binary in a virtualenv. First, create a scratch
environment:
.. code-block:: sh
$ /path/to/virtualenv --no-site-packages /tmp/hack-zope.deprecation
Next, get this package registered as a "development egg" in the
environment:
.. code-block:: sh
$ /tmp/hack-zope.deprecation/bin/python setup.py develop
Running the tests
-----------------
Run the tests using the build-in ``setuptools`` testrunner:
.. code-block:: sh
$ /tmp/hack-zope.deprecation/bin/python setup.py test
running test
....................................................
----------------------------------------------------------------------
Ran 52 tests in 0.155s
OK
If you have the :mod:`nose` package installed in the virtualenv, you can
use its testrunner too:
.. code-block:: sh
$ /tmp/hack-zope.deprecation/bin/easy_install nose
...
$ /tmp/hack-zope.deprecation/bin/python setup.py nosetests
running nosetests
....................................................
----------------------------------------------------------------------
Ran 52 tests in 0.155s
OK
or:
.. code-block:: sh
$ /tmp/hack-zope.deprecation/bin/nosetests
....................................................
----------------------------------------------------------------------
Ran 52 tests in 0.155s
OK
If you have the :mod:`coverage` pacakge installed in the virtualenv,
you can see how well the tests cover the code:
.. code-block:: sh
$ /tmp/hack-zope.deprecation/bin/easy_install nose coverage
...
$ /tmp/hack-zope.deprecation/bin/python setup.py nosetests \
--with coverage --cover-package=zope.deprecation
running nosetests
....................................................
Name Stmts Miss Cover Missing
------------------------------------------------------------
zope.deprecation 7 0 100%
zope.deprecation.deprecation 127 0 100%
zope.deprecation.fixture 1 0 100%
------------------------------------------------------------
TOTAL 135 0 100%
----------------------------------------------------------------------
Ran 52 tests in 0.155s
OK
Building the documentation
--------------------------
:mod:`zope.deprecation` uses the nifty :mod:`Sphinx` documentation system
for building its docs. Using the same virtualenv you set up to run the
tests, you can build the docs:
.. code-block:: sh
$ /tmp/hack-zope.deprecation/bin/easy_install Sphinx
...
$ bin/sphinx-build -b html -d docs/_build/doctrees docs docs/_build/html
...
build succeeded.
You can also test the code snippets in the documentation:
.. code-block:: sh
$ bin/sphinx-build -b doctest -d docs/_build/doctrees docs docs/_build/doctest
...
Doctest summary
===============
89 tests
0 failures in tests
0 failures in setup code
build succeeded.
Testing of doctests in the sources finished, look at the \
results in _build/doctest/output.txt.
Using :mod:`zc.buildout`
########################
Setting up the buildout
-----------------------
:mod:`zope.deprecation` ships with its own :file:`buildout.cfg` file and
:file:`bootstrap.py` for setting up a development buildout:
.. code-block:: sh
$ /path/to/python2.6 bootstrap.py
...
Generated script '.../bin/buildout'
$ bin/buildout
Develop: '/home/jrandom/projects/Zope/BTK/deprecation/.'
...
Generated script '.../bin/sphinx-quickstart'.
Generated script '.../bin/sphinx-build'.
Running the tests using
-----------------------
Run the tests:
.. code-block:: sh
$ bin/test --all
Running zope.testing.testrunner.layer.UnitTests tests:
Set up zope.testing.testrunner.layer.UnitTests in 0.000 seconds.
Ran 52 tests with 0 failures and 0 errors in 0.366 seconds.
Tearing down left over layers:
Tear down zope.testing.testrunner.layer.UnitTests in 0.000 seconds.
Using :mod:`tox`
################
Running Tests on Multiple Python Versions
-----------------------------------------
`tox <http://tox.testrun.org/latest/>`_ is a Python-based test automation
tool designed to run tests against multiple Python versions. It creates
a ``virtualenv`` for each configured version, installs the current package
and configured dependencies into each ``virtualenv``, and then runs the
configured commands.
:mod:`zope.deprecation` configures the following :mod:`tox` environments via
its ``tox.ini`` file:
- The ``py26``, ``py27``, ``py33``, ``py34``, and ``pypy`` environments
builds a ``virtualenv`` with ``pypy``,
installs :mod:`zope.deprecation` and dependencies, and runs the tests
via ``python setup.py test -q``.
- The ``coverage`` environment builds a ``virtualenv`` with ``python2.6``,
installs :mod:`zope.deprecation`, installs
:mod:`nose` and :mod:`coverage`, and runs ``nosetests`` with statement
coverage.
- The ``docs`` environment builds a virtualenv with ``python2.6``, installs
:mod:`zope.deprecation`, installs ``Sphinx`` and
dependencies, and then builds the docs and exercises the doctest snippets.
This example requires that you have a working ``python2.6`` on your path,
as well as installing ``tox``:
.. code-block:: sh
$ tox -e py26
GLOB sdist-make: .../zope.interface/setup.py
py26 sdist-reinst: .../zope.interface/.tox/dist/zope.interface-4.0.2dev.zip
py26 runtests: commands[0]
..........
----------------------------------------------------------------------
Ran 52 tests in 0.155s
OK
___________________________________ summary ____________________________________
py26: commands succeeded
congratulations :)
Running ``tox`` with no arguments runs all the configured environments,
including building the docs and testing their snippets:
.. code-block:: sh
$ tox
GLOB sdist-make: .../zope.interface/setup.py
py26 sdist-reinst: .../zope.interface/.tox/dist/zope.interface-4.0.2dev.zip
py26 runtests: commands[0]
...
Doctest summary
===============
89 tests
0 failures in tests
0 failures in setup code
0 failures in cleanup code
build succeeded.
___________________________________ summary ____________________________________
py26: commands succeeded
py27: commands succeeded
py32: commands succeeded
pypy: commands succeeded
coverage: commands succeeded
docs: commands succeeded
congratulations :)
Contributing to :mod:`zope.deprecation`
#######################################
Submitting a Bug Report
-----------------------
:mod:`zope.deprecation` tracks its bugs on Github:
https://github.com/zopefoundation/zope.deprecation/issues
Please submit bug reports and feature requests there.
Sharing Your Changes
--------------------
.. note::
Please ensure that all tests are passing before you submit your code.
If possible, your submission should include new tests for new features
or bug fixes, although it is possible that you may have tested your
new code by updating existing tests.
If have made a change you would like to share, the best route is to fork
the Githb repository, check out your fork, make your changes on a branch
in your fork, and push it. You can then submit a pull request from your
branch:
https://github.com/zopefoundation/zope.deprecation/pulls
If you branched the code from Launchpad using Bazaar, you have another
option: you can "push" your branch to Launchpad:
.. code-block:: sh
$ bzr push lp:~jrandom/zope.deprecation/cool_feature
After pushing your branch, you can link it to a bug report on Launchpad,
or request that the maintainers merge your branch using the Launchpad
"merge request" feature.
| zope.deprecation | /zope.deprecation-5.0.tar.gz/zope.deprecation-5.0/docs/hacking.rst | hacking.rst |
"""Python implementations of document template some features
"""
import sys
from types import StringTypes, TupleType, ClassType
ClassTypes = [ClassType]
from zope.documenttemplate.ustr import ustr
def safe_callable(ob):
# Works with ExtensionClasses and Acquisition.
if hasattr(ob, '__class__'):
if hasattr(ob, '__call__'):
return 1
else:
return type(ob) in ClassTypes
else:
return callable(ob)
class InstanceDict:
def __init__(self, o, namespace):
self.self = o
self.cache = {}
self.namespace = namespace
def has_key(self,key):
return hasattr(self.self,key)
def keys(self):
return self.self.__dict__.keys()
def __repr__(self):
return 'InstanceDict(%s)' % str(self.self)
def __getitem__(self,key):
cache=self.cache
if cache.has_key(key):
return cache[key]
inst = self.self
try:
r = getattr(inst, key)
except AttributeError:
raise KeyError(key)
self.cache[key] = r
return r
def __len__(self):
return 1
class MultiMapping:
def __init__(self):
self.dicts = []
def __getitem__(self, key):
for d in self.dicts:
try:
return d[key]
except (KeyError, AttributeError):
pass
raise KeyError(key)
def push(self,d):
self.dicts.insert(0, d)
def pop(self, n=1):
r = self.dicts[-1]
del self.dicts[:n]
return r
def keys(self):
kz = []
for d in self.dicts:
kz = kz + d.keys()
return kz
class DictInstance:
def __init__(self, mapping):
self.__d = mapping
def __getattr__(self, name):
try:
return self.__d[name]
except KeyError:
raise AttributeError(name)
class TemplateDict:
level = 0
def _pop(self, n=1):
return self.dicts.pop(n)
def _push(self, d):
return self.dicts.push(d)
def _push_instance(self, inst):
self._push(InstanceDict(inst, self))
def _proxied(self):
return self
def __init__(self):
m = self.dicts = MultiMapping()
self._pop = m.pop
self._push = m.push
try:
self.keys = m.keys
except:
pass
def __getitem__(self,key,call=1):
v = self.dicts[key]
if call:
if hasattr(v, '__render_with_namespace__'):
return v.__render_with_namespace__(self)
vbase = getattr(v, 'aq_base', v)
if safe_callable(vbase):
v = v()
return v
def __len__(self):
total = 0
for d in self.dicts.dicts:
total += len(d)
return total
def has_key(self,key):
try:
self.dicts[key]
except KeyError:
return 0
return 1
getitem = __getitem__
def __call__(self, *args, **kw):
if args:
if len(args) == 1 and not kw:
m=args[0]
else:
m = self.__class__()
for a in args:
m._push(a)
if kw:
m._push(kw)
else:
m=kw
return (DictInstance(m),)
# extra handy utilities that people expect to find in template dicts:
import math
import random
def range(md, iFirst, *args):
# limited range function from Martijn Pieters
RANGELIMIT = 1000
if not len(args):
iStart, iEnd, iStep = 0, iFirst, 1
elif len(args) == 1:
iStart, iEnd, iStep = iFirst, args[0], 1
elif len(args) == 2:
iStart, iEnd, iStep = iFirst, args[0], args[1]
else:
raise AttributeError(u'range() requires 1-3 int arguments')
if iStep == 0:
raise ValueError(u'zero step for range()')
iLen = int((iEnd - iStart) / iStep)
if iLen < 0:
iLen = 0
if iLen >= RANGELIMIT:
raise ValueError(u'range() too large')
return range(iStart, iEnd, iStep)
def pow(self, x, y, z):
if not z:
raise ValueError('pow(x, y, z) with z==0')
return pow(x,y,z)
def test(self, *args):
l = len(args)
for i in range(1, l, 2):
if args[i-1]:
return args[i]
if l%2:
return args[-1]
getattr = getattr
attr = getattr
hasattr = hasattr
def namespace(self, **kw):
return self(**kw)
def render(self, v):
"Render an object in the way done by the 'name' attribute"
if hasattr(v, '__render_with_namespace__'):
v = v.__render_with_namespace__(self)
else:
vbase = getattr(v, 'aq_base', v)
if callable(vbase):
v = v()
return v
def reorder(self, s, with_=None, without=(), **kw):
if with_ is None and kw.has_key('with'):
with_ = kw['with']
if with_ is None:
with_ = s
d = {}
for i in s:
if isinstance(i, TupleType) and len(i) == 2:
k, v = i
else:
k = v = i
d[k] = v
r = []
a = r.append
h = d.has_key
for i in without:
if isinstance(i, TupleType) and len(i) == 2:
k, v = i
else:
k= v = i
if h(k):
del d[k]
for i in with_:
if isinstance(i, TupleType) and len(i) == 2:
k, v = i
else:
k = v = i
if h(k):
a((k,d[k]))
del d[k]
return r
# Add selected builtins to template dicts
for name in ('None', 'abs', 'chr', 'divmod', 'float', 'hash', 'hex', 'int',
'len', 'max', 'min', 'oct', 'ord', 'round', 'str'):
setattr(TemplateDict, name, __builtins__[name])
def render_blocks(blocks, md):
rendered = []
for section in blocks:
if type(section) is TupleType:
l = len(section)
if l == 1:
# Simple var
section = section[0]
if isinstance(section, StringTypes):
section = md[section]
else:
section = section(md)
section = ustr(section)
else:
# if
cache = {}
md._push(cache)
try:
i = 0
m = l-1
while i < m:
cond = section[i]
if isinstance(cond, StringTypes):
n = cond
try:
cond = md[cond]
cache[n] = cond
except KeyError, v:
v = v[0]
if n != v:
raise KeyError(v), None, sys.exc_traceback
cond=None
else:
cond = cond(md)
if cond:
section = section[i+1]
if section:
section = render_blocks(section,md)
else: section=''
m = 0
break
i += 2
if m:
if i == m:
section = render_blocks(section[i],md)
else:
section = ''
finally: md._pop()
elif not isinstance(section, StringTypes):
section = section(md)
if section:
rendered.append(section)
l = len(rendered)
if l == 0:
return ''
elif l == 1:
return rendered[0]
return ''.join(rendered)
return rendered | zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/pdocumenttemplate.py | pdocumenttemplate.py |
import sys, traceback
from StringIO import StringIO
from zope.documenttemplate.dt_util import ParseError, parse_params
from zope.documenttemplate.dt_util import render_blocks
from zope.documenttemplate.dt_return import DTReturn
from types import StringType
class Try:
"""Zope DTML Exception handling
usage:
<dtml-try>
<dtml-except SomeError AnotherError>
<dtml-except YetAnotherError>
<dtml-except>
<dtml-else>
</dtml-try>
or:
<dtml-try>
<dtml-finally>
</dtml-try>
The DTML try tag functions quite like Python's try command.
The contents of the try tag are rendered. If an exception is raised,
then control switches to the except blocks. The first except block to
match the type of the error raised is rendered. If an except block has
no name then it matches all raised errors.
The try tag understands class-based exceptions, as well as string-based
exceptions. Note: the 'raise' tag raises string-based exceptions.
Inside the except blocks information about the error is available via
three variables.
'error_type' -- This variable is the name of the exception caught.
'error_value' -- This is the caught exception's value.
'error_tb' -- This is a traceback for the caught exception.
The optional else block is rendered when no exception occurs in the
try block. Exceptions in the else block are not handled by the preceding
except blocks.
The try..finally form specifies a `cleanup` block, to be rendered even
when an exception occurs. Note that any rendered result is discarded if
an exception occurs in either the try or finally blocks. The finally block
is only of any use if you need to clean up something that will not be
cleaned up by the transaction abort code.
The finally block will always be called, wether there was an exception in
the try block or not, or wether or not you used a return tag in the try
block. Note that any output of the finally block is discarded if you use a
return tag in the try block.
If an exception occurs in the try block, and an exception occurs in the
finally block, or you use the return tag in that block, any information
about that first exception is lost. No information about the first
exception is available in the finally block. Also, if you use a return tag
in the try block, and an exception occurs in the finally block or you use
a return tag there as well, the result returned in the try block will be
lost.
Original version by Jordan B. Baker.
Try..finally and try..else implementation by Martijn Pieters.
"""
name = 'try'
blockContinuations = 'except', 'else', 'finally'
finallyBlock = None
elseBlock = None
def __init__(self, context, blocks):
tname, args, section = blocks[0]
self.args = parse_params(args)
self.section = section.blocks
# Find out if this is a try..finally type
if len(blocks) == 2 and blocks[1][0] == 'finally':
self.finallyBlock = blocks[1][2].blocks
# This is a try [except]* [else] block.
else:
# store handlers as tuples (name,block)
self.handlers = []
defaultHandlerFound = 0
for tname, nargs, nsection in blocks[1:]:
if tname == 'else':
if not self.elseBlock is None:
raise ParseError(
'No more than one else block is allowed',
self.name)
self.elseBlock = nsection.blocks
elif tname == 'finally':
raise ParseError(
'A try..finally combination cannot contain '
'any other else, except or finally blocks',
self.name)
else:
if not self.elseBlock is None:
raise ParseError(
'The else block should be the last block '
'in a try tag', self.name)
for errname in nargs.split():
self.handlers.append((errname, nsection.blocks))
if nargs.strip() == '':
if defaultHandlerFound:
raise ParseError(
'Only one default exception handler '
'is allowed', self.name)
else:
defaultHandlerFound = 1
self.handlers.append(('', nsection.blocks))
def render(self, md):
if (self.finallyBlock is None):
return self.render_try_except(md)
else:
return self.render_try_finally(md)
def render_try_except(self, md):
result = ''
# first we try to render the first block
try:
result = render_blocks(self.section, md)
except DTReturn:
raise
except:
# but an error occurs.. save the info.
t, v = sys.exc_info()[:2]
if isinstance(t, StringType):
errname = t
else:
errname = t.__name__
handler = self.find_handler(t)
if handler is None:
# we didn't find a handler, so reraise the error
raise
# found the handler block, now render it
try:
f = StringIO()
traceback.print_exc(100,f)
error_tb = f.getvalue()
ns = md.namespace(error_type=errname, error_value=v,
error_tb=error_tb)[0]
md._push_instance(ns)
return render_blocks(handler, md)
finally:
md._pop(1)
else:
# No errors have occurred, render the optional else block
if (self.elseBlock is None):
return result
else:
return result + render_blocks(self.elseBlock, md)
def render_try_finally(self, md):
result = ''
# first try to render the first block
try:
result = render_blocks(self.section, md)
# Then handle finally block
finally:
result = result + render_blocks(self.finallyBlock, md)
return result
def find_handler(self,exception):
"recursively search for a handler for a given exception"
if isinstance(exception, StringType):
for e,h in self.handlers:
if exception==e or e=='':
return h
else:
return None
for e,h in self.handlers:
if e==exception.__name__ or e=='' or self.match_base(exception,e):
return h
return None
def match_base(self,exception,name):
for base in exception.__bases__:
if base.__name__ == name or self.match_base(base, name):
return 1
return None
__call__ = render | zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/dt_try.py | dt_try.py |
"""HTML formated DocumentTemplates
"""
import re
from zope.documenttemplate.dt_string import String
from zope.documenttemplate.dt_util import ParseError
class DTMLRegExClass:
def search(self, text, start=0,
name_match=re.compile('[\0- ]*[a-zA-Z]+[\0- ]*').match,
start_search=re.compile('[<&]').search,
ent_name=re.compile('[-a-zA-Z0-9_.]+').match
):
while True:
mo = start_search(text, start)
if mo is None:
return None
s = mo.start(0)
if text[s:s+6] == '<dtml-':
e = n = s+6
while True:
e = text.find('>', e+1)
if e < 0:
return None
if len(text[n:e].split('"'))%2:
# check for even number of "s inside
break
en = 1
end = ''
elif text[s:s+7] == '</dtml-':
e=n=s+7
while True:
e=text.find('>',e+1)
if e < 0:
return None
if len(text[n:e].split('"'))%2:
# check for even number of "s inside
break
en=1
end='/'
else:
if text[s:s+5] == '&dtml' and text[s+5] in '.-':
n=s+6
e=text.find(';', n)
if e >= 0:
args=text[n:e]
l=len(args)
mo = ent_name(args)
if mo is not None and mo.end(0)-mo.start(0) == l:
d=self.__dict__
if text[s+5] == '-':
d[1] = d['end'] = ''
d[2] = d['name'] = 'var'
d[0] = text[s:e+1]
d[3] = d['args'] = args + ' html_quote'
self._start = s
return self
else:
nn=args.find('-')
if nn >= 0 and nn < l-1:
d[1]=d['end']=''
d[2]=d['name']='var'
d[0]=text[s:e+1]
args=(args[nn+1:]+' '+
args[:nn].replace('.', ' '))
d[3]=d['args']=args
self._start = s
return self
start = s + 1
continue
break
mo=name_match(text,n)
if mo is None:
return None
l = mo.end(0) - mo.start(0)
a=n+l
name=text[n:a].strip()
args=text[a:e].strip()
d=self.__dict__
d[0]=text[s:e+en]
d[1]=d['end']=end
d[2]=d['name']=name
d[3]=d['args']=args
self._start = s
return self
def group(self, *args):
get=self.__dict__.get
if len(args)==1:
return get(args[0])
return tuple(map(get, args))
def start(self, *args):
return self._start
class HTML(String):
"""HTML Document Templates
HTML Document templates use HTML server-side-include syntax,
rather than Python format-string syntax. Here's a simple example:
<dtml-in results>
<dtml-var name>
</dtml-in>
HTML document templates quote HTML tags in source when the
template is converted to a string. This is handy when templates
are inserted into HTML editing forms.
"""
def tagre(self):
return DTMLRegExClass()
def parseTag(self, tagre, command=None, sargs=''):
"""Parse a tag using an already matched re
Return: tag, args, command, coname
where: tag is the tag,
args is the tag\'s argument string,
command is a corresponding command info structure if the
tag is a start tag, or None otherwise, and
coname is the name of a continue tag (e.g. else)
or None otherwise
"""
tag, end, name, args, =tagre.group(0, 'end', 'name', 'args')
args=args.strip()
if end:
if not command or name != command.name:
raise ParseError('unexpected end tag', tag)
return tag, args, None, None
if command and name in command.blockContinuations:
if name=='else' and args:
# Waaaaaah! Have to special case else because of
# old else start tag usage. Waaaaaaah!
l=len(args)
if not (args==sargs or
args==sargs[:l] and sargs[l:l+1] in ' \t\n'):
return tag, args, self.commands[name], None
return tag, args, None, name
try: return tag, args, self.commands[name], None
except KeyError:
raise ParseError('Unexpected tag', tag)
def SubTemplate(self, name):
return HTML('', __name__=name)
def varExtra(self,tagre):
return 's'
def quotedHTML(self,
text=None,
character_entities=(
(('&'), '&'),
(("<"), '<' ),
((">"), '>' ),
(('"'), '"'))): #"
if text is None:
text=self.read_raw()
for re, name in character_entities:
if text.find(re) >= 0:
text = name.join(text.split(re))
return text
errQuote = quotedHTML
def __str__(self):
return self.quotedHTML() | zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/dt_html.py | dt_html.py |
from zope.documenttemplate.dt_util import render_blocks, Eval, ParseError
from types import StringType
import re
class Let:
blockContinuations = ()
name = 'let'
def __init__(self, context, blocks):
tname, args, section = blocks[0]
self.__name__ = args
self.section = section.blocks
self.args = args = parse_let_params(args)
for i in range(len(args)):
name,expr = args[i]
if expr[:1] == '"' and expr[-1:] == '"' and len(expr) > 1:
# expr shorthand
expr = expr[1:-1]
try:
args[i] = name, Eval(context, expr).eval
except SyntaxError, v:
m,(huh,l,c,src) = v
raise ParseError(
'<strong>Expression (Python) Syntax error</strong>:'
'\n<pre>\n%s\n</pre>\n' % v[0],
'let')
def render(self, md):
d = {}
md._push(d)
try:
for name,expr in self.args:
if isinstance(expr, StringType):
d[name] = md[expr]
else:
d[name] = expr(md)
return render_blocks(self.section, md)
finally:
md._pop(1)
__call__ = render
def parse_let_params(text,
result=None,
tag='let',
parmre=re.compile('([\000- ]*([^\000- ="]+)=([^\000- ="]+))'),
qparmre=re.compile('([\000- ]*([^\000- ="]+)="([^"]*)")'),
**parms):
result = result or []
mo = parmre.match(text)
mo1 = qparmre.match(text)
if mo is not None:
name = mo.group(2)
value = mo.group(3)
l = len(mo.group(1))
elif mo1 is not None:
name = mo1.group(2)
value = '"%s"' % mo1.group(3)
l = len(mo1.group(1))
else:
if not text or not text.strip():
return result
raise ParseError('invalid parameter: "%s"' % text, tag)
result.append((name,value))
text = text[l:].strip()
if text:
return apply(parse_let_params, (text, result,tag), parms)
else:
return result | zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/dt_let.py | dt_let.py |
from zope.documenttemplate.dt_util import ParseError, parse_params, name_param
from zope.documenttemplate.dt_util import render_blocks, ValidationError, Eval
import re
from zope.documenttemplate.dt_insv import sequence_variables, opt
from types import StringType, ListType, TupleType, IntType, FloatType, NoneType
class InFactory:
blockContinuations = ('else',)
name = 'in'
def __call__(self, context, blocks):
i = InClass(context, blocks)
if i.batch:
return i.renderwb
else:
return i.renderwob
In = InFactory()
class InError(Exception):
"""Strings are not allowed as input to the in tag"""
class InClass:
elses = None
expr = sort = batch = mapping = None
start_name_re = None
reverse = None
sort_expr = reverse_expr = None
def __init__(self, context, blocks):
tname, args, section = blocks[0]
args=parse_params(args, name='', start='1',end='-1',size='10',
orphan='3',overlap='1',mapping=1,
skip_unauthorized=1,
previous=1, next=1, expr='', sort='',
reverse=1, sort_expr='', reverse_expr='')
self.args=args
has_key=args.has_key
if has_key('sort'):
self.sort=sort=args['sort']
if sort=='sequence-item': self.sort=''
if has_key('sort_expr'):
self.sort_expr = Eval(context, args['sort_expr'])
if has_key('reverse_expr'):
self.reverse_expr = Eval(context, args['reverse_expr'])
if has_key('reverse'):
self.reverse = args['reverse']
if has_key('mapping'):
self.mapping = args['mapping']
for n in 'start', 'size', 'end':
if has_key(n):
self.batch=1
for n in 'orphan','overlap','previous','next':
if has_key(n) and not self.batch:
raise ParseError(
"""
The %s attribute was used but neither of the
<code>start</code>, <code>end</code>, or <code>size</code>
attributes were used.
""" % n, 'in')
if has_key('start'):
v = args['start']
if isinstance(v, StringType):
try: v.atoi()
except:
self.start_name_re = re.compile(
'&+'+
''.join(map(lambda c: "[%s]" % c, v))+
'=[0-9]+&+')
name, expr = name_param(context, args, 'in', 1)
if expr is not None:
expr = expr.eval
self.__name__, self.expr = name, expr
self.section = section.blocks
if len(blocks) > 1:
if len(blocks) != 2: raise ParseError(
'too many else blocks', 'in')
tname, args, section = blocks[1]
args=parse_params(args, name='')
if args:
ename = name_param(context, args)
if ename != name:
raise ParseError(
'name in else does not match in', 'in')
self.elses = section.blocks
def renderwb(self, md):
expr = self.expr
name = self.__name__
if expr is None:
sequence = md[name]
cache = {name: sequence }
else:
sequence = expr(md)
cache = None
if not sequence:
if self.elses:
return render_blocks(self.elses, md)
return ''
if isinstance(sequence, StringType):
raise InError('Strings are not allowed as input to the in tag.')
section = self.section
params = self.args
mapping = self.mapping
if self.sort_expr is not None:
self.sort = self.sort_expr.eval(md)
sequence = self.sort_sequence(sequence)
elif self.sort is not None:
sequence = self.sort_sequence(sequence)
if self.reverse_expr is not None and self.reverse_expr.eval(md):
sequence = self.reverse_sequence(sequence)
elif self.reverse is not None:
sequence = self.reverse_sequence(sequence)
next = previous = 0
try:
start = int_param(params, md, 'start', 0)
except:
start=1
end = int_param(params, md, 'end', 0)
size = int_param(params, md, 'size', 0)
overlap = int_param(params, md, 'overlap', 0)
orphan = int_param(params, md, 'orphan', '3')
start, end, sz = opt(start, end, size, orphan, sequence)
if params.has_key('next'):
next = 1
if params.has_key('previous'):
previous = 1
last = end - 1
first = start - 1
try:
query_string = md['QUERY_STRING']
except:
query_string = ''
vars = sequence_variables(sequence,'?' + query_string,
self.start_name_re)
kw = vars.data
kw['mapping'] = mapping
kw['sequence-step-size'] = sz
kw['sequence-step-overlap'] = overlap
kw['sequence-step-start'] = start
kw['sequence-step-end'] = end
kw['sequence-step-start-index'] = start - 1
kw['sequence-step-end-index'] = end - 1
kw['sequence-step-orphan'] = orphan
push = md._push
pop = md._pop
render = render_blocks
if cache:
push(cache)
push(vars)
try:
if previous:
if first > 0:
pstart, pend, psize = opt(0, first+overlap,
sz, orphan, sequence)
kw['previous-sequence'] = 1
kw['previous-sequence-start-index'] = pstart - 1
kw['previous-sequence-end-index'] = pend - 1
kw['previous-sequence-size'] = pend + 1 - pstart
result=render(section,md)
elif self.elses:
result = render(self.elses, md)
else:
result = ''
elif next:
try:
# The following line is a sneaky way to test whether
# there are more items, without actually
# computing a length:
sequence[end]
except IndexError:
if self.elses:
result = render(self.elses, md)
else:
result = ''
else:
pstart, pend, psize = opt(end+1-overlap, 0,
sz, orphan, sequence)
kw['next-sequence'] = 1
kw['next-sequence-start-index'] = pstart - 1
kw['next-sequence-end-index'] = pend - 1
kw['next-sequence-size'] = pend + 1 - pstart
result = render(section, md)
else:
result = []
append = result.append
validate = md.validate
for index in range(first,end):
# preset
kw['previous-sequence'] = 0
# now more often defined then previously
kw['next-sequence'] = 0
if index==first or index==last:
# provide batching information
if first > 0:
pstart, pend, psize = opt(0, first + overlap,
sz, orphan, sequence)
if index == first:
kw['previous-sequence'] = 1
kw['previous-sequence-start-index'] = pstart - 1
kw['previous-sequence-end-index'] = pend - 1
kw['previous-sequence-size'] = pend + 1 - pstart
try:
# The following line is a sneaky way to
# test whether there are more items,
# without actually computing a length:
sequence[end]
pstart, pend, psize = opt(end + 1 - overlap, 0,
sz, orphan, sequence)
if index == last:
kw['next-sequence'] = 1
kw['next-sequence-start-index'] = pstart - 1
kw['next-sequence-end-index'] = pend - 1
kw['next-sequence-size'] = pend + 1 - pstart
except:
pass
if index == last:
kw['sequence-end'] = 1
client = sequence[index]
if validate is not None:
try:
vv = validate(sequence, sequence, None, client,md)
except:
vv = 0
if not vv:
if (params.has_key('skip_unauthorized') and
params['skip_unauthorized']):
if index == first:
kw['sequence-start'] = 0
continue
raise ValidationError(index)
kw['sequence-index'] = index
if isinstance(client, TupleType) and len(client) == 2:
client = client[1]
if mapping:
push(client)
else:
md._push_instance(client)
try:
append(render(section, md))
finally:
pop(1)
if index == first:
kw['sequence-start'] = 0
result = ''.join(result)
finally:
if cache:
pop()
pop()
return result
def renderwob(self, md):
"""RENDER WithOutBatch"""
expr = self.expr
name = self.__name__
if expr is None:
sequence = md[name]
cache = {name: sequence }
else:
sequence = expr(md)
cache = None
if not sequence:
if self.elses:
return render_blocks(self.elses, md)
return ''
if isinstance(sequence, StringType):
raise InError('Strings are not allowed as input to the in tag.')
section = self.section
mapping = self.mapping
if self.sort_expr is not None:
self.sort = self.sort_expr.eval(md)
sequence = self.sort_sequence(sequence)
elif self.sort is not None:
sequence = self.sort_sequence(sequence)
if self.reverse_expr is not None and self.reverse_expr.eval(md):
sequence = self.reverse_sequence(sequence)
elif self.reverse is not None:
sequence = self.reverse_sequence(sequence)
vars = sequence_variables(sequence)
kw = vars.data
kw['mapping'] = mapping
l = len(sequence)
last = l - 1
push = md._push
pop = md._pop
render = render_blocks
get = self.args.get
if cache:
push(cache)
push(vars)
try:
result = []
append = result.append
validate = md.validate
for index in range(l):
if index == last:
kw['sequence-end'] = 1
client = sequence[index]
if validate is not None:
try:
vv = validate(sequence, sequence, None, client, md)
except:
vv = 0
if not vv:
if get('skip_unauthorized'):
if index == 1:
kw['sequence-start'] = 0
continue
raise ValidationError(index)
kw['sequence-index'] = index
if isinstance(client, TupleType) and len(client) == 2:
client = client[1]
if mapping:
push(client)
else:
md._push_instance(client)
try:
append(render(section, md))
finally:
pop()
if index == 0:
kw['sequence-start'] = 0
result = ''.join(result)
finally:
if cache:
pop()
pop()
return result
def sort_sequence(self, sequence):
# Modified with multiple sort fields by Ross Lazarus
# April 7 2000 [email protected]
# eg <dtml in "foo" sort=akey,anotherkey>
sort = self.sort
sortfields = sort.split(',') # multi sort = key1,key2
multsort = len(sortfields) > 1 # flag: is multiple sort
mapping = self.mapping
isort = not sort
s = []
for client in sequence:
k = None
if isinstance(client, TupleType) and len(client)==2:
if isort:
k = client[0]
v = client[1]
else:
if isort:
k = client
v = client
if sort:
if multsort: # More than one sort key.
k = []
for sk in sortfields:
if mapping:
akey = v.get(sk)
else:
akey = getattr(v, sk, None)
if not basic_type(akey):
try:
akey = akey()
except:
pass
k.append(akey)
else: # One sort key.
if mapping:
k = v.get(sort)
else:
k = getattr(v, sort, None)
if not basic_type(type(k)):
try:
k = k()
except:
pass
s.append((k,client))
s.sort()
sequence = []
for k, client in s:
sequence.append(client)
return sequence
def reverse_sequence(self, sequence):
s = list(sequence)
s.reverse()
return s
basic_type = {StringType: 1, IntType: 1, FloatType: 1, TupleType: 1,
ListType: 1, NoneType: 1}.has_key
def int_param(params, md, name, default=0, st=StringType):
try:
v = params[name]
except:
v = default
if v:
try:
v = v.atoi()
except:
v = md[v]
if isinstance(v, st):
v = v.atoi()
return v | zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/dt_in.py | dt_in.py |
"""Base DTML string class
"""
import re, thread
from zope.documenttemplate.dt_util import ParseError, render_blocks
from zope.documenttemplate.dt_var import Var, Call, Comment
from zope.documenttemplate.dt_return import ReturnTag, DTReturn
from types import TupleType
_marker = [] # Create a new marker object.
class String:
"""Document templates defined from strings.
Document template strings use an extended form of python string
formatting. To insert a named value, simply include text of the
form: '%(name)x', where 'name' is the name of the value and 'x' is
a format specification, such as '12.2d'.
To intrduce a block such as an 'if' or an 'in' or a block continuation,
such as an 'else', use '[' as the format specification. To
terminate a block, ise ']' as the format specification, as in::
%(in results)[
%(name)s
%(in results)]
"""
from zope.documenttemplate.dt_util import TemplateDict
# Document Templates masquerade as functions:
class func_code:
pass
func_code = func_code()
func_code.co_varnames = 'self', 'REQUEST'
func_code.co_argcount = 2
func_defaults = ()
def errQuote(self, s):
return s
def parse_error(self, mess, tag, text, start):
raise ParseError("%s, for tag %s, on line %s of %s<p>" % (
mess, self.errQuote(tag), len(text[:start].split('\n')),
self.errQuote(self.__name__)))
commands={
'var': Var,
'call': Call,
'in': ('in', 'dt_in','In'),
'with': ('with', 'dt_with','With'),
'if': ('if', 'dt_if','If'),
'unless': ('unless', 'dt_if','Unless'),
'else': ('else', 'dt_if','Else'),
'comment': Comment,
'raise': ('raise', 'dt_raise','Raise'),
'try': ('try', 'dt_try','Try'),
'let': ('let', 'dt_let', 'Let'),
'return': ReturnTag,
}
def SubTemplate(self, name):
return String('', __name__=name)
def tagre(self):
return re.compile(
'%\\(' # beginning
'(?P<name>[a-zA-Z0-9_/.-]+)' # tag name
'('
'[\000- ]+' # space after tag name
'(?P<args>([^\\)"]+("[^"]*")?)*)' # arguments
')?'
'\\)(?P<fmt>[0-9]*[.]?[0-9]*[a-z]|[]![])' # end
, re.I)
def _parseTag(self, match_ob, command=None, sargs='', tt=TupleType):
tag, args, command, coname = self.parseTag(match_ob, command, sargs)
if isinstance(command, tt):
cname, module, name = command
d={}
try:
exec 'from %s import %s' % (module, name) in d
except ImportError:
exec 'from zope.documenttemplate.%s import %s' % (module,
name) in d
command = d[name]
self.commands[cname] = command
return tag, args, command, coname
def parseTag(self, match_ob, command=None, sargs=''):
"""Parse a tag using an already matched re
Return: tag, args, command, coname
where: tag is the tag,
args is the tag\'s argument string,
command is a corresponding command info structure if the
tag is a start tag, or None otherwise, and
coname is the name of a continue tag (e.g. else)
or None otherwise
"""
tag, name, args, fmt = match_ob.group(0, 'name', 'args', 'fmt')
args = args and args.strip() or ''
if fmt == ']':
if not command or name != command.name:
raise ParseError('unexpected end tag', tag)
return tag, args, None, None
elif fmt == '[' or fmt == '!':
if command and name in command.blockContinuations:
if name=='else' and args:
# Waaaaaah! Have to special case else because of
# old else start tag usage. Waaaaaaah!
l = len(args)
if not (args == sargs or
args == sargs[:l] and sargs[l:l+1] in ' \t\n'):
return tag, args, self.commands[name], None
return tag, args, None, name
try:
return tag, args, self.commands[name], None
except KeyError:
raise ParseError('Unexpected tag', tag)
else:
# Var command
args = args and ("%s %s" % (name, args)) or name
return tag, args, Var, None
def varExtra(self, match_ob):
return match_ob.group('fmt')
def parse(self, text, start=0, result=None, tagre=None):
if result is None:
result = []
if tagre is None:
tagre = self.tagre()
mo = tagre.search(text, start)
while mo:
l = mo.start(0)
try:
tag, args, command, coname = self._parseTag(mo)
except ParseError, m:
self.parse_error(m[0], m[1], text, l)
s = text[start:l]
if s:
result.append(s)
start = l + len(tag)
if hasattr(command,'blockContinuations'):
start = self.parse_block(text, start, result, tagre,
tag, l, args, command)
else:
try:
if command is Var:
r = command(self, args, self.varExtra(mo))
else:
r = command(self, args)
if hasattr(r,'simple_form'):
r = r.simple_form
result.append(r)
except ParseError, m:
self.parse_error(m[0], tag, text, l)
mo = tagre.search(text, start)
text = text[start:]
if text:
result.append(text)
return result
def skip_eol(self, text, start, eol=re.compile('[ \t]*\n')):
# if block open is followed by newline, then skip past newline
mo = eol.match(text, start)
if mo is not None:
start = start + mo.end(0) - mo.start(0)
return start
def parse_block(self, text, start, result, tagre,
stag, sloc, sargs, scommand):
start = self.skip_eol(text, start)
blocks = []
tname = scommand.name
sname = stag
sstart = start
sa = sargs
while True:
mo = tagre.search(text, start)
if mo is None:
self.parse_error('No closing tag', stag, text, sloc)
l = mo.start(0)
try:
tag, args, command, coname= self._parseTag(mo, scommand, sa)
except ParseError, m:
self.parse_error(m[0], m[1], text, l)
if command:
start = l + len(tag)
if hasattr(command, 'blockContinuations'):
# New open tag. Need to find closing tag.
start=self.parse_close(text, start, tagre, tag, l,
command, args)
else:
# Either a continuation tag or an end tag
section = self.SubTemplate(sname)
section._v_blocks = section.blocks = \
self.parse(text[:l],sstart)
section._v_cooked = None
blocks.append((tname, sargs, section))
start = self.skip_eol(text, l+len(tag))
if coname:
tname = coname
sname = tag
sargs = args
sstart = start
else:
try:
r = scommand(self, blocks)
if hasattr(r,'simple_form'):
r = r.simple_form
result.append(r)
except ParseError, m:
self.parse_error(m[0], stag, text, l)
return start
def parse_close(self, text, start, tagre, stag, sloc, scommand, sa):
while True:
mo = tagre.search(text, start)
if mo is None:
self.parse_error('No closing tag', stag, text, sloc)
l = mo.start(0)
try:
tag, args, command, coname= self._parseTag(mo, scommand, sa)
except ParseError, m:
self.parse_error(m[0], m[1], text, l)
start = l + len(tag)
if command:
if hasattr(command, 'blockContinuations'):
# New open tag. Need to find closing tag.
start = self.parse_close(text, start, tagre, tag, l,
command, args)
elif not coname:
return start
shared_globals={}
def __init__(self, source_string='', mapping=None, __name__='<string>',
**vars):
"""\
Create a document template from a string.
The optional parameter, 'mapping', may be used to provide a
mapping object containing defaults for values to be inserted.
"""
self.raw = source_string
self.initvars(mapping, vars)
def default(self, name=None, **kw):
"""Change or query default values in a document template.
If a name is specified, the value of the named default value
before the operation is returned.
Keyword arguments are used to provide default values.
"""
if name:
name = self.globals[name]
for key in kw.keys():
self.globals[key] = kw[key]
return name
def var(self,name=None,**kw):
"""Change or query a variable in a document template.
If a name is specified, the value of the named variable before
the operation is returned.
Keyword arguments are used to provide variable values.
"""
if name:
name = self._vars[name]
for key in kw.keys():
self._vars[key] = kw[key]
return name
def munge(self, source_string=None, mapping=None, **vars):
"""Change the text or default values for a document template."""
if mapping is not None or vars:
self.initvars(mapping, vars)
if source_string is not None:
self.raw = source_string
self.cook()
def read_raw(self, raw=None):
return self.raw
def read(self, raw=None):
return self.read_raw()
def cook(self, cooklock=thread.allocate_lock()):
cooklock.acquire()
try:
self._v_blocks = self.parse(self.read())
self._v_cooked = None
finally:
cooklock.release()
def initvars(self, globals, vars):
if globals:
for k in globals.keys():
if k[:1] != '_' and not vars.has_key(k):
vars[k] = globals[k]
self.globals = vars
self._vars = {}
def __render_with_namespace__(self, md):
return self(None, md)
def __call__(self,client=None,mapping={},**kw):
'''\
Generate a document from a document template.
The document will be generated by inserting values into the
format string specified when the document template was
created. Values are inserted using standard python named
string formats.
The optional argument 'client' is used to specify a object
containing values to be looked up. Values will be looked up
using getattr, so inheritence of values is supported. Note
that names beginning with '_' will not be looked up from the
client.
The optional argument, 'mapping' is used to specify a mapping
object containing values to be inserted.
Values to be inserted may also be specified using keyword
arguments.
Values will be inserted from one of several sources. The
sources, in the order in which they are consulted, are:
o Keyword arguments,
o The 'client' argument,
o The 'mapping' argument,
o The keyword arguments provided when the object was
created, and
o The 'mapping' argument provided when the template was
created.
'''
# print '============================================================'
# print '__called__'
# print self.raw
# print kw
# print client
# print mapping
# print '============================================================'
if mapping is None:
mapping = {}
if not hasattr(self,'_v_cooked'):
try:
changed = self.__changed__()
except:
changed = 1
self.cook()
if not changed:
self.__changed__(0)
pushed=None
try:
if isinstance(mapping, self.TemplateDict):
pushed=0
except:
pass
globals = self.globals
if pushed is not None:
# We were passed a TemplateDict, so we must be a sub-template
md = mapping
push = md._push
if globals:
push(self.globals)
pushed = pushed+1
else:
md = self.TemplateDict()
push = md._push
shared_globals = self.shared_globals
if shared_globals:
push(shared_globals)
if globals:
push(globals)
if mapping:
push(mapping)
md.validate = self.validate
if client is not None:
if isinstance(client, TupleType):
md.this = client[-1]
else:
md.this = client
pushed=0
level = md.level
if level > 200:
raise SystemError('infinite recursion in document template')
md.level = level+1
if client is not None:
if isinstance(client, TupleType):
# if client is a tuple, it represents a "path" of clients
# which should be pushed onto the md in order.
for ob in client:
md._push_instance(ob)
pushed += 1
else:
# otherwise its just a normal client object.
md._push_instance(client)
pushed += 1
if self._vars:
push(self._vars)
pushed += 1
if kw:
push(kw)
pushed += 1
try:
try:
result = render_blocks(self._v_blocks, md)
except DTReturn, v:
result = v.v
return result
finally:
if pushed:
md._pop(pushed) # Get rid of circular reference!
md.level=level # Restore previous level
validate=None
def __str__(self):
return self.read()
def __getstate__(self, _special=('_v_', '_p_')):
# Waaa, we need _v_ behavior but we may not subclass Persistent
d={}
for k, v in self.__dict__.items():
if k[:3] in _special: continue
d[k] = v
return d
def compile_python_expresssion(self, src):
return compile(src, getattr(self, '__name__', '<string>'), 'eval') | zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/dt_string.py | dt_string.py |
from zope.documenttemplate.dt_util import parse_params, name_param, html_quote
from zope.structuredtext import stx2htmlWithReferences
import re, sys
from urllib import quote, quote_plus
class Var:
name = 'var'
expr = None
def __init__(self, context, args, fmt='s'):
if args[:4] == 'var ':
args = args[4:]
args = parse_params(args, name='', lower=1, upper=1, expr='',
capitalize=1, spacify=1, null='', fmt='s',
size=0, etc='...', thousands_commas=1,
html_quote=1, url_quote=1, sql_quote=1,
url_quote_plus=1, missing='',
newline_to_br=1, url=1)
self.args = args
self.modifiers = tuple(
map(lambda t: t[1],
filter(lambda m, args=args, used=args.has_key:
used(m[0]) and args[m[0]],
modifiers)))
name, expr = name_param(context, args, 'var', 1)
self.__name__, self.expr = name, expr
self.fmt = fmt
if len(args) == 1 and fmt == 's':
if expr is None:
expr = name
else:
expr = expr.eval
self.simple_form = expr,
def render(self, md):
args = self.args
have_arg = args.has_key
name = self.__name__
val = self.expr
if val is None:
if md.has_key(name):
if have_arg('url'):
val = md.getitem(name,0)
val = val.absolute_url()
else:
val = md[name]
else:
if have_arg('missing'):
return args['missing']
else:
raise KeyError(name)
else:
val = val.eval(md)
if have_arg('url'):
val = val.absolute_url()
__traceback_info__ = name, val, args
if have_arg('null') and not val and val != 0:
# check for null (false but not zero, including None, [], '')
return args['null']
# handle special formats defined using fmt= first
if have_arg('fmt'):
fmt=args['fmt']
if have_arg('null') and not val and val != 0:
try:
if hasattr(val, fmt):
val = getattr(val,fmt)()
elif special_formats.has_key(fmt):
val = special_formats[fmt](val, name, md)
elif fmt == '':
val = ''
else:
val = fmt % val
except:
t, v = sys.exc_info()[:2]
if val is None or not str(val):
return args['null']
raise t(v)
else:
# We duplicate the code here to avoid exception handler
# which tends to screw up stack or leak
if hasattr(val, fmt):
val = getattr(val,fmt)()
elif special_formats.has_key(fmt):
val = special_formats[fmt](val, name, md)
elif fmt == '':
val = ''
else:
val = fmt % val
# finally, pump it through the actual string format...
fmt=self.fmt
if fmt == 's':
val = str(val)
else:
val = ('%'+self.fmt) % (val,)
# next, look for upper, lower, etc
for f in self.modifiers:
val = f(val)
if have_arg('size'):
size = args['size']
try:
size = int(size)
except:
raise 'Document Error',(
'''a <code>size</code> attribute was used in a <code>var</code>
tag with a non-integer value.''')
if len(val) > size:
val = val[:size]
l = val.rfind(' ')
if l > size/2:
val = val[:l+1]
if have_arg('etc'):
l = args['etc']
else:
l = '...'
val += l
return val
__call__ = render
class Call:
name = 'call'
expr = None
def __init__(self, context, args):
args = parse_params(args, name='', expr='')
name, expr = name_param(context, args,'call',1)
if expr is None:
expr = name
else:
expr = expr.eval
self.simple_form = expr, None
def url_quote(v, name='(Unknown name)', md={}):
return quote(str(v))
def url_quote_plus(v, name='(Unknown name)', md={}):
return quote_plus(str(v))
def newline_to_br(v, name='(Unknown name)', md={}):
v = str(v)
v = v.replace('\r', '')
v = v.replace('\n', '<br>\n')
return v
def whole_dollars(v, name='(Unknown name)', md={}):
try:
return "$%d" % v
except:
return ''
def dollars_and_cents(v, name='(Unknown name)', md={}):
try:
return "$%.2f" % v
except:
return ''
def thousands_commas(v, name='(Unknown name)', md={},
thou=re.compile(
r"([0-9])([0-9][0-9][0-9]([,.]|$))").search):
v = str(v)
vl = v.split('.')
if not vl:
return v
v = vl[0]
del vl[0]
if vl:
s = '.' + '.'.join(vl)
else:
s = ''
mo = thou(v)
while mo is not None:
l = mo.start(0)
v = v[:l+1] + ',' + v[l+1:]
mo = thou(v)
return v+s
def whole_dollars_with_commas(v, name='(Unknown name)', md={}):
try:
v = "$%d" % v
except:
v = ''
return thousands_commas(v)
def dollars_and_cents_with_commas(v, name='(Unknown name)', md={}):
try:
v = "$%.2f" % v
except:
v = ''
return thousands_commas(v)
def len_format(v, name='(Unknown name)', md={}):
return str(len(v))
def len_comma(v, name='(Unknown name)', md={}):
return thousands_commas(str(len(v)))
def structured_text(v, name='(Unknown name)', md={}):
return stx2htmlWithReferences(str(v), level=3, header=0)
def sql_quote(v, name='(Unknown name)', md={}):
"""Quote single quotes in a string by doubling them.
This is needed to securely insert values into sql
string literals in templates that generate sql.
"""
if v.find("'") >= 0:
return "''".join(v.split("'"))
return v
special_formats={
'whole-dollars': whole_dollars,
'dollars-and-cents': dollars_and_cents,
'collection-length': len_format,
'structured-text': structured_text,
# The rest are deprecated:
'sql-quote': sql_quote,
'html-quote': html_quote,
'url-quote': url_quote,
'url-quote-plus': url_quote_plus,
'multi-line': newline_to_br,
'comma-numeric': thousands_commas,
'dollars-with-commas': whole_dollars_with_commas,
'dollars-and-cents-with-commas': dollars_and_cents_with_commas,
}
def spacify(val):
if val.find('_') >= 0:
val = ' '.join(val.split('_'))
return val
def lower(val):
return val.lower()
def upper(val):
return val.upper()
def capitalize(val):
return val.capitalize()
modifiers = (html_quote, url_quote, url_quote_plus, newline_to_br,
lower, upper, capitalize, spacify,
thousands_commas, sql_quote)
modifiers = map(lambda f: (f.__name__, f), modifiers)
class Comment:
'''Comments
The 'comment' tag can be used to simply include comments
in DTML source.
For example::
<dtml-comment>
This text is not rendered.
</dtml-comment>
'''
name = 'comment'
blockContinuations = ()
def __init__(self, context, args, fmt=''):
pass
def render(self, md):
return ''
__call__=render | zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/dt_var.py | dt_var.py |
"""DTML utilities
"""
import re
from types import ListType, StringType, TupleType
from cgi import escape
# These imports are for the use of clients of this module, as this
# module is the canonical place to get them.
from zope.documenttemplate.pdocumenttemplate import TemplateDict, InstanceDict
from zope.documenttemplate.pdocumenttemplate import render_blocks
from zope.documenttemplate.ustr import ustr
class ParseError(Exception):
'''Document Template Parse Error'''
class ValidationError(Exception):
'''Unauthorized'''
def html_quote(v, name='(Unknown name)', md={}):
return escape(ustr(v), 1)
def int_param(params, md, name, default=0):
try:
v = params[name]
except:
v = default
if v:
try:
v = v.atoi()
except:
v = md[v]
if isinstance(v, StringType):
v = v.atoi()
return v or 0
class Eval:
def __init__(self, context, expr):
self.expr = '('+expr.strip()+')'
self.code = context.compile_python_expresssion(self.expr)
def eval(self, mapping):
d={'_vars': mapping._proxied(),
'_': mapping._proxied()}
code = self.code
for name in code.co_names:
if not d.has_key(name):
__traceback_info__ = name
try:
d[name] = mapping.getitem(name, 0)
except KeyError:
# Swallow KeyErrors since the expression
# might not actually need the name. If it
# does need the name, a NameError will occur.
pass
return eval(code,
{'__builtins__': getattr(mapping, '__builtins__', None)},
d)
def __call__(self, **kw):
return eval(self.code, {}, kw)
def name_param(context, params, tag='', expr=0, attr='name',
default_unnamed=1):
used = params.has_key
__traceback_info__ = params, tag, expr, attr
#if expr and used('expr') and used('') and not used(params['']):
# # Fix up something like: <!--#in expr="whatever" mapping-->
# params[params['']]=default_unnamed
# del params['']
if used(''):
v = params['']
if v[:1] == '"' and v[-1:] == '"' and len(v) > 1: # expr shorthand
if used(attr):
raise ParseError(u'%s and expr given' % attr, tag)
if expr:
if used('expr'):
raise ParseError(u'two exprs given', tag)
v = v[1:-1]
try:
expr=Eval(context, v)
except SyntaxError, v:
raise ParseError(
u'<strong>Expression (Python) Syntax error</strong>:'
u'\n<pre>\n%s\n</pre>\n' % v[0],
tag)
return v, expr
else:
raise ParseError(
u'The "..." shorthand for expr was used in a tag '
u'that doesn\'t support expr attributes.',
tag)
else: # name shorthand
if used(attr):
raise ParseError(u'Two %s values were given' % attr, tag)
if expr:
if used('expr'):
# raise 'Waaaaaa', 'waaa'
raise ParseError(u'%s and expr given' % attr, tag)
return params[''],None
return params['']
elif used(attr):
if expr:
if used('expr'):
raise ParseError(u'%s and expr given' % attr, tag)
return params[attr],None
return params[attr]
elif expr and used('expr'):
name = params['expr']
expr = Eval(context, name)
return name, expr
raise ParseError(u'No %s given' % attr, tag)
Expr_doc = u"""
Python expression support
Several document template tags, including 'var', 'in', 'if', 'else',
and 'elif' provide support for using Python expressions via an
'expr' tag attribute.
Expressions may be used where a simple variable value is
inadequate. For example, an expression might be used to test
whether a variable is greater than some amount::
<dtml-if expr="age > 18">
or to transform some basic data::
<dtml-var expr="phone[:3]">
Objects available in the document templates namespace may be used.
Subobjects of these objects may be used as well, although subobject
access is restricted by the optional validation method.
In addition, a special additional name, '_', is available. The '_'
variable provides access to the document template namespace as a
mapping object. This variable can be useful for accessing objects
in a document template namespace that have names that are not legal
Python variable names::
<dtml-var expr="_['sequence-number']*5">
This variable also has attributes that provide access to standard
utility objects. These attributes include:
- The objects: 'None', 'abs', 'chr', 'divmod', 'float', 'hash',
'hex', 'int', 'len', 'max', 'min', 'oct', 'ord', 'pow',
'round', and 'str' from the standard Python builtin module.
- Special security-aware versions of 'getattr' and 'hasattr',
- The Python 'string', 'math', and 'random' modules, and
- A special function, 'test', that supports if-then expressions.
The 'test' function accepts any number of arguments. If the
first argument is true, then the second argument is returned,
otherwise if the third argument is true, then the fourth
argument is returned, and so on. If there is an odd number of
arguments, then the last argument is returned in the case that
none of the tested arguments is true, otherwise None is
returned.
For example, to convert a value to lower case::
<dtml-var expr="title.lower()">
"""
def parse_params(text,
result=None,
tag='',
unparmre=re.compile('([\000- ]*([^\000- ="]+))'),
qunparmre=re.compile('([\000- ]*("[^"]*"))'),
parmre=re.compile('([\000- ]*([^\000- ="]+)=([^\000- ="]+))'),
qparmre=re.compile('([\000- ]*([^\000- ="]+)="([^"]*)")'),
**parms):
"""Parse tag parameters
The format of tag parameters consists of 1 or more parameter
specifications separated by whitespace. Each specification
consists of an unnamed and unquoted value, a valueless name, or a
name-value pair. A name-value pair consists of a name and a
quoted or unquoted value separated by an '='.
The input parameter, text, gives the text to be parsed. The
keyword parameters give valid parameter names and default values.
If a specification is not a name-value pair and it is not the
first specification and it is a
valid parameter name, then it is treated as a name-value pair with
a value as given in the keyword argument. Otherwise, if it is not
a name-value pair, it is treated as an unnamed value.
The data are parsed into a dictionary mapping names to values.
Unnamed values are mapped from the name '""'. Only one value may
be given for a name and there may be only one unnamed value. """
result = result or {}
# HACK - we precalculate all matches. Maybe we don't need them
# all. This should be fixed for performance issues
mo_p = parmre.match(text)
mo_q = qparmre.match(text)
mo_unp = unparmre.match(text)
mo_unq = qunparmre.match(text)
if mo_p:
name = mo_p.group(2).lower()
value = mo_p.group(3)
l = len(mo_p.group(1))
elif mo_q:
name = mo_q.group(2).lower()
value = mo_q.group(3)
l = len(mo_q.group(1))
elif mo_unp:
name = mo_unp.group(2)
l = len(mo_unp.group(1))
if result:
if parms.has_key(name):
if parms[name] is None: raise ParseError(
u'Attribute %s requires a value' % name, tag)
result[name] = parms[name]
else: raise ParseError(
u'Invalid attribute name, "%s"' % name, tag)
else:
result[''] = name
return apply(parse_params, (text[l:],result), parms)
elif mo_unq:
name = mo_unq.group(2)
l = len(mo_unq.group(1))
if result:
raise ParseError(u'Invalid attribute name, "%s"' % name, tag)
else:
result[''] = name
return apply(parse_params, (text[l:], result), parms)
else:
if not text or not text.strip():
return result
raise ParseError(u'invalid parameter: "%s"' % text, tag)
if not parms.has_key(name):
raise ParseError(u'Invalid attribute name, "%s"' % name, tag)
if result.has_key(name):
p = parms[name]
if type(p) is not ListType or p:
raise ParseError(
u'Duplicate values for attribute "%s"' % name, tag)
result[name] = value
text = text[l:].strip()
if text:
return apply(parse_params, (text,result), parms)
else:
return result | zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/dt_util.py | dt_util.py |
from zope.documenttemplate.dt_util import ParseError, parse_params, name_param
class If:
blockContinuations = 'else', 'elif'
name = 'if'
elses = None
expr = ''
def __init__(self, context, blocks):
tname, args, section = blocks[0]
args = parse_params(args, name='', expr='')
name,expr = name_param(context, args,'if',1)
self.__name__ = name
if expr is None:
cond = name
else:
cond = expr.eval
sections = [cond, section.blocks]
if blocks[-1][0] == 'else':
tname, args, section = blocks[-1]
del blocks[-1]
args = parse_params(args, name='')
if args:
ename,expr=name_param(context, args,'else',1)
if ename != name:
raise ParseError('name in else does not match if', 'in')
elses=section.blocks
else: elses = None
for tname, args, section in blocks[1:]:
if tname == 'else':
raise ParseError(
'more than one else tag for a single if tag', 'in')
args = parse_params(args, name='', expr='')
name,expr = name_param(context, args, 'elif', 1)
if expr is None:
cond = name
else:
cond = expr.eval
sections.append(cond)
sections.append(section.blocks)
if elses is not None:
sections.append(elses)
self.simple_form = tuple(sections)
class Unless:
name = 'unless'
blockContinuations = ()
def __init__(self, context, blocks):
tname, args, section = blocks[0]
args=parse_params(args, name='', expr='')
name,expr=name_param(context, args, 'unless', 1)
if expr is None:
cond = name
else:
cond = expr.eval
self.simple_form = (cond, None, section.blocks)
class Else(Unless):
# The else tag is included for backward compatibility and is deprecated.
name = 'else' | zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/dt_if.py | dt_if.py |
from math import sqrt
from types import IntType, TupleType
mv = None # Missing value
class sequence_variables:
def __init__(self, items=None, query_string='', start_name_re=None):
self.items = items
self.query_string = query_string
self.start_name_re = start_name_re
self.data = data = {
'previous-sequence': 0,
'next-sequence': 0,
'sequence-start': 1,
'sequence-end': 0,
}
def __len__(self):
return 1
def number(self, index):
return index+1
def even(self, index):
return index%2 == 0
def odd(self, index):
return index%2
def letter(self, index):
return chr(ord('a') + index)
def Letter(self, index):
return chr(ord('A') + index)
def key(self,index):
return self.items[index][0]
def item(self,index, tt = TupleType):
i = self.items[index]
if isinstance(i, tt) and len(i)==2:
return i[1]
return i
def roman(self, index):
return self.Roman(index).lower()
def Roman(self,num):
# Force number to be an integer value
num = int(num) + 1
# Initialize roman as an empty string
roman = ''
while num >= 1000:
num = num - 1000
roman = '%sM' % roman
while num >= 500:
num = num - 500
roman = '%sD' % roman
while num >= 100:
num = num - 100
roman = '%sC' % roman
while num >= 50:
num = num - 50
roman = '%sL' % roman
while num >= 10:
num = num - 10
roman = '%sX' % roman
while num >= 5:
num = num - 5
roman = '%sV' % roman
while num < 5 and num >= 1:
num = num - 1
roman = '%sI' % roman
# Replaces special cases in Roman Numerals
roman = sub('DCCCC', 'CM', roman)
roman = sub('CCCC', 'CD', roman)
roman = sub('LXXXX', 'XC', roman)
roman = sub('XXXX', 'XL', roman)
roman = sub('VIIII', 'IX', roman)
roman = sub('IIII', 'IV', roman)
return roman
def value(self, index, name):
data = self.data
item = self.items[index]
if isinstance(item, TupleType) and len(item)==2:
item = item[1]
if data['mapping']:
return item[name]
return getattr(item, name)
def first(self, name, key=''):
data = self.data
if data['sequence-start']:
return 1
index = data['sequence-index']
return self.value(index, name) != self.value(index-1, name)
def last(self, name, key=''):
data = self.data
if data['sequence-end']:
return 1
index = data['sequence-index']
return self.value(index, name) != self.value(index+1, name)
def length(self, ignored):
l=self.data['sequence-length'] = len(self.items)
return l
def query(self, *ignored):
if self.start_name_re is None:
raise KeyError('sequence-query')
query_string = self.query_string
while query_string and query_string[:1] in '?&':
query_string = query_string[1:]
while query_string[-1:] == '&':
query_string = query_string[:-1]
if query_string:
query_string = '&%s&' % query_string
re = self.start_name_re
l = re.search_group(query_string, (0,))
if l:
v = l[1]
l = l[0]
query_string = (query_string[:l] +
query_string[l + len(v) - 1:])
query_string = '?' + query_string[1:]
else:
query_string = '?'
self.data['sequence-query'] = query_string
return query_string
statistic_names = (
'total', 'count', 'min', 'max', 'median', 'mean',
'variance', 'variance-n','standard-deviation', 'standard-deviation-n',
)
def statistics(self, name, key):
items = self.items
data = self.data
mapping = data['mapping']
count = sum = sumsq = 0
min = max = None
scount = smin = smax = None
values = []
svalues = []
for item in items:
try:
if mapping:
item = item[name]
else:
item = getattr(item, name)
try:
if item is mv:
item = None
if isinstance(item, IntType):
s = item * long(item)
else:
s = item * item
sum = sum + item
sumsq = sumsq + s
values.append(item)
if min is None:
min = max = item
else:
if item < min:
min = item
if item > max:
max = item
except:
if item is not None and item is not mv:
if smin is None:
smin = smax = item
else:
if item < smin:
smin = item
if item > smax:
smax = item
svalues.append(item)
except: pass
# Initialize all stats to empty strings:
for stat in self.statistic_names:
data['%s-%s' % (stat,name)] = ''
count = len(values)
try: # Numeric statistics
n = float(count)
mean = sum/n
sumsq = sumsq/n - mean*mean
data['mean-%s' % name] = mean
data['total-%s' % name] = sum
data['variance-n-%s' % name] = sumsq
data['standard-deviation-n-%s' % name] = sqrt(sumsq)
if count > 1:
sumsq = sumsq * n/(n-1)
data['variance-%s' % name] = sumsq
data['standard-deviation-%s' % name] = sqrt(sumsq)
else:
data['variance-%s' % name] = ''
data['standard-deviation-%s' % name] = ''
except:
if min is None: min, max, values = smin, smax, svalues
else:
if smin < min:
min = smin
if smax > max:
max = smax
values = values + svalues
count = len(values)
data['count-%s' % name] = count
# data['_values']=values
if min is not None:
data['min-%s' % name] = min
data['max-%s' % name] = max
values.sort()
if count == 1:
data['median-%s' % name] = min
else:
n=count+1
if n/2 * 2 == n:
data['median-%s' % name] = values[n/2 - 1]
else:
n = n/2
try:
data['median-%s' % name] = (values[n]+values[n-1])/2
except:
try:
data['median-%s' % name] = (
"between %s and %s" % (values[n], values[n-1]))
except: pass
return data[key]
def next_batches(self, suffix='batches', key=''):
if suffix != 'batches':
raise KeyError(key)
data = self.data
sequence = self.items
try:
if not data['next-sequence']:
return ()
sz = data['sequence-step-size']
start = data['sequence-step-start']
end = data['sequence-step-end']
l = len(sequence)
orphan = data['sequence-step-orphan']
overlap = data['sequence-step-overlap']
except:
AttributeError, 'next-batches'
r = []
while end < l:
start, end, spam = opt(end+1-overlap, 0, sz, orphan, sequence)
v = sequence_variables(self.items,
self.query_string, self.start_name_re)
d = v.data
d['batch-start-index'] = start-1
d['batch-end-index'] = end-1
d['batch-size'] = end+1-start
d['mapping'] = data['mapping']
r.append(v)
data['next-batches'] = r
return r
def previous_batches(self, suffix='batches', key=''):
if suffix != 'batches':
raise KeyError(key)
data = self.data
sequence = self.items
try:
if not data['previous-sequence']:
return ()
sz = data['sequence-step-size']
start = data['sequence-step-start']
end = data['sequence-step-end']
l = len(sequence)
orphan = data['sequence-step-orphan']
overlap = data['sequence-step-overlap']
except:
AttributeError, 'previous-batches'
r = []
while start > 1:
start, end, spam = opt(0, start-1+overlap, sz, orphan, sequence)
v = sequence_variables(self.items,
self.query_string, self.start_name_re)
d = v.data
d['batch-start-index'] = start-1
d['batch-end-index'] = end-1
d['batch-size'] = end+1-start
d['mapping'] = data['mapping']
r.append(v)
r.reverse()
data['previous-batches'] = r
return r
special_prefixes = {
'first': first,
'last': last,
'previous': previous_batches,
'next': next_batches,
# These two are for backward compatability with a missfeature:
'sequence-index': lambda self, suffix, key: self['sequence-'+suffix],
'sequence-index-is': lambda self, suffix, key: self['sequence-'+suffix],
}
for n in statistic_names:
special_prefixes[n] = statistics
def __getitem__(self,key,
special_prefixes=special_prefixes,
special_prefix=special_prefixes.has_key
):
data = self.data
if data.has_key(key):
return data[key]
l = key.rfind('-')
if l < 0:
raise KeyError(key)
suffix = key[l+1:]
prefix = key[:l]
if hasattr(self, suffix):
try:
v = data[prefix+'-index']
except:
pass
else:
return getattr(self, suffix)(v)
if special_prefix(prefix):
return special_prefixes[prefix](self, suffix, key)
if prefix[-4:] == '-var':
prefix = prefix[:-4]
try:
return self.value(data[prefix+'-index'], suffix)
except:
pass
if key == 'sequence-query':
return self.query()
raise KeyError(key)
def sub(s1, s2, src):
return s2.join(src.split(s1))
def opt(start, end, size, orphan, sequence):
if size < 1:
if start > 0 and end > 0 and end >= start:
size = end+1 - start
else: size = 7
if start > 0:
try:
sequence[start-1]
except:
start = len(sequence)
if end > 0:
if end < start:
end = start
else:
end = start + size-1
try:
sequence[end+orphan-1]
except:
end = len(sequence)
elif end > 0:
try:
sequence[end-1]
except:
end=len(sequence)
start = end+1 - size
if start - 1 < orphan:
start = 1
else:
start = 1
end = start + size-1
try:
sequence[end+orphan-1]
except:
end = len(sequence)
return start, end, size | zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/dt_insv.py | dt_insv.py |
Untrusted Document Templates
============================
Untrusted document templates implement an untrusted interpreter for
the DTML language. Untrusted templates protect any data they're given.
>>> from zope.documenttemplate.untrusted import UntrustedHTML
Consider a sample class, which allows access to attributes f1, f2, and name:
>>> from zope.security.checker import NamesChecker
>>> class C(object):
... def __init__(self, name, **kw):
... self.name = name
... self.__dict__.update(kw)
... def f1(self):
... return 'f1 called'
... def f2(self):
... return 'f2 called'
... __Security_checker__ = NamesChecker(['f1', 'f2', 'name'])
We can get at alowed data just fine:
>>> UntrustedHTML('<dtml-var f1> <dtml-var name>')(C('bob'))
'f1 called bob'
But we'll get an error if we try to access an attribute we're not
alowed to get:
>>> UntrustedHTML('<dtml-var x>')(C('bob', x=1))
Traceback (most recent call last):
...
KeyError: 'x'
If we create data inside the template, we'll be allowed to manipulate
it:
>>> UntrustedHTML('''
... <dtml-let data="[]">
... <dtml-call expr="data.append(1)"><dtml-var data>
... </dtml-let>
... ''')()
'\n [1]\n'
but any attributes we get from data we create are proxied, and
this protected:
>>> UntrustedHTML('''
... <dtml-let data="[]">
... <dtml-with data><dtml-with __class__><dtml-var __dict__>
... </dtml-with></dtml-with>
... </dtml-let>
... ''')()
Traceback (most recent call last):
...
KeyError: '__dict__'
>>> UntrustedHTML('''
... <dtml-let data="[]">
... <dtml-var expr="data.__class__.__dict__">
... </dtml-let>
... ''')()
Traceback (most recent call last):
...
ForbiddenAttribute: ('__dict__', <type 'list'>)
>>> UntrustedHTML('''<dtml-var expr="'foo'.__class__.__dict__">''')()
Traceback (most recent call last):
...
ForbiddenAttribute: ('__dict__', <type 'str'>)
Access is provided to a number of utility functions provided by the
template dict, but not to hidden functions:
>>> UntrustedHTML('''<dtml-var expr="_.abs(-1)">''')()
'1'
But not to privare attributes:
>>> UntrustedHTML('''<dtml-var expr="_._pop()">''')()
Traceback (most recent call last):
...
ForbiddenAttribute: ('_pop', <an UntrustedTemplateDict>)
| zope.documenttemplate | /zope.documenttemplate-3.4.3.tar.gz/zope.documenttemplate-3.4.3/src/zope/documenttemplate/untrusted/README.txt | README.txt |
Changes
=======
6.0 (2023-03-27)
----------------
- Add support for Python 3.11.
- Drop support for Python 3.6.
5.0 (2022-09-08)
----------------
- Add support for Python 3.8, 3.9, 3.10.
- Drop support for Python 2.7, 3.4, 3.5.
4.3 (2018-10-05)
----------------
- Add support for Python 3.7.
- Drop support for Python 3.3.
4.2 (2017-05-11)
----------------
- Add support for Python 3.5 and 3.6.
- Drop support for Python 2.6 and 3.2.
- 100% unit test coverage (including branches).
- Convert doctests to Sphinx documentation, including building docs
and running doctest snippets under ``tox``.
4.1.0 (2014-12-26)
------------------
- Add support for PyPy3.
- Add support for Python 3.4.
- Add support for testing on Travis.
4.0.0 (2013-02-05)
------------------
- Made tests pass on Python 3.2, 3.3 and PyPy.
- Add support for continuous integration using ``tox``.
3.4.6 (2009-09-15)
------------------
- Make tests pass on python26.
3.4.5 (2009-01-27)
------------------
- Move README.txt in the egg, so tests works with the released egg as well.
3.4.4 (2009-01-27)
------------------
- Fix ReST in README.txt, fix broken tests with recent zope.testing.
3.4.3 (2008-12-02)
------------------
- More documentation and tests.
3.4.2 (2007-10-02)
------------------
- Fix broken release.
3.4.1 (2007-10-02)
------------------
- Update package meta-data.
3.4.0 (2007-07-19)
------------------
- Initial Zope-independent release.
| zope.dottedname | /zope.dottedname-6.0.tar.gz/zope.dottedname-6.0/CHANGES.rst | CHANGES.rst |
``zope.dottedname``
===================
.. image:: https://img.shields.io/pypi/v/zope.dottedname.svg
:target: https://pypi.python.org/pypi/zope.dottedname/
:alt: Latest release
.. image:: https://github.com/zopefoundation/zope.dottedname/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/zope.dottedname/actions/workflows/tests.yml
.. image:: https://readthedocs.org/projects/zopedottedname/badge/?version=latest
:target: http://zopedottedname.readthedocs.org/en/latest/
:alt: Documentation Status
Resolve strings containing dotted names into the appropriate python object.
| zope.dottedname | /zope.dottedname-6.0.tar.gz/zope.dottedname-6.0/README.rst | README.rst |
Hacking on :mod:`zope.dottedname`
=================================
Getting the Code
################
The main repository for :mod:`zope.dottedname` is in the Zope Foundation
Github repository:
https://github.com/zopefoundation/zope.dottedname
You can get a read-only checkout from there:
.. code-block:: sh
$ git clone https://github.com/zopefoundation/zope.dottedname.git
or fork it and get a writeable checkout of your fork:
.. code-block:: sh
$ git clone [email protected]/jrandom/zope.dottedname.git
The project also mirrors the trunk from the Github repository as a
Bazaar branch on Launchpad:
https://code.launchpad.net/zope.dottedname
You can branch the trunk from there using Bazaar:
.. code-block:: sh
$ bzr branch lp:zope.dottedname
Working in a ``virtualenv``
###########################
Installing
----------
If you use the ``virtualenv`` package to create lightweight Python
development environments, you can run the tests using nothing more
than the ``python`` binary in a virtualenv. First, create a scratch
environment:
.. code-block:: sh
$ /path/to/virtualenv --no-site-packages /tmp/hack-zope.dottedname
Next, get this package registered as a "development egg" in the
environment:
.. code-block:: sh
$ /tmp/hack-zope.dottedname/bin/python setup.py develop
Running the tests
-----------------
Run the tests using the build-in ``setuptools`` testrunner:
.. code-block:: sh
$ /tmp/hack-zope.dottedname/bin/python setup.py test
running test
..........
----------------------------------------------------------------------
Ran 10 tests in 0.000s
OK
If you have the :mod:`nose` package installed in the virtualenv, you can
use its testrunner too:
.. code-block:: sh
$ /tmp/hack-zope.dottedname/bin/easy_install nose
...
$ /tmp/hack-zope.dottedname/bin/nosetests
..........
----------------------------------------------------------------------
Ran 10 tests in 0.000s
OK
If you have the :mod:`coverage` pacakge installed in the virtualenv,
you can see how well the tests cover the code:
.. code-block:: sh
$ /tmp/hack-zope.dottedname/bin/easy_install nose coverage
...
$ /tmp/hack-zope.dottedname/bin/nosetests --with coverage
running nosetests
...........
Name Stmts Miss Branch BrPart Cover Missing
------------------------------------------------------------------------
zope/dottedname.py 0 0 0 0 100%
zope/dottedname/example.py 0 0 0 0 100%
zope/dottedname/resolve.py 22 0 8 0 100%
------------------------------------------------------------------------
TOTAL 22 0 8 0 100%
----------------------------------------------------------------------
Ran 11 tests in 0.000s
OK
Building the documentation
--------------------------
:mod:`zope.dottedname` uses the nifty :mod:`Sphinx` documentation system
for building its docs. Using the same virtualenv you set up to run the
tests, you can build the docs:
.. code-block:: sh
$ /tmp/hack-zope.dottedname/bin/easy_install Sphinx
...
$ bin/sphinx-build -b html -d docs/_build/doctrees docs docs/_build/html
...
build succeeded.
You can also test the code snippets in the documentation:
.. code-block:: sh
$ bin/sphinx-build -b doctest -d docs/_build/doctrees docs docs/_build/doctest
...
Doctest summary
===============
12 tests
0 failures in tests
0 failures in setup code
build succeeded.
Testing of doctests in the sources finished, look at the \
results in _build/doctest/output.txt.
Using :mod:`zc.buildout`
########################
Setting up the buildout
-----------------------
:mod:`zope.dottedname` ships with its own :file:`buildout.cfg` file and
:file:`bootstrap.py` for setting up a development buildout:
.. code-block:: sh
$ /path/to/python2.6 bootstrap.py
...
Generated script '.../bin/buildout'
$ bin/buildout
Develop: '/home/jrandom/projects/Zope/zope.dottedname/.'
...
Generated script '.../bin/sphinx-quickstart'.
Generated script '.../bin/sphinx-build'.
Running the tests
-----------------
Run the tests:
.. code-block:: sh
$ bin/test --all
Running zope.testing.testrunner.layer.UnitTests tests:
Set up zope.testing.testrunner.layer.UnitTests in 0.000 seconds.
Ran 400 tests with 0 failures and 0 errors in 0.366 seconds.
Tearing down left over layers:
Tear down zope.testing.testrunner.layer.UnitTests in 0.000 seconds.
Using :mod:`tox`
################
Running Tests on Multiple Python Versions
-----------------------------------------
`tox <http://tox.testrun.org/latest/>`_ is a Python-based test automation
tool designed to run tests against multiple Python versions. It creates
a ``virtualenv`` for each configured version, installs the current package
and configured dependencies into each ``virtualenv``, and then runs the
configured commands.
:mod:`zope.dottedname` configures the following :mod:`tox` environments via
its ``tox.ini`` file:
- The ``py26``, ``py27``, ``py33``, ``py34``, and ``pypy`` environments
builds a ``virtualenv`` with the appropriate interpreter,
installs :mod:`zope.dottedname` and dependencies, and runs the tests
via ``python setup.py test -q``.
- The ``coverage`` environment builds a ``virtualenv`` with ``python2.6``,
installs :mod:`zope.dottedname`, installs
:mod:`nose` and :mod:`coverage`, and runs ``nosetests`` with statement
coverage.
- The ``docs`` environment builds a virtualenv with ``python2.6``, installs
:mod:`zope.dottedname`, installs ``Sphinx`` and
dependencies, and then builds the docs and exercises the doctest snippets.
This example requires that you have a working ``python2.6`` on your path,
as well as installing ``tox``:
.. code-block:: sh
$ tox -e py26
GLOB sdist-make: .../zope.interface/setup.py
py26 sdist-reinst: .../zope.interface/.tox/dist/zope.interface-4.0.2dev.zip
py26 runtests: commands[0]
...........
----------------------------------------------------------------------
Ran 10 tests in 0.152s
OK
___________________________________ summary ____________________________________
py26: commands succeeded
congratulations :)
Running ``tox`` with no arguments runs all the configured environments,
including building the docs and testing their snippets:
.. code-block:: sh
$ tox
GLOB sdist-make: .../zope.interface/setup.py
py26 sdist-reinst: .../zope.interface/.tox/dist/zope.interface-4.0.2dev.zip
py26 runtests: commands[0]
...
Doctest summary
===============
12 tests
0 failures in tests
0 failures in setup code
0 failures in cleanup code
build succeeded.
___________________________________ summary ____________________________________
py26: commands succeeded
py27: commands succeeded
py33: commands succeeded
py34: commands succeeded
pypy: commands succeeded
coverage: commands succeeded
docs: commands succeeded
congratulations :)
Contributing to :mod:`zope.dottedname`
######################################
Submitting a Bug Report
-----------------------
:mod:`zope.dottedname` tracks its bugs on Github:
https://github.com/zopefoundation/zope.dottedname/issues
Please submit bug reports and feature requests there.
Sharing Your Changes
--------------------
.. note::
Please ensure that all tests are passing before you submit your code.
If possible, your submission should include new tests for new features
or bug fixes, although it is possible that you may have tested your
new code by updating existing tests.
If have made a change you would like to share, the best route is to fork
the Githb repository, check out your fork, make your changes on a branch
in your fork, and push it. You can then submit a pull request from your
branch:
https://github.com/zopefoundation/zope.dottedname/pulls
If you branched the code from Launchpad using Bazaar, you have another
option: you can "push" your branch to Launchpad:
.. code-block:: sh
$ bzr push lp:~jrandom/zope.dottedname/cool_feature
After pushing your branch, you can link it to a bug report on Launchpad,
or request that the maintainers merge your branch using the Launchpad
"merge request" feature.
| zope.dottedname | /zope.dottedname-6.0.tar.gz/zope.dottedname-6.0/docs/hacking.rst | hacking.rst |
Dotted Name Resolution
======================
:mod:`zope.dottedname` provides one function,
:func:`~zope.dottedname.resolve.resolve`, that resolves strings containing
dotted names into the appropriate Python object.
Dotted names are resolved by importing modules and by getting
attributes from imported modules. Names may be relative, provided the
module they are relative to is supplied.
Here are some examples of importing absolute names:
.. doctest::
>>> from zope.dottedname.resolve import resolve
>>> resolve('unittest')
<module 'unittest' from '...'>
>>> resolve('datetime.datetime')(2015, 2, 2, 18, 59, 27)
datetime.datetime(2015, 2, 2, 18, 59, 27)
>>> resolve('os.path.basename')
<function basename at ...>
>>> resolve('non existent module')
Traceback (most recent call last):
...
ModuleNotFoundError: No module named non existent module
>>> resolve('__doc__')
Traceback (most recent call last):
...
ModuleNotFoundError: No module named __doc__
>>> resolve('logging.foo')
Traceback (most recent call last):
...
ModuleNotFoundError: No module named ...foo
>>> resolve('os.path.split').__name__
'split'
Here are some examples of importing relative names:
.. doctest::
>>> resolve('.split', 'os.path')
<function split at ...>
>>> resolve('..system', 'os.path')
<built-in function system>
>>> resolve('...datetime', 'os.path')
<module 'datetime' ...>
NB: When relative names are imported, a module the name is relative to
**must** be supplied:
.. doctest::
>>> resolve('.split').__name__
Traceback (most recent call last):
...
ValueError: relative name without base module
| zope.dottedname | /zope.dottedname-6.0.tar.gz/zope.dottedname-6.0/docs/narrative.rst | narrative.rst |
"""Support information for qualified Dublin Core Metadata.
"""
from zope.dublincore import dcsv
# useful namespace URIs
DC_NS = "http://purl.org/dc/elements/1.1/"
DCTERMS_NS = "http://purl.org/dc/terms/"
XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
W3CDTF = "W3CDTF"
def splitEncoding(name):
if "." not in name:
return name, None
parts = name.split(".")
if parts[-1] in encodings:
if len(parts) == 2:
return parts
else:
return ".".join(parts[:-1]), parts[-1]
else:
return name, None
# The type validator function must raise an exception if the value
# passed isn't valid for the type being check, other just return.
_dcmitypes = {}
for x in ("Collection Dataset Event Image InteractiveResource"
" Service Software Sound Text PhysicalObject").split():
_dcmitypes[x.lower()] = x
del x
def check_dcmitype(value):
if value.lower() not in _dcmitypes:
raise ValueError("%r not a valid DCMIType")
def check_imt(value):
pass
def check_iso639_2(value):
pass
def check_rfc1766(value):
pass
def check_uri(value):
pass
def check_point(value):
pass
def check_iso3166(value):
pass
def check_box(value):
pass
def check_tgn(value):
pass
_period_fields = "name start end scheme".split()
def check_period(value):
# checks a Period in DCSV format; see:
# http://dublincore.org/documents/dcmi-period/
items = dcsv.decode(value)
d = dcsv.createMapping(items)
for k in d:
if k not in _period_fields:
raise ValueError("unknown field label %r" % k)
if d.get("scheme", W3CDTF).upper() == W3CDTF:
if "start" in d:
check_w3cdtf(d["start"])
if "end" in d:
check_w3cdtf(d["end"])
def check_w3cdtf(value):
pass
def check_rfc3066(value):
pass
encodings = {
# name --> (allowed for, validator|None),
"LCSH": (("Subject",), None),
"MESH": (("Subject",), None),
"DDC": (("Subject",), None),
"LCC": (("Subject",), None),
"UDC": (("Subject",), None),
"DCMIType": (("Type",), check_dcmitype),
"IMT": (("Format",), check_imt),
"ISO639-2": (("Language",), check_iso639_2),
"RFC1766": (("Language",), check_rfc1766),
"URI": (("Identifier", "Relation", "Source",), check_uri),
"Point": (("Coverage.Spatial",), check_point),
"ISO3166": (("Coverage.Spatial",), check_iso3166),
"Box": (("Coverage.Spatial",), check_box),
"TGN": (("Coverage.Spatial",), check_tgn),
"Period": (("Coverage.Temporal",), check_period),
W3CDTF: (("Coverage.Temporal", "Date",), check_w3cdtf),
"RFC3066": (("Language",), check_rfc3066),
}
name_to_element = {
# unqualified DCMES 1.1
"Title": ("dc:title", ""),
"Creator": ("dc:creator", ""),
"Subject": ("dc:subject", ""),
"Description": ("dc:description", ""),
"Publisher": ("dc:publisher", ""),
"Contributor": ("dc:contributor", ""),
"Date": ("dc:date", "dcterms:" + W3CDTF),
"Type": ("dc:type", ""),
"Format": ("dc:format", ""),
"Identifier": ("dc:identifier", ""),
"Source": ("dc:source", ""),
"Language": ("dc:language", ""),
"Relation": ("dc:relation", ""),
"Coverage": ("dc:coverage", ""),
"Rights": ("dc:rights", ""),
# qualified DCMES 1.1 (directly handled by Zope)
"Date.Created": ("dcterms:created", "dcterms:" + W3CDTF),
"Date.Modified": ("dcterms:modified", "dcterms:" + W3CDTF),
# qualified DCMES 1.1 (not used by Zope)
"Audience": ("dcterms:audience", ""),
"Audience.Education Level": ("dcterms:educationLevel", ""),
"Audience.Mediator": ("dcterms:mediator", ""),
"Coverage.Spatial": ("dcterms:spatial", ""),
"Coverage.Temporal": ("dcterms:temporal", ""),
"Date.Accepted": ("dcterms:accepted", "dcterms:" + W3CDTF),
"Date.Available": ("dcterms:available", "dcterms:" + W3CDTF),
"Date.Copyrighted": ("dcterms:copyrighted", "dcterms:" + W3CDTF),
"Date.Issued": ("dcterms:issued", "dcterms:" + W3CDTF),
"Date.Submitted": ("dcterms:submitted", "dcterms:" + W3CDTF),
"Date.Valid": ("dcterms:valid", "dcterms:" + W3CDTF),
"Description.Abstract": ("dcterms:abstract", ""),
"Description.Table Of Contents": ("dcterms:tableOfContents", ""),
"Format": ("dc:format", ""),
"Format.Extent": ("dcterms:extent", ""),
"Format.Medium": ("dcterms:medium", ""),
"Identifier.Bibliographic Citation": ("dcterms:bibliographicCitation", ""),
"Relation.Is Version Of": ("dcterms:isVersionOf", ""),
"Relation.Has Version": ("dcterms:hasVersion", ""),
"Relation.Is Replaced By": ("dcterms:isReplacedBy", ""),
"Relation.Replaces": ("dcterms:replaces", ""),
"Relation.Is Required By": ("dcterms:isRequiredBy", ""),
"Relation.Requires": ("dcterms:requires", ""),
"Relation.Is Part Of": ("dcterms:isPartOf", ""),
"Relation.Has Part": ("dcterms:hasPart", ""),
"Relation.Is Referenced By": ("dcterms:isReferencedBy", ""),
"Relation.References": ("dcterms:references", ""),
"Relation.Is Format Of": ("dcterms:isFormatOf", ""),
"Relation.Has Format": ("dcterms:hasFormat", ""),
"Relation.Conforms To": ("dcterms:conformsTo", ""),
"Rights.Access Rights": ("dcterms:accessRights", ""),
"Title.Alternative": ("dcterms:alternative", ""),
}
_prefix_to_ns = {
"dc": DC_NS,
"dcterms": DCTERMS_NS,
# "xsi": XSI_NS, dont' use this for element names, only attrs
}
element_to_name = {}
for name, (qname, attrs) in name_to_element.items():
prefix, localname = qname.split(":")
elem_name = _prefix_to_ns[prefix], localname
element_to_name[elem_name] = name
name_to_element[name] = (elem_name, attrs) | zope.dublincore | /zope.dublincore-5.0-py3-none-any.whl/zope/dublincore/dcterms.py | dcterms.py |
"""Dublin Core interfaces
"""
from zope.interface import Interface
from zope.schema import Datetime
from zope.schema import Text
from zope.schema import TextLine
from zope.schema import Tuple
class IDublinCoreElementItem(Interface):
"""A qualified dublin core element"""
qualification = TextLine(
title="Qualification",
description="The element qualification"
)
value = Text(
title="Value",
description="The element value",
)
class IGeneralDublinCore(Interface):
"""Dublin-core data access interface
The Dublin Core, http://dublincore.org/, is a meta data standard
that specifies a set of standard data elements. It provides
flexibility of interpretation of these elements by providing for
element qualifiers that specialize the meaning of specific
elements. For example, a date element might have a qualifier, like
"creation" to indicate that the date is a creation date. In
addition, any element may be repeated. For some elements, like
subject, and contributor, this is obviously necessary, but for
other elements, like title and description, allowing repetitions
is not very useful and adds complexity.
This interface provides methods for retrieving data in full
generality, to be compliant with the Dublin Core standard.
Other interfaces will provide more convenient access methods
tailored to specific element usage patterns.
"""
def getQualifiedTitles():
"""Return a sequence of Title IDublinCoreElementItem."""
def getQualifiedCreators():
"""Return a sequence of Creator IDublinCoreElementItem."""
def getQualifiedSubjects():
"""Return a sequence of Subject IDublinCoreElementItem."""
def getQualifiedDescriptions():
"""Return a sequence of Description IDublinCoreElementItem."""
def getQualifiedPublishers():
"""Return a sequence of Publisher IDublinCoreElementItem."""
def getQualifiedContributors():
"""Return a sequence of Contributor IDublinCoreElementItem."""
def getQualifiedDates():
"""Return a sequence of Date IDublinCoreElementItem."""
def getQualifiedTypes():
"""Return a sequence of Type IDublinCoreElementItem."""
def getQualifiedFormats():
"""Return a sequence of Format IDublinCoreElementItem."""
def getQualifiedIdentifiers():
"""Return a sequence of Identifier IDublinCoreElementItem."""
def getQualifiedSources():
"""Return a sequence of Source IDublinCoreElementItem."""
def getQualifiedLanguages():
"""Return a sequence of Language IDublinCoreElementItem."""
def getQualifiedRelations():
"""Return a sequence of Relation IDublinCoreElementItem."""
def getQualifiedCoverages():
"""Return a sequence of Coverage IDublinCoreElementItem."""
def getQualifiedRights():
"""Return a sequence of Rights IDublinCoreElementItem."""
class IWritableGeneralDublinCore(Interface):
"""Provide write access to dublin core data
This interface augments `IStandardDublinCore` with methods for
writing elements.
"""
def setQualifiedTitles(qualified_titles):
"""Set the qualified Title elements.
The argument must be a sequence of `IDublinCoreElementItem`.
"""
def setQualifiedCreators(qualified_creators):
"""Set the qualified Creator elements.
The argument must be a sequence of Creator `IDublinCoreElementItem`.
"""
def setQualifiedSubjects(qualified_subjects):
"""Set the qualified Subjects elements.
The argument must be a sequence of Subject `IDublinCoreElementItem`.
"""
def setQualifiedDescriptions(qualified_descriptions):
"""Set the qualified Descriptions elements.
The argument must be a sequence of Description
`IDublinCoreElementItem`.
"""
def setQualifiedPublishers(qualified_publishers):
"""Set the qualified Publishers elements.
The argument must be a sequence of Publisher `IDublinCoreElementItem`.
"""
def setQualifiedContributors(qualified_contributors):
"""Set the qualified Contributors elements.
The argument must be a sequence of Contributor
`IDublinCoreElementItem`.
"""
def setQualifiedDates(qualified_dates):
"""Set the qualified Dates elements.
The argument must be a sequence of Date `IDublinCoreElementItem`.
"""
def setQualifiedTypes(qualified_types):
"""Set the qualified Types elements.
The argument must be a sequence of Type `IDublinCoreElementItem`.
"""
def setQualifiedFormats(qualified_formats):
"""Set the qualified Formats elements.
The argument must be a sequence of Format `IDublinCoreElementItem`.
"""
def setQualifiedIdentifiers(qualified_identifiers):
"""Set the qualified Identifiers elements.
The argument must be a sequence of Identifier `IDublinCoreElementItem`.
"""
def setQualifiedSources(qualified_sources):
"""Set the qualified Sources elements.
The argument must be a sequence of Source `IDublinCoreElementItem`.
"""
def setQualifiedLanguages(qualified_languages):
"""Set the qualified Languages elements.
The argument must be a sequence of Language `IDublinCoreElementItem`.
"""
def setQualifiedRelations(qualified_relations):
"""Set the qualified Relations elements.
The argument must be a sequence of Relation `IDublinCoreElementItem`.
"""
def setQualifiedCoverages(qualified_coverages):
"""Set the qualified Coverages elements.
The argument must be a sequence of Coverage `IDublinCoreElementItem`.
"""
def setQualifiedRights(qualified_rights):
"""Set the qualified Rights elements.
The argument must be a sequence of Rights `IDublinCoreElementItem`.
"""
class IDCDescriptiveProperties(Interface):
"""Basic descriptive meta-data properties"""
title = TextLine(
title='Title',
description="The first unqualified Dublin Core 'Title' element value."
)
description = Text(
title='Description',
description=(
"The first unqualified Dublin Core 'Description' element value.")
)
class IDCTimes(Interface):
"""Time properties"""
created = Datetime(
title='Creation Date',
description="The date and time that an object is created."
"\nThis is normally set automatically."
)
modified = Datetime(
title='Modification Date',
description="The date and time that the object was last modified in a"
" meaningful way."
)
class IDCPublishing(Interface):
"""Publishing properties"""
effective = Datetime(
title='Effective Date',
description="The date and time that an object should be published."
)
expires = Datetime(
title='Expiration Date',
description="The date and time that the object should become"
" unpublished."
)
class IDCExtended(Interface):
"""Extended properties
This is a mixed bag of properties we want but that we probably haven't
quite figured out yet.
"""
creators = Tuple(
title='Creators',
description="The unqualified Dublin Core 'Creator' element values",
value_type=TextLine(),
)
subjects = Tuple(
title='Subjects',
description="The unqualified Dublin Core 'Subject' element values",
value_type=TextLine(),
)
publisher = Text(
title='Publisher',
description="The first unqualified Dublin Core 'Publisher' element"
" value.",
)
contributors = Tuple(
title='Contributors',
description="The unqualified Dublin Core 'Contributor' element"
" values",
value_type=TextLine(),
)
class ICMFDublinCore(Interface):
"""This interface duplicates the CMF dublin core interface."""
def Title():
"""Return the resource title.
The first unqualified Dublin Core `Title` element value is
returned as a unicode string if an unqualified element is
defined, otherwise, an empty unicode string is returned.
"""
def Creator():
"""Return the resource creators.
Return the full name(s) of the author(s) of the content
object.
The unqualified Dublin Core `Creator` element values are
returned as a sequence of unicode strings.
"""
def Subject():
"""Return the resource subjects.
The unqualified Dublin Core `Subject` element values are
returned as a sequence of unicode strings.
"""
def Description():
"""Return the resource description
Return a natural language description of this object.
The first unqualified Dublin Core `Description` element value is
returned as a unicode string if an unqualified element is
defined, otherwise, an empty unicode string is returned.
"""
def Publisher():
"""Dublin Core element - resource publisher
Return full formal name of the entity or person responsible
for publishing the resource.
The first unqualified Dublin Core `Publisher` element value is
returned as a unicode string if an unqualified element is
defined, otherwise, an empty unicode string is returned.
"""
def Contributors():
"""Return the resource contributors
Return any additional collaborators.
The unqualified Dublin Core `Contributor` element values are
returned as a sequence of unicode strings.
"""
def Date():
"""Return the default date
The first unqualified Dublin Core `Date` element value is
returned as a unicode string if an unqualified element is
defined, otherwise, an empty unicode string is returned. The
string is formatted 'YYYY-MM-DD H24:MN:SS TZ'.
"""
def CreationDate():
"""Return the creation date.
The value of the first Dublin Core `Date` element qualified by
'creation' is returned as a unicode string if a qualified
element is defined, otherwise, an empty unicode string is
returned. The string is formatted 'YYYY-MM-DD H24:MN:SS TZ'.
"""
def EffectiveDate():
"""Return the effective date
The value of the first Dublin Core `Date` element qualified by
'effective' is returned as a unicode string if a qualified
element is defined, otherwise, an empty unicode string is
returned. The string is formatted 'YYYY-MM-DD H24:MN:SS TZ'.
"""
def ExpirationDate():
"""Date resource expires.
The value of the first Dublin Core `Date` element qualified by
'expiration' is returned as a unicode string if a qualified
element is defined, otherwise, an empty unicode string is
returned. The string is formatted 'YYYY-MM-DD H24:MN:SS TZ'.
"""
def ModificationDate():
"""Date resource last modified.
The value of the first Dublin Core `Date` element qualified by
'modification' is returned as a unicode string if a qualified
element is defined, otherwise, an empty unicode string is
returned. The string is formatted 'YYYY-MM-DD H24:MN:SS TZ'.
"""
def Type():
"""Return the resource type
Return a human-readable type name for the resource.
The first unqualified Dublin Core `Type` element value is
returned as a unicode string if an unqualified element is
defined, otherwise, an empty unicode string is returned.
"""
def Format():
"""Return the resource format.
Return the resource's MIME type (e.g., 'text/html',
'image/png', etc.).
The first unqualified Dublin Core `Format` element value is
returned as a unicode string if an unqualified element is
defined, otherwise, an empty unicode string is returned.
"""
def Identifier():
"""Return the URL of the resource.
This value is computed. It is included in the output of
qualifiedIdentifiers with the qualification 'url'.
"""
def Language():
"""Return the resource language.
Return the RFC language code (e.g., 'en-US', 'pt-BR')
for the resource.
The first unqualified Dublin Core `Language` element value is
returned as a unicode string if an unqualified element is
defined, otherwise, an empty unicode string is returned.
"""
def Rights():
"""Return the resource rights.
Return a string describing the intellectual property status,
if any, of the resource. for the resource.
The first unqualified Dublin Core `Rights` element value is
returned as a unicode string if an unqualified element is
defined, otherwise, an empty unicode string is returned.
"""
class IZopeDublinCore(
IGeneralDublinCore,
ICMFDublinCore,
IDCDescriptiveProperties,
IDCTimes,
IDCPublishing,
IDCExtended,
):
"""Zope Dublin Core properties"""
class IWriteZopeDublinCore(
IZopeDublinCore,
IWritableGeneralDublinCore,
):
"""Zope Dublin Core properties with generate update support""" | zope.dublincore | /zope.dublincore-5.0-py3-none-any.whl/zope/dublincore/interfaces.py | interfaces.py |
"""Zope's Dublin Core Implementation
"""
from datetime import datetime
from zope.datetime import parseDatetimetz
from zope.interface import implementer
from zope.dublincore.interfaces import IZopeDublinCore
class SimpleProperty:
def __init__(self, name):
self.__name__ = name
class ScalarProperty(SimpleProperty):
def __get__(self, inst, klass):
if inst is None:
return self
data = inst._mapping.get(self.__name__, ())
if data:
return data[0]
else:
return ''
def __set__(self, inst, value):
if not isinstance(value, str):
raise TypeError("Element must be str")
dict = inst._mapping
__name__ = self.__name__
inst._changed()
dict[__name__] = (value, ) + dict.get(__name__, ())[1:]
def _scalar_get(inst, name):
data = inst._mapping.get(name, ())
if data:
return data[0]
else:
return ''
class DateProperty(ScalarProperty):
def __get__(self, inst, klass):
if inst is None:
return self
data = inst._mapping.get(self.__name__, ())
if data:
return parseDatetimetz(data[0])
else:
return None
def __set__(self, inst, value):
if not isinstance(value, datetime):
raise TypeError("Element must be %s", datetime)
value = value.isoformat('T')
if isinstance(value, bytes):
value = value.decode('ascii')
super().__set__(inst, value)
class SequenceProperty(SimpleProperty):
def __get__(self, inst, klass):
if inst is None:
return self
return inst._mapping.get(self.__name__, ())
def __set__(self, inst, value):
value = tuple(value)
for v in value:
if not isinstance(v, str):
raise TypeError("Elements must be str")
inst._changed()
inst._mapping[self.__name__] = value
@implementer(IZopeDublinCore)
class ZopeDublinCore:
"""Zope Dublin Core Mixin
Subclasses should define either `_changed()` or `_p_changed`.
Just mix with `Persistence` to get a persistent version.
"""
def __init__(self, mapping=None):
if mapping is None:
mapping = {}
self._mapping = mapping
def _changed(self):
self._p_changed = True
title = ScalarProperty('Title')
def Title(self):
"""See `IZopeDublinCore`"""
return self.title
creators = SequenceProperty('Creator')
def Creator(self):
"""See `IZopeDublinCore`"""
return self.creators
subjects = SequenceProperty('Subject')
def Subject(self):
"""See `IZopeDublinCore`"""
return self.subjects
description = ScalarProperty('Description')
def Description(self):
"""See `IZopeDublinCore`"""
return self.description
publisher = ScalarProperty('Publisher')
def Publisher(self):
"""See IZopeDublinCore"""
return self.publisher
contributors = SequenceProperty('Contributor')
def Contributors(self):
"""See `IZopeDublinCore`"""
return self.contributors
def Date(self):
"""See IZopeDublinCore"""
return _scalar_get(self, 'Date')
created = DateProperty('Date.Created')
def CreationDate(self):
"""See `IZopeDublinCore`"""
return _scalar_get(self, 'Date.Created')
effective = DateProperty('Date.Effective')
def EffectiveDate(self):
"""See `IZopeDublinCore`"""
return _scalar_get(self, 'Date.Effective')
expires = DateProperty('Date.Expires')
def ExpirationDate(self):
"""See `IZopeDublinCore`"""
return _scalar_get(self, 'Date.Expires')
modified = DateProperty('Date.Modified')
def ModificationDate(self):
"""See `IZopeDublinCore`"""
return _scalar_get(self, 'Date.Modified')
type = ScalarProperty('Type')
def Type(self):
"""See `IZopeDublinCore`"""
return self.type
format = ScalarProperty('Format')
def Format(self):
"""See `IZopeDublinCore`"""
return self.format
identifier = ScalarProperty('Identifier')
def Identifier(self):
"""See `IZopeDublinCore`"""
return self.identifier
language = ScalarProperty('Language')
def Language(self):
"""See `IZopeDublinCore`"""
return self.language
rights = ScalarProperty('Rights')
def Rights(self):
"""See `IZopeDublinCore`"""
return self.rights
def setQualifiedTitles(self, qualified_titles):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Title', qualified_titles)
def setQualifiedCreators(self, qualified_creators):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Creator', qualified_creators)
def setQualifiedSubjects(self, qualified_subjects):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Subject', qualified_subjects)
def setQualifiedDescriptions(self, qualified_descriptions):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Description', qualified_descriptions)
def setQualifiedPublishers(self, qualified_publishers):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Publisher', qualified_publishers)
def setQualifiedContributors(self, qualified_contributors):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Contributor', qualified_contributors)
def setQualifiedDates(self, qualified_dates):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Date', qualified_dates)
def setQualifiedTypes(self, qualified_types):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Type', qualified_types)
def setQualifiedFormats(self, qualified_formats):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Format', qualified_formats)
def setQualifiedIdentifiers(self, qualified_identifiers):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Identifier', qualified_identifiers)
def setQualifiedSources(self, qualified_sources):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Source', qualified_sources)
def setQualifiedLanguages(self, qualified_languages):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Language', qualified_languages)
def setQualifiedRelations(self, qualified_relations):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Relation', qualified_relations)
def setQualifiedCoverages(self, qualified_coverages):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Coverage', qualified_coverages)
def setQualifiedRights(self, qualified_rights):
"""See `IWritableDublinCore`"""
return _set_qualified(self, 'Rights', qualified_rights)
def getQualifiedTitles(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Title')
def getQualifiedCreators(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Creator')
def getQualifiedSubjects(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Subject')
def getQualifiedDescriptions(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Description')
def getQualifiedPublishers(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Publisher')
def getQualifiedContributors(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Contributor')
def getQualifiedDates(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Date')
def getQualifiedTypes(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Type')
def getQualifiedFormats(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Format')
def getQualifiedIdentifiers(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Identifier')
def getQualifiedSources(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Source')
def getQualifiedLanguages(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Language')
def getQualifiedRelations(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Relation')
def getQualifiedCoverages(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Coverage')
def getQualifiedRights(self):
"""See `IStandardDublinCore`"""
return _get_qualified(self, 'Rights')
def _set_qualified(self, name, qvalue):
data = {}
dict = self._mapping
for qualification, value in qvalue:
data[qualification] = data.get(qualification, ()) + (value, )
self._changed()
for qualification, values in data.items():
qname = qualification and (name + '.' + qualification) or name
dict[qname] = values
def _get_qualified(self, name):
result = []
for aname, avalue in self._mapping.items():
if aname == name:
qualification = ''
for value in avalue:
result.append((qualification, value))
elif aname.startswith(name):
qualification = aname[len(name) + 1:]
for value in avalue:
result.append((qualification, value))
return tuple(result)
__doc__ = ZopeDublinCore.__doc__ + __doc__ | zope.dublincore | /zope.dublincore-5.0-py3-none-any.whl/zope/dublincore/zopedublincore.py | zopedublincore.py |
"""Dublin Core Annotatable Adapter
"""
from persistent.dict import PersistentDict
from zope.annotation.interfaces import IAnnotatable
from zope.annotation.interfaces import IAnnotations
from zope.component import adapter
from zope.interface import implementer
from zope.location import Location
from zope.dublincore.interfaces import IWriteZopeDublinCore
from zope.dublincore.zopedublincore import DateProperty
from zope.dublincore.zopedublincore import ScalarProperty
from zope.dublincore.zopedublincore import ZopeDublinCore
DCkey = "zope.app.dublincore.ZopeDublinCore"
@implementer(IWriteZopeDublinCore)
@adapter(IAnnotatable)
class ZDCAnnotatableAdapter(ZopeDublinCore, Location):
"""Adapt annotatable objects to Zope Dublin Core."""
annotations = None
def __init__(self, context):
annotations = IAnnotations(context)
dcdata = annotations.get(DCkey)
if dcdata is None:
self.annotations = annotations
dcdata = ZDCAnnotationData()
super().__init__(dcdata)
def _changed(self):
if self.annotations is not None:
self.annotations[DCkey] = self._mapping
self.annotations = None
class ZDCAnnotationData(PersistentDict):
"""Data for a Dublin Core annotation.
A specialized class is used to allow an alternate fssync
serialization to be registered. See the
zope.dublincore.fssync package.
"""
# Hybrid adapters.
#
# Adapter factories created using this support the Dublin Core using a
# mixture of annotations and data on the context object.
class DirectProperty:
def __init__(self, name, attrname):
self.__name__ = name
self.__attrname = attrname
def __get__(self, inst, klass):
if inst is None:
return self
context = inst._ZDCPartialAnnotatableAdapter__context
return getattr(context, self.__attrname, "")
def __set__(self, inst, value):
if not isinstance(value, str):
raise TypeError("Element must be str")
context = inst._ZDCPartialAnnotatableAdapter__context
oldvalue = getattr(context, self.__attrname, None)
if oldvalue != value:
setattr(context, self.__attrname, value)
def partialAnnotatableAdapterFactory(direct_fields):
if not direct_fields:
raise ValueError("only use partialAnnotatableAdapterFactory()"
" if at least one DC field is implemented directly")
fieldmap = {}
try:
# is direct_fields a sequence or a mapping?
direct_fields[0]
except KeyError:
# direct_fields: { dc_name: attribute_name }
fieldmap.update(direct_fields)
else:
for attrname in direct_fields:
fieldmap[attrname] = attrname
class ZDCPartialAnnotatableAdapter(ZDCAnnotatableAdapter):
def __init__(self, context):
self.__context = context
# can't use super() since this isn't a globally available class
ZDCAnnotatableAdapter.__init__(self, context)
for dcname, attrname in fieldmap.items():
oldprop = ZopeDublinCore.__dict__.get(dcname)
if oldprop is None:
raise ValueError("%r is not a valid DC field" % dcname)
if (isinstance(oldprop, DateProperty)
or not isinstance(oldprop, ScalarProperty)):
raise ValueError("%r is not a supported DC field" % dcname)
prop = DirectProperty(dcname, attrname)
setattr(ZDCPartialAnnotatableAdapter, dcname, prop)
return ZDCPartialAnnotatableAdapter | zope.dublincore | /zope.dublincore-5.0-py3-none-any.whl/zope/dublincore/annotatableadapter.py | annotatableadapter.py |
"""Dublin Core XML data parser and writer
"""
import xml.sax
import xml.sax.handler
from io import StringIO
from xml.sax.saxutils import escape
from xml.sax.saxutils import quoteattr
from zope.dublincore import dcterms
XSI_TYPE = (dcterms.XSI_NS, "type")
dublin_core_namespaces = dcterms.DC_NS, dcterms.DCTERMS_NS
DEFAULT_NAMESPACE_PREFIXES = {
# uri: prefix,
dcterms.DC_NS: "dc",
dcterms.DCTERMS_NS: "dcterms",
dcterms.XSI_NS: "xsi",
}
class NamespaceTracker:
def __init__(self, mapping=None):
self._mapping = {}
self._used = {}
if mapping:
self._mapping.update(mapping)
self._counter = 0
def encode(self, xxx_todo_changeme):
(uri, localname) = xxx_todo_changeme
if not uri:
return localname
if uri not in self._mapping:
self._counter += 1
prefix = "ns%d" % self._counter
self._mapping[uri] = prefix
self._used[prefix] = uri
else:
prefix = self._mapping[uri]
if prefix not in self._used:
self._used[prefix] = uri
if prefix:
return "{}:{}".format(prefix, localname)
else:
return localname
def getPrefixMappings(self):
return self._used.items()
def dumpString(mapping):
sio = StringIO()
nsmap = NamespaceTracker(DEFAULT_NAMESPACE_PREFIXES)
items = sorted(mapping.items())
prev = None
for name, values in items:
name, type = dcterms.splitEncoding(name)
group = name.split(".", 1)[0]
if prev != group:
sio.write("\n")
prev = group
if name in dcterms.name_to_element:
element, t = dcterms.name_to_element[name]
qname = nsmap.encode(element)
if not type:
type = t
if type:
type = " {}={}".format(nsmap.encode((dcterms.XSI_NS, "type")),
quoteattr(type))
for value in values:
sio.write(" <%s%s>\n %s\n </%s>\n"
% (qname, type, _encode_string(value), qname))
else:
raise RuntimeError("could not serialize %r metadata element"
% name)
content = sio.getvalue()
sio = StringIO()
sio.write("<?xml version='1.0' encoding='utf-8'?>\n"
"<metadata")
for prefix, uri in nsmap.getPrefixMappings():
sio.write("\n xmlns:{}={}".format(prefix, quoteattr(uri)))
sio.write(">\n")
sio.write(content)
sio.write("</metadata>\n")
return sio.getvalue()
try:
unicode
except NameError:
_encode_string = escape
else:
def _encode_string(s):
if isinstance(s, unicode): # noqa: F821
s = s.encode('utf-8')
return escape(s)
def parse(source, error_handler=None):
parser, ch = _setup_parser(error_handler)
parser.parse(source)
return ch.mapping
def parseString(text, error_handler=None):
parser, ch = _setup_parser(error_handler)
parser.feed(text)
parser.close()
return ch.mapping
def _setup_parser(error_handler):
parser = xml.sax.make_parser()
ch = DublinCoreHandler()
parser.setFeature(xml.sax.handler.feature_namespaces, True)
parser.setContentHandler(ch)
if error_handler is not None:
parser.setErrorHandler(error_handler)
return parser, ch
class PrefixManager:
# We don't use this other than in the DublinCoreHandler, but it's
# entirely general so we'll separate it out for now.
"""General handler for namespace prefixes.
This should be used as a mix-in when creating a ContentHandler.
"""
__prefix_map = None
def startPrefixMapping(self, prefix, uri):
if self.__prefix_map is None:
self.__prefix_map = {}
pm = self.__prefix_map
pm.setdefault(prefix, []).append(uri)
def endPrefixMapping(self, prefix):
pm = self.__prefix_map
uris = pm[prefix]
del uris[-1]
if not uris:
del pm[prefix]
def get_uri(self, prefix):
pm = self.__prefix_map
if pm is None:
return None
if prefix in pm:
return pm[prefix][-1]
else:
return None
class DublinCoreHandler(PrefixManager, xml.sax.handler.ContentHandler):
def startDocument(self):
self.mapping = {}
self.stack = []
def get_dc_container(self):
name = None
for (uri, localname), dcelem, validator in self.stack:
if uri in dublin_core_namespaces:
name = uri, localname
if name in dcterms.element_to_name:
# dcelem contains type info, so go back to the mapping
return dcterms.element_to_name[name]
else:
return None
def startElementNS(self, name, qname, attrs):
self.buffer = ""
# TODO: need convert element to metadata element name
dcelem = validator = None
if name in dcterms.element_to_name:
dcelem = dcterms.element_to_name[name]
type = attrs.get(XSI_TYPE)
if type:
if not dcelem:
raise ValueError(
"data type specified for unknown metadata element: %s"
% qname)
if ":" in type:
prefix, t = type.split(":", 1)
ns = self.get_uri(prefix)
if ns != dcterms.DCTERMS_NS:
raise ValueError("unknown data type namespace: %s" % t)
type = t
if type not in dcterms.encodings:
raise ValueError("unknown data type: %r" % type)
allowed_in, validator = dcterms.encodings[type]
dcelem_split = dcelem.split(".")
for elem in allowed_in:
elem_split = elem.split(".")
if dcelem_split[:len(elem_split)] == elem_split:
break
else:
raise ValueError("%s values are not allowed for %r"
% (type, dcelem))
dcelem = "{}.{}".format(dcelem, type)
if dcelem:
cont = self.get_dc_container()
if cont and cont != dcelem:
prefix = cont + "."
if not dcelem.startswith(prefix):
raise ValueError("%s is not a valid refinement for %s"
% (dcelem, cont))
self.stack.append((name, dcelem, validator))
def endElementNS(self, name, qname):
startname, dcelem, validator = self.stack.pop()
assert startname == name
if self.buffer is None:
return
data = self.buffer.strip()
self.buffer = None
if not dcelem:
return
if validator is not None:
validator(data)
if dcelem in self.mapping:
self.mapping[dcelem] += (data,)
else:
self.mapping[dcelem] = (data,)
def characters(self, data):
if self.buffer is not None:
self.buffer += data | zope.dublincore | /zope.dublincore-5.0-py3-none-any.whl/zope/dublincore/xmlmetadata.py | xmlmetadata.py |
"""Base DublinCore property adapter.
"""
from zope import schema
from zope.dublincore.interfaces import IZopeDublinCore
_marker = object()
class DCProperty:
"""Adapt to a dublin core property
Handles DC list properties as scalar property.
"""
def __init__(self, name):
self.__name = name
def __get__(self, inst, klass):
if inst is None:
return self
name = self.__name
inst = IZopeDublinCore(inst)
value = getattr(inst, name, _marker)
if value is _marker:
field = IZopeDublinCore[name].bind(inst)
value = getattr(field, 'default', _marker)
if value is _marker:
raise AttributeError(name)
if isinstance(value, (list, tuple)):
value = value[0]
return value
def __set__(self, inst, value):
name = self.__name
inst = IZopeDublinCore(inst)
field = IZopeDublinCore[name].bind(inst)
if isinstance(field, schema.List):
if isinstance(value, tuple):
value = list(value)
else:
value = [value]
elif isinstance(field, schema.Tuple):
if isinstance(value, list):
value = tuple(value)
else:
value = (value,)
field.validate(value)
if field.readonly and name in inst.__dict__:
raise ValueError(name, 'field is readonly')
setattr(inst, name, value)
def __getattr__(self, name):
return getattr(IZopeDublinCore[self.__name], name)
class DCListProperty(DCProperty):
"""Adapt to a dublin core list property
Returns the DC property unchanged.
"""
def __init__(self, name):
self.__name = name
def __get__(self, inst, klass):
if inst is None:
return self
name = self.__name
inst = IZopeDublinCore(inst)
value = getattr(inst, name, _marker)
if value is _marker:
field = IZopeDublinCore[name].bind(inst)
value = getattr(field, 'default', _marker)
if value is _marker:
raise AttributeError(name)
return value
def __set__(self, inst, value):
name = self.__name
inst = IZopeDublinCore(inst)
field = IZopeDublinCore[name].bind(inst)
if isinstance(field, schema.Tuple):
value = tuple(value)
field.validate(value)
if field.readonly and name in inst.__dict__:
raise ValueError(name, 'field is readonly')
setattr(inst, name, value) | zope.dublincore | /zope.dublincore-5.0-py3-none-any.whl/zope/dublincore/property.py | property.py |
import re
__all__ = "encode", "decode"
def encode(items):
L = []
for item in items:
if isinstance(item, str):
L.append(_encode_string(item, "values") + ";")
else:
k, v = item
if not isinstance(v, str):
raise TypeError("values must be strings; found %r" % v)
v = _encode_string(v, "values")
if k:
if not isinstance(k, str):
raise TypeError("labels must be strings; found %r" % k)
k = _encode_string(k, "labels")
s = "{}={};".format(k, v)
else:
s = v + ";"
L.append(s)
return " ".join(L)
def _encode_string(s, what):
if s.strip() != s:
raise ValueError("%s may not include leading or trailing spaces: %r"
% (what, s))
return s.replace("\\", r"\\").replace(";", r"\;").replace("=", r"\=")
def decode(text):
items = []
text = text.strip()
while text:
m = _find_interesting(text)
if m:
prefix, char = m.group(1, 2)
prefix = _decode_string(prefix).rstrip()
if char == ";":
items.append(('', prefix))
text = text[m.end():].lstrip()
continue
else: # char == "="
text = text[m.end():].lstrip()
# else we have a label
m = _find_value(text)
if m:
value = m.group(1)
text = text[m.end():].lstrip()
else:
value = text
text = ''
items.append((prefix, _decode_string(value)))
else:
items.append(('', _decode_string(text)))
break
return items
_prefix = r"((?:[^;\\=]|\\.)*)"
_find_interesting = re.compile(_prefix + "([;=])").match
_find_value = re.compile(_prefix + ";").match
def _decode_string(s):
if "\\" not in s:
return s.rstrip()
r = ""
while s:
c1 = s[0]
if c1 == "\\":
c2 = s[1:2]
if not c2:
return r + c1
r += c2
s = s[2:]
else:
r += c1
s = s[1:]
return r.rstrip()
def createMapping(items, allow_duplicates=False):
mapping = {}
for item in items:
if isinstance(item, str):
raise ValueError("can't create mapping with unlabelled data")
k, v = item
if not isinstance(k, str):
raise TypeError("labels must be strings; found %r" % k)
if not isinstance(v, str):
raise TypeError("values must be strings; found %r" % v)
if k in mapping:
if allow_duplicates:
mapping[k].append(v)
else:
raise ValueError("labels may not have more than one value")
else:
if allow_duplicates:
mapping[k] = [v]
else:
mapping[k] = v
return mapping | zope.dublincore | /zope.dublincore-5.0-py3-none-any.whl/zope/dublincore/dcsv.py | dcsv.py |
=========
Changes
=========
5.0 (2023-07-06)
================
- Add support for Python 3.11.
- Drop support for Python 2.7, 3.5, 3.6.
4.6 (2022-08-29)
================
- Add support for Python 3.8, 3.9, 3.10.
- Drop support for Python 3.4.
4.5.0 (2018-10-19)
==================
- Add support for Python 3.7.
4.4.0 (2017-07-22)
==================
- Drop support for Python 3.3.
- Add support for Python 3.6.
- 100% test coverage.
- Remove internal ``_compat`` module in favor of ``six``, which we
already had a dependency on.
- Stop decoding in ASCII (whatever the default codec is) in favor of UTF-8.
- Tighten the interface of
``ILocalErrorReportingUtility.setProperties``. Now
``ignored_exceptions`` is required to be str or byte objects.
Previously any object that could be converted into a text object via
the text constructor was accepted, but this encouraged passing class
objects, when in actuality we need the class *name*.
- Stop ignoring ``KeyboardInterrupt`` exceptions and other similar
``BaseException`` exceptions during the ``raising`` method.
4.3.0 (2016-07-07)
==================
- Add support for Python 3.5.
- Drop support for Python 2.6.
- bugfix: fix leak by converting ``request.URL`` to string in
``ErrorReportingUtility``
4.2.0 (2014-12-27)
==================
- Add support for PyPy and PyPy3.
- Add support for Python 3.4.
4.1.1 (2014-12-22)
==================
- Enable testing on Travis.
4.1.0 (2013-02-21)
==================
- Add compatibility with Python 3.3
4.0.0 (2012-12-10)
==================
- Replace deprecated ``zope.interface.implements`` usage with equivalent
``zope.interface.implementer`` decorator.
- Drop support for Python 2.4 and 2.5.
- Sort request items for presentation in the error reporting utility.
- Don't HTML-escape HTML tracebacks twice.
3.7.4 (2012-02-01)
==================
- Add explicit tests for escaping introduced in 3.7.3.
- Handing names of classes those string representation cannot
be determined as untrusted input thus escaping them in error reports.
- Fix tests on Python 2.4 and 2.5.
3.7.3 (2012-01-17)
==================
- Escape untrusted input before constructing HTML for error reporting.
3.7.2 (2010-10-30)
==================
- Set ``copy_to_zlog`` by default to 1/True.
Having it turned off is a small problem, because fatal (startup) errors
will not get logged anywhere.
3.7.1 (2010-09-25)
==================
- Add test extra to declare test dependency on ``zope.testing``.
3.7.0 (2009-09-29)
==================
- Clean up dependencies. Droped all testing dependencies as we only need
zope.testing now.
- Fix ImportError when zope.testing is not available for some reason.
- Remove zcml slug and old zpkg-related files.
- Remove word "version" from changelog entries.
- Change package's mailing list address to zope-dev at zope.org as
zope3-dev at zope.org is now retired. Also changed `cheeseshop` to
`pypi` in the package's homepage url.
- Add dependency on ZODB3 as we use Persistent.
- Use a mock request for testing. Dropped the dependency on zope.publisher
which was really only a testing dependency.
- Reduce the dependency on zope.container to one on zope.location by no
longer using the Contained mix-in class.
3.6.0 (2009-01-31)
==================
- Use zope.container instead of zope.app.container
- Move error log bootstrapping logic (which was untested) to
``zope.app.appsetup``, to which we added a test.
3.5.1 (2007-09-27)
==================
- Rebump to replace faulty egg
3.5.0
=====
- Initial documented release
- Moved core components from ``zope.app.error`` to this package.
| zope.error | /zope.error-5.0.tar.gz/zope.error-5.0/CHANGES.rst | CHANGES.rst |
__docformat__ = 'restructuredtext'
import codecs
import logging
import time
from random import random
from threading import Lock
from xml.sax.saxutils import escape as xml_escape
import zope.location.interfaces
from persistent import Persistent
from zope.exceptions.exceptionformatter import format_exception
from zope.interface import implementer
from zope.error.interfaces import IErrorReportingUtility
from zope.error.interfaces import ILocalErrorReportingUtility
# Restrict the rate at which errors are sent to the Event Log
_rate_restrict_pool = {}
# The number of seconds that must elapse on average between sending two
# exceptions of the same name into the the Event Log. one per minute.
_rate_restrict_period = 60
# The number of exceptions to allow in a burst before the above limit
# kicks in. We allow five exceptions, before limiting them to one per
# minute.
_rate_restrict_burst = 5
# _temp_logs holds the logs.
_temp_logs = {} # { oid -> [ traceback string ] }
cleanup_lock = Lock()
logger = logging.getLogger('SiteError')
def printedreplace(error):
symbols = ("\\x%02x" % (s if isinstance(s, int) else ord(s))
for s in error.object[error.start:error.end])
return "".join(symbols), error.end
codecs.register_error("zope.error.printedreplace", printedreplace)
def getPrintable(value, as_html=False):
if not isinstance(value, str):
if not isinstance(value, bytes):
# A call to str(obj) could raise anything at all.
# We'll ignore these errors, and print something
# useful instead, but also log the error.
try:
value = str(value)
except Exception:
logger.exception(
"Error in ErrorReportingUtility while getting a str"
" representation of an object")
return "<unprintable %s object>" % (
xml_escape(type(value).__name__))
if isinstance(value, bytes):
value = value.decode('utf-8', errors="zope.error.printedreplace")
return value if as_html else xml_escape(value)
def getFormattedException(info, as_html=False):
lines = []
for line in format_exception(as_html=as_html, *info):
line = getPrintable(line, as_html=as_html)
if not line.endswith("\n"):
line += "<br />\n" if as_html else "\n"
lines.append(line)
return "".join(lines)
@implementer(IErrorReportingUtility,
ILocalErrorReportingUtility,
zope.location.interfaces.IContained)
class ErrorReportingUtility(Persistent):
"""Error Reporting Utility"""
__parent__ = __name__ = None
keep_entries = 20
copy_to_zlog = True
_ignored_exceptions = ('Unauthorized',)
def _getLog(self):
"""Returns the log for this object.
Careful, the log is shared between threads.
"""
log = _temp_logs.get(self._p_oid, None)
if log is None:
log = []
_temp_logs[self._p_oid] = log
return log
def _getUsername(self, request):
username = None
principal = getattr(request, "principal", None)
if principal is None:
return username
# UnauthenticatedPrincipal does not have getLogin()
getLogin = getattr(principal, "getLogin", None)
if getLogin is None:
login = "unauthenticated"
else:
try:
login = getLogin()
except Exception:
logger.exception("Error in ErrorReportingUtility while"
" getting login of the principal")
login = "<error getting login>"
parts = []
for part in [
login,
getattr(principal, "id",
"<error getting 'principal.id'>"),
getattr(principal, "title",
"<error getting 'principal.title'>"),
getattr(principal, "description",
"<error getting 'principal.description'>")
]:
part = getPrintable(part)
parts.append(part)
username = ", ".join(parts)
return username
def _getRequestAsHTML(self, request):
lines = []
for key, value in sorted(request.items()):
lines.append("{}: {}<br />\n".format(
getPrintable(key), getPrintable(value)))
return "".join(lines)
# Exceptions that happen all the time, so we dont need
# to log them. Eventually this should be configured
# through-the-web.
def raising(self, info, request=None):
"""Log an exception.
Called by ZopePublication.handleException method.
"""
now = time.time()
t, _v, tb = info
try:
strtype = getattr(t, '__name__', t)
strtype = strtype.decode(
"utf-8") if isinstance(strtype, bytes) else strtype
if strtype in self._ignored_exceptions:
return
tb_text = None
tb_html = None
if isinstance(tb, (str, bytes)):
tb_text = getPrintable(tb)
else:
tb_text = getFormattedException(info)
tb_html = getFormattedException(info, True)
url = None
username = None
req_html = None
if request:
# TODO: Temporary fix, which Steve should undo. URL is
# just too HTTPRequest-specific.
if hasattr(request, 'URL'):
url = str(request.URL)
username = self._getUsername(request)
req_html = self._getRequestAsHTML(request)
strv = getPrintable(info[1])
log = self._getLog()
entry_id = str(now) + str(random()) # Low chance of collision
log.append({
'type': strtype,
'value': strv,
'time': time.ctime(now),
'id': entry_id,
'tb_text': tb_text,
'tb_html': tb_html,
'username': username,
'url': url,
'req_html': req_html,
})
cleanup_lock.acquire()
try:
if len(log) >= self.keep_entries:
del log[:-self.keep_entries]
finally:
cleanup_lock.release()
if self.copy_to_zlog:
self._do_copy_to_zlog(now, strtype, str(url), info)
finally:
info = None
def _do_copy_to_zlog(self, now, strtype, url, info):
# info is unused; logging.exception() will call sys.exc_info()
# work around this with an evil hack
when = _rate_restrict_pool.get(strtype, 0)
if now > when:
next_when = max(when,
now - _rate_restrict_burst * _rate_restrict_period)
next_when += _rate_restrict_period
_rate_restrict_pool[strtype] = next_when
logger.error(str(url), exc_info=info)
def getProperties(self):
return {
'keep_entries': self.keep_entries,
'copy_to_zlog': self.copy_to_zlog,
'ignored_exceptions': self._ignored_exceptions,
}
def setProperties(self, keep_entries, copy_to_zlog=True,
ignored_exceptions=()):
"""Sets the properties of this site error log.
"""
self.keep_entries = int(keep_entries)
self.copy_to_zlog = bool(copy_to_zlog)
self._ignored_exceptions = tuple(
e.decode('utf-8') if not isinstance(e, str) else e
for e in ignored_exceptions
if e
)
def getLogEntries(self):
"""Returns the entries in the log, most recent first.
Makes a copy to prevent changes.
"""
res = [entry.copy() for entry in self._getLog()]
res.reverse()
return res
def getLogEntryById(self, id):
"""Returns the specified log entry.
Makes a copy to prevent changes. Returns None if not found.
"""
for entry in self._getLog():
if entry['id'] == id:
return entry.copy()
class RootErrorReportingUtility(ErrorReportingUtility):
rootId = 'root'
def _getLog(self):
"""Returns the log for this object.
Careful, the log is shared between threads.
"""
return _temp_logs.setdefault(self.rootId, [])
globalErrorReportingUtility = RootErrorReportingUtility()
def _cleanup_temp_log():
_temp_logs.clear()
def _clear():
_cleanup_temp_log()
for k in 'keep_entries', 'copy_to_zlog', '_ignored_exceptions':
try:
delattr(globalErrorReportingUtility, k)
except AttributeError:
pass
# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
try:
from zope.testing.cleanup import addCleanUp
except ImportError: # pragma: no cover
pass
else:
addCleanUp(_clear)
del addCleanUp | zope.error | /zope.error-5.0.tar.gz/zope.error-5.0/src/zope/error/error.py | error.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.
| zope.errorview | /zope.errorview-2.0-py3-none-any.whl/zope.errorview-2.0.dist-info/LICENSE.rst | LICENSE.rst |
from zope.browser.interfaces import ISystemErrorView
from zope.event import notify
from zope.interface import implementer
from zope.publisher.interfaces.http import IHTTPException
from zope.errorview.interfaces import HandleExceptionEvent
@implementer(ISystemErrorView)
class SystemErrorViewMixin:
"""An optional mixin to indicate a particular error view to be an "system
error" view. This indicates the publication object to log the error again
with the error reporting utility.
"""
def isSystemError(self):
return True
@implementer(IHTTPException)
class ExceptionViewBase:
def __init__(self, context, request):
self.context = context
self.request = request
def update(self):
self.request.response.setStatus(500)
self.request.response.setHeader(
'Content-Type', 'text/plain;charset=utf-8')
def render(self):
return ''
def __call__(self):
notify(HandleExceptionEvent(self.request))
self.update()
return self.render()
def __str__(self):
return self()
class ExceptionView(ExceptionViewBase):
pass
class TraversalExceptionView(ExceptionViewBase):
def update(self):
super().update()
if self.request.method == 'MKCOL' and self.request.getTraversalStack():
# MKCOL with non-existing parent.
self.request.response.setStatus(409)
else:
self.request.response.setStatus(404)
class UnauthorizedView(ExceptionViewBase):
def update(self):
super().update()
self.request.unauthorized('basic realm="Zope"')
self.request.response.setStatus(401)
class MethodNotAllowedView(ExceptionViewBase):
# XXX define an interface for MethodNotAllowedView components.
def allowed(self):
# XXX how to determine the allowed HTTP methods? XXX we need
# a safe way to determine the allow HTTP methods. Or should we
# let the application handle it?
return []
def update(self):
super().update()
allow = self.allowed()
self.request.response.setStatus(405)
self.request.response.setHeader('Allow', ', '.join(allow)) | zope.errorview | /zope.errorview-2.0-py3-none-any.whl/zope/errorview/http.py | http.py |
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface import implementer
class IDuplicationError(Interface):
pass
@implementer(IDuplicationError)
class DuplicationError(Exception):
"""A duplicate registration was attempted"""
class IUserError(Interface):
"""User error exceptions
"""
@implementer(IUserError)
class UserError(Exception):
"""User errors
These exceptions should generally be displayed to users unless
they are handled.
"""
class ITracebackSupplement(Interface):
"""Provides valuable information to supplement an exception traceback.
The interface is geared toward providing meaningful feedback when
exceptions occur in user code written in mini-languages like
Zope page templates and restricted Python scripts.
"""
source_url = Attribute(
'source_url',
"""Optional. Set to URL of the script where the exception occurred.
Normally this generates a URL in the traceback that the user
can visit to manage the object. Set to None if unknown or
not available.
""")
line = Attribute(
'line',
"""Optional. Set to the line number (>=1) where the exception
occurred.
Set to 0 or None if the line number is unknown.
""")
column = Attribute(
'column',
"""Optional. Set to the column offset (>=0) where the exception
occurred.
Set to None if the column number is unknown.
""")
expression = Attribute(
'expression',
"""Optional. Set to the expression that was being evaluated.
Set to None if not available or not applicable.
""")
warnings = Attribute(
'warnings',
"""Optional. Set to a sequence of warning messages.
Set to None if not available, not applicable, or if the exception
itself provides enough information.
""")
def getInfo():
"""Optional. Returns a string containing any other useful info.
""" | zope.exceptions | /zope.exceptions-5.0.1-py3-none-any.whl/zope/exceptions/interfaces.py | interfaces.py |
import linecache
import sys
import traceback
from html import escape
DEBUG_EXCEPTION_FORMATTER = 1
class TextExceptionFormatter:
line_sep = '\n'
def __init__(self, limit=None, with_filenames=False):
self.limit = limit
self.with_filenames = with_filenames
def escape(self, s):
return s
def getPrefix(self):
return 'Traceback (most recent call last):'
def getLimit(self):
limit = self.limit
if limit is None:
limit = getattr(sys, 'tracebacklimit', 200)
return limit
def formatSupplementLine(self, line):
return f' - {line}'
def formatSourceURL(self, url):
return [self.formatSupplementLine(url)]
def formatSupplement(self, supplement, tb):
result = []
fmtLine = self.formatSupplementLine
url = getattr(supplement, 'source_url', None)
if url is not None:
result.extend(self.formatSourceURL(url))
line = getattr(supplement, 'line', 0)
if line == -1:
line = tb.tb_lineno
col = getattr(supplement, 'column', -1)
if line:
if col is not None and col >= 0:
result.append(fmtLine('Line {}, Column {}'.format(
line, col)))
else:
result.append(fmtLine('Line %s' % line))
elif col is not None and col >= 0:
result.append(fmtLine('Column %s' % col))
expr = getattr(supplement, 'expression', None)
if expr:
result.append(fmtLine('Expression: %s' % expr))
warnings = getattr(supplement, 'warnings', None)
if warnings:
for warning in warnings:
result.append(fmtLine('Warning: %s' % warning))
getInfo = getattr(supplement, 'getInfo', None)
if getInfo is not None:
try:
extra = getInfo()
if extra:
result.append(self.formatSupplementInfo(extra))
except Exception: # pragma: no cover
if DEBUG_EXCEPTION_FORMATTER:
traceback.print_exc()
# else just swallow the exception.
return result
def formatSupplementInfo(self, info):
return self.escape(info)
def formatTracebackInfo(self, tbi):
return self.formatSupplementLine('__traceback_info__: {}'.format(tbi))
def formatLine(self, tb=None, f=None):
if tb and not f:
f = tb.tb_frame
lineno = tb.tb_lineno
elif not tb and f:
lineno = f.f_lineno
else:
raise ValueError("Pass exactly one of tb or f")
co = f.f_code
filename = co.co_filename
name = co.co_name
f_locals = f.f_locals
f_globals = f.f_globals
if self.with_filenames:
s = ' File "%s", line %d' % (filename, lineno)
else:
modname = f_globals.get('__name__', filename)
s = ' Module %s, line %d' % (modname, lineno)
s = s + ', in %s' % name
result = []
result.append(self.escape(s))
# Append the source line, if available
line = linecache.getline(filename, lineno)
if line:
result.append(" " + self.escape(line.strip()))
# Output a traceback supplement, if any.
if '__traceback_supplement__' in f_locals:
# Use the supplement defined in the function.
tbs = f_locals['__traceback_supplement__']
elif '__traceback_supplement__' in f_globals:
# Use the supplement defined in the module.
# This is used by Scripts (Python).
tbs = f_globals['__traceback_supplement__']
else:
tbs = None
if tbs is not None:
factory = tbs[0]
args = tbs[1:]
try:
supp = factory(*args)
result.extend(self.formatSupplement(supp, tb))
except Exception: # pragma: no cover
if DEBUG_EXCEPTION_FORMATTER:
traceback.print_exc()
# else just swallow the exception.
try:
tbi = f_locals.get('__traceback_info__', None)
if tbi is not None:
result.append(self.formatTracebackInfo(tbi))
except Exception: # pragma: no cover
if DEBUG_EXCEPTION_FORMATTER:
traceback.print_exc()
# else just swallow the exception.
return self.line_sep.join(result)
def formatExceptionOnly(self, etype, value):
# We don't want to get an error when we format an error, so we
# compensate in our code. For example, on Python 3.11.0 HTTPError
# gives an unhelpful KeyError in tempfile when Python formats it.
# See https://github.com/python/cpython/issues/90113
try:
result = ''.join(traceback.format_exception_only(etype, value))
except Exception: # pragma: no cover
# This code branch is only covered on Python 3.11+.
result = str(value)
return result
def formatLastLine(self, exc_line):
return self.escape(exc_line)
def formatException(self, etype, value, tb):
# The next line provides a way to detect recursion. The 'noqa'
# comment disables a flake8 warning about the unused variable.
__exception_formatter__ = 1 # noqa
result = []
while tb is not None:
if tb.tb_frame.f_locals.get('__exception_formatter__'):
# Stop recursion.
result.append('(Recursive formatException() stopped, '
'trying traceback.format_tb)\n')
result.extend(traceback.format_tb(tb))
break
line = self.formatLine(tb=tb)
result.append(line + '\n')
tb = tb.tb_next
template = (
'...\n'
'{omitted} entries omitted, because limit is {limit}.\n'
'Set sys.tracebacklimit or {klass}.limit to a higher'
' value to see omitted entries\n'
'...')
self._obeyLimit(result, template)
result = [self.getPrefix() + '\n'] + result
exc_line = self.formatExceptionOnly(etype, value)
result.append(self.formatLastLine(exc_line))
return result
def extractStack(self, f=None):
if f is None:
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
# The next line provides a way to detect recursion. The 'noqa'
# comment disables a flake8 warning about the unused variable.
__exception_formatter__ = 1 # noqa
result = []
while f is not None:
if f.f_locals.get('__exception_formatter__'):
# Stop recursion.
result.append('(Recursive extractStack() stopped, '
'trying traceback.format_stack)\n')
res = traceback.format_stack(f)
res.reverse()
result.extend(res)
break
line = self.formatLine(f=f)
result.append(line + '\n')
f = f.f_back
self._obeyLimit(
result,
'...{omitted} entries omitted, because limit is {limit}...\n')
result.reverse()
return result
def _obeyLimit(self, result, template):
limit = self.getLimit()
if limit is not None and len(result) > limit:
# cut out the middle part of the TB
tocut = len(result) - limit
middle = len(result) // 2
lower = middle - tocut // 2
msg = template.format(
omitted=tocut, limit=limit, klass=self.__class__.__name__)
result[lower:lower + tocut] = [msg]
class HTMLExceptionFormatter(TextExceptionFormatter):
line_sep = '<br />\r\n'
def escape(self, s):
return escape(str(s), quote=False)
def getPrefix(self):
return '<p>Traceback (most recent call last):</p>\r\n<ul>'
def formatSupplementLine(self, line):
return '<b>%s</b>' % self.escape(line)
def formatSupplementInfo(self, info):
info = self.escape(info)
info = info.replace(" ", " ")
info = info.replace("\n", self.line_sep)
return info
def formatTracebackInfo(self, tbi):
s = self.escape(tbi)
s = s.replace('\n', self.line_sep)
return '__traceback_info__: {}'.format(s)
def formatLine(self, tb=None, f=None):
line = TextExceptionFormatter.formatLine(self, tb, f)
return '<li>%s</li>' % line
def formatLastLine(self, exc_line):
line = '</ul><p>%s</p>' % self.escape(exc_line)
return line.replace('\n', self.line_sep)
def format_exception(t, v, tb, limit=None, as_html=False,
with_filenames=False):
"""Format a stack trace and the exception information.
Similar to 'traceback.format_exception', but adds supplemental
information to the traceback and accepts two options, 'as_html'
and 'with_filenames'.
The result is a list of strings.
"""
if as_html:
fmt = HTMLExceptionFormatter(limit, with_filenames)
else:
fmt = TextExceptionFormatter(limit, with_filenames)
return fmt.formatException(t, v, tb)
def print_exception(t, v, tb, limit=None, file=None, as_html=False,
with_filenames=True):
"""Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
Similar to 'traceback.print_exception', but adds supplemental
information to the traceback and accepts two options, 'as_html'
and 'with_filenames'.
"""
if file is None: # pragma: no cover
file = sys.stderr
lines = format_exception(t, v, tb, limit, as_html, with_filenames)
for line in lines:
file.write(line)
def extract_stack(f=None, limit=None, as_html=False,
with_filenames=True):
"""Format a stack trace and the exception information.
Similar to 'traceback.extract_stack', but adds supplemental
information to the traceback and accepts two options, 'as_html'
and 'with_filenames'.
"""
if as_html:
fmt = HTMLExceptionFormatter(limit, with_filenames)
else:
fmt = TextExceptionFormatter(limit, with_filenames)
return fmt.extractStack(f) | zope.exceptions | /zope.exceptions-5.0.1-py3-none-any.whl/zope/exceptions/exceptionformatter.py | exceptionformatter.py |
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
__version__ = '2015-07-01'
# See zc.buildout's changelog if this version is up to date.
tmpeggs = tempfile.mkdtemp(prefix='bootstrap-')
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 --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("--version",
action="store_true", default=False,
help=("Return bootstrap.py version."))
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", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
parser.add_option("--allow-site-packages",
action="store_true", default=False,
help=("Let bootstrap.py use existing site packages"))
parser.add_option("--buildout-version",
help="Use a specific zc.buildout version")
parser.add_option("--setuptools-version",
help="Use a specific setuptools version")
parser.add_option("--setuptools-to-dir",
help=("Allow for re-use of existing directory of "
"setuptools versions"))
options, args = parser.parse_args()
if options.version:
print("bootstrap.py version %s" % __version__)
sys.exit(0)
######################################################################
# load/install setuptools
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
ez = {}
if os.path.exists('ez_setup.py'):
exec(open('ez_setup.py').read(), ez)
else:
exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez)
if not options.allow_site_packages:
# ez_setup imports site, which adds site packages
# this will remove them from the path to ensure that incompatible versions
# of setuptools are not in the path
import site
# inside a virtualenv, there is no 'getsitepackages'.
# We can't remove these reliably
if hasattr(site, 'getsitepackages'):
for sitepackage_path in site.getsitepackages():
# Strip all site-packages directories from sys.path that
# are not sys.prefix; this is because on Windows
# sys.prefix is a site-package directory.
if sitepackage_path != sys.prefix:
sys.path[:] = [x for x in sys.path
if sitepackage_path not in x]
setup_args = dict(to_dir=tmpeggs, download_delay=0)
if options.setuptools_version is not None:
setup_args['version'] = options.setuptools_version
if options.setuptools_to_dir is not None:
setup_args['to_dir'] = options.setuptools_to_dir
ez['use_setuptools'](**setup_args)
import setuptools
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)
######################################################################
# Install buildout
ws = pkg_resources.working_set
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
# Fix sys.path here as easy_install.pth added before PYTHONPATH
cmd = [sys.executable, '-c',
'import sys; sys.path[0:0] = [%r]; ' % setuptools_path +
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
requirement = 'zc.buildout'
version = options.buildout_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):
try:
return not parsed_version.is_prerelease
except AttributeError:
# Older setuptools
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=[setuptools_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)
import subprocess
if subprocess.call(cmd) != 0:
raise Exception(
"Failed to execute command:\n%s" % repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | zope.fanstatic | /zope.fanstatic-3.0.0.tar.gz/zope.fanstatic-3.0.0/bootstrap.py | bootstrap.py |
Zope integration for fanstatic
******************************
This package provides Zope integration for fanstatic. This means it's
taking care of three things:
* provide access to the needed resources throughout the request/response cycle.
* provide the base URL for the resources to be rendered.
* clear the needed resources when an exception view is rendered.
This library fulfills these conditions for a Zope Toolkit/Grok setup.
We'll run through a few tests to demonstrate it. Note that the real
code being tested is not in this document itself, but in the views
described in ``ftesting.zcml``.
We need to be in a request to make this work, so let's up a request to
a page we have set up in ``ftesting.zcml`` that should cause the
inclusion of a single resource in its header::
>>> from zope.testbrowser.wsgi import Browser
>>> browser = Browser()
>>> browser.open('http://localhost/zope.fanstatic.test_single')
>>> print(browser.contents)
<html>
<head>
<script type="text/javascript" src="http://localhost/fanstatic/foo/a.js"></script></head>
<body>
<p>the widget HTML itself</p>
</body>
</html>
If a resource happens to need another resource, this resource is also
automatically included::
>>> browser.open('http://localhost/zope.fanstatic.test_multiple')
>>> print(browser.contents)
<html>
<head>
<script type="text/javascript" src="http://localhost/fanstatic/foo/a.js"></script>
<script type="text/javascript" src="http://localhost/fanstatic/foo/b.js"></script></head>
<body>
<p>the widget HTML itself</p>
</body>
</html>
Bottom rendering of resources, just before the ``</body>`` tag::
>>> browser.open('http://localhost/zope.fanstatic.test_bottom')
>>> print(browser.contents)
<html>
<head>
</head>
<body>
<p>the widget HTML itself</p>
<script type="text/javascript" src="http://localhost/fanstatic/foo/c.js"></script>
<script type="text/javascript" src="http://localhost/fanstatic/foo/d.js"></script></body>
</html>
In-template resources
---------------------
zope.fanstatic provides support for rendering resource publisher
aware URLs to in-template resources::
>>> browser.open('http://localhost/zope.fanstatic.test_inline_resource')
>>> print(browser.contents)
<html>
<head>
</head>
<body>
<img src="http://localhost/fanstatic/foo/evencaveman.jpg" />
<img src="http://localhost/fanstatic/foo/sub/evencaveman.jpg" />
</body>
</html>
Exception views
---------------
When an exception occurs in the rendering of a view, we don't want to have any
needed resources intended for a view being also injected in the error view.
The needed resources are cleared and if the exception view chooses to do so,
it can need resources itself.
>>> browser.raiseHttpErrors = False
>>> browser.open('http://localhost/zope.fanstatic.test_error')
>>> import fanstatic
>>> fanstatic.get_needed().has_resources()
False
| zope.fanstatic | /zope.fanstatic-3.0.0.tar.gz/zope.fanstatic-3.0.0/src/zope/fanstatic/README.txt | README.txt |
import fanstatic
from zope.component import adapter
from zope.errorview.interfaces import IHandleExceptionEvent
from zope.fanstatic.interfaces import IZopeFanstaticResource
from zope.interface import implementer
from zope.publisher.interfaces import IEndRequestEvent
from zope.traversing.browser.absoluteurl import absoluteURL
from zope.traversing.browser.interfaces import IAbsoluteURL
from zope.traversing.interfaces import ITraversable
def ensure_base_url(needed, request):
if not isinstance(needed, fanstatic.NeededResources):
# Do nothing if there's no concrete NeededResources at all.
return
if not needed.has_base_url():
# Only set the base_url if it has not been set just yet.
#
# Note that the given context is set to None, resulting in
# computing a URL to the Application root (while still
# adhering to the, for example, virtualhost information). In
# principle this is not correct, as we should compute the URL
# for the nearest ISite object, but there is no site nor
# context anymore in the EndRequestEvent (as the request has
# been "closed", transactions have been handled, and the site
# is cleared). Since fanstatic resource "registrations" cannot
# be overridden on a per ISite basis anyway, this is good
# enough.
needed.set_base_url(absoluteURL(None, request))
@adapter(IEndRequestEvent)
def set_base_url(event):
# At first sight it might be better to subscribe to the
# IBeforeTraverseEvent for ISite objects and only set a base_url
# then. However, we might be too early in that case and miss out
# on essential information for computing URLs. One example of such
# information is that of the virtualhost namespace traversal.
needed = fanstatic.get_needed()
ensure_base_url(needed, event.request)
@adapter(IHandleExceptionEvent)
def clear_needed_resources(event):
needed = fanstatic.get_needed()
if isinstance(needed, fanstatic.NeededResources):
# Only if there's a concrete NeededResources.
needed.clear()
_sentinel = object()
@implementer(IZopeFanstaticResource, ITraversable, IAbsoluteURL)
class ZopeFanstaticResource(object):
# Hack to get ++resource++foo/bar/baz.jpg *paths* working in Zope
# Pagetemplates. Note that ++resource+foo/bar/baz.jpg *URLs* will
# not work with this hack!
#
# The ZopeFanstaticResource class also implements an __getitem__()
# / get() interface, to support rendering URLs to resources from
# code.
def __init__(self, request, library, name=''):
self.request = request
self.library = library
self.name = name
def get(self, name, default=_sentinel):
# XXX return default if given, or NotFound (or something) when
# not, in case name is not resolved to an actual resource.
name = '%s/%s' % (self.name, name)
return ZopeFanstaticResource(self.request, self.library, name=name)
def traverse(self, name, furtherPath):
return self.get(name)
def __getitem__(self, name):
resource = self.get(name, None)
if resource is None:
raise KeyError(name)
return resource
def __str__(self):
needed = fanstatic.get_needed()
if not isinstance(needed, fanstatic.NeededResources):
# We cannot render a URL in this case, we just return some
# fake url to indicate this.
return '++resource++%s%s' % (self.library.name, self.name)
ensure_base_url(needed, self.request)
return needed.library_url(self.library) + self.name
__call__ = __str__ | zope.fanstatic | /zope.fanstatic-3.0.0.tar.gz/zope.fanstatic-3.0.0/src/zope/fanstatic/zopesupport.py | zopesupport.py |
=========
CHANGES
=========
1.2.0 (2020-03-06)
==================
- Add support for Python 3.7 and 3.8
- Drop Python 3.4 support.
1.1.0 (2017-09-30)
==================
- Move more browser dependencies to the ``browser`` extra.
- Begin testing PyPy3 on Travis CI.
1.0.0 (2017-04-25)
==================
- Remove unneeded test dependencies zope.app.server,
zope.app.component, zope.app.container, and others.
- Update to work with zope.testbrowser 5.
- Add PyPy support.
- Add support for Python 3.4, 3.5 and 3.6.
See `PR 5 <https://github.com/zopefoundation/zope.file/pull/5>`_.
0.6.2 (2012-06-04)
==================
- Moved menu-oriented registrations into new menus.zcml. This is now
loaded if zope.app.zcmlfiles is available only.
- Increase test coverage.
0.6.1 (2012-01-26)
==================
- Declared more dependencies.
0.6.0 (2010-09-16)
==================
- Bug fix: remove duplicate firing of ObjectCreatedEvent in
zope.file.upload.Upload (the event is already fired in its base class,
zope.formlib.form.AddForm).
- Move browser-related zcml to `browser.zcml` so that it easier for
applications to exclude it.
- Import content-type parser from zope.contenttype, adding a dependency on
that package.
- Removed undeclared dependency on zope.app.container, depend on zope.browser.
- Using Python's ``doctest`` module instead of deprecated
``zope.testing.doctest``.
0.5.0 (2009-07-23)
==================
- Change package's mailing list address to zope-dev at zope.org instead
of the retired one.
- Made tests compatible with ZODB 3.9.
- Removed not needed install requirement declarations.
0.4.0 (2009-01-31)
==================
- `openDetached` is now protected by zope.View instead of zope.ManageContent.
- Use zope.container instead of zope.app.container.
0.3.0 (2007-11-01)
==================
- Package data update.
0.2.0 (2007-04-18)
==================
- Fix code for Publisher version 3.4.
0.1.0 (2007-04-18)
==================
- Initial release.
| zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/CHANGES.rst | CHANGES.rst |
=======================
Presentation Adapters
=======================
Object size
===========
The size of the file as presented in the contents view of a container is
provided using an adapter implementing the `zope.size.interfaces.ISized`
interface. Such an adapter is available for the file object.
Let's do some imports and create a new file object:
>>> from zope.file.file import File
>>> from zope.file.browser import Sized
>>> from zope.size.interfaces import ISized
>>> f = File()
>>> f.size
0
>>> s = Sized(f)
>>> ISized.providedBy(s)
True
>>> s.sizeForSorting()
('byte', 0)
>>> s.sizeForDisplay()
u'0 KB'
Let's add some content to the file:
>>> with f.open('w') as w:
... _ = w.write(b"some text")
The sized adapter now reflects the updated size:
>>> s.sizeForSorting()
('byte', 9)
>>> s.sizeForDisplay()
u'1 KB'
Let's try again with a larger file size:
>>> with f.open('w') as w:
... _ = w.write(b"x" * (1024*1024+10))
>>> s.sizeForSorting()
('byte', 1048586)
>>> m = s.sizeForDisplay()
>>> m
u'${size} MB'
>>> m.mapping
{'size': '1.00'}
And still a bigger size:
>>> with f.open('w') as w:
... _ = w.write(b"x" * 3*512*1024)
>>> s.sizeForSorting()
('byte', 1572864)
>>> m = s.sizeForDisplay()
>>> m
u'${size} MB'
>>> m.mapping
{'size': '1.50'}
| zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/src/zope/file/browser.rst | browser.rst |
==========
Adapters
==========
The `zope.file` package provides some adapters to adapt file-like
objects to `zope.filerepresentation` conform objects. There is a
read-file adapter and a write-file adapter available. We start with a
regular `File` object:
>>> from zope.file.file import File
>>> f = File(parameters=dict(charset='utf-8'))
>>> with f.open('w') as _: _ = _.write(b"hello")
Now we can turn this file into a read-only file which we can read and
whose size we can get:
>>> from zope.filerepresentation.interfaces import IReadFile, IWriteFile
>>> r = IReadFile(f)
>>> r.read()
'hello'
>>> r.size()
5
Writing to this read-only file is impossible, as the interface does
not require it:
>>> r.write(b"some more content")
Traceback (most recent call last):
AttributeError: 'ReadFileAdapter' object has no attribute 'write'
With a write-file the opposite happens. We can write but not read:
>>> w = IWriteFile(f)
>>> w.write(b"some more content")
>>> w.read()
Traceback (most recent call last):
AttributeError: 'WriteFileAdapter' object has no attribute 'read'
The delivered adapters really comply with the promised interfaces:
>>> from zope.interface.verify import verifyClass, verifyObject
>>> from zope.file.adapters import ReadFileAdapter, WriteFileAdapter
>>> verifyClass(IReadFile, ReadFileAdapter)
True
>>> verifyObject(IReadFile, r)
True
>>> verifyClass(IWriteFile, WriteFileAdapter)
True
>>> verifyObject(IWriteFile, w)
True
| zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/src/zope/file/adapters.rst | adapters.rst |
=============
File Object
=============
The `zope.file` package provides a content object used to store a
file. The interface supports efficient upload and download. Let's
create an instance:
>>> from zope.file.file import File
>>> f = File()
The object provides a limited number of data attributes. The
`mimeType` attribute is used to store the preferred MIME
content-type value for the data:
>>> f.mimeType
>>> f.mimeType = "text/plain"
>>> f.mimeType
'text/plain'
>>> f.mimeType = "application/postscript"
>>> f.mimeType
'application/postscript'
The `parameters` attribute is a mapping used to store the content-type
parameters. This is where encoding information can be found when
applicable (and available):
>>> f.parameters
{}
>>> f.parameters["charset"] = "us-ascii"
>>> f.parameters["charset"]
'us-ascii'
Both, `parameters` and `mimeType` can optionally also be set when
creating a `File` object:
>>> f2 = File(mimeType = "application/octet-stream",
... parameters = dict(charset = "utf-8"))
>>> f2.mimeType
'application/octet-stream'
>>> f2.parameters["charset"]
'utf-8'
File objects also sport a `size` attribute that provides the number of
bytes in the file:
>>> f.size
0
The object supports efficient upload and download by providing all
access to content data through accessor objects that provide (subsets
of) Python's file API.
A file that hasn't been written to is empty. We can get a reader by calling
`open()`. Note that all blobs are binary, thus the mode always contains a
'b':
>>> r = f.open("r")
>>> r.mode
'rb'
The `read()` method can be called with a non-negative integer argument
to specify how many bytes to read, or with a negative or omitted
argument to read to the end of the file:
>>> r.read(10)
''
>>> r.read()
''
>>> r.read(-1)
''
Once the accessor has been closed, we can no longer read from it:
>>> r.close()
>>> r.read()
Traceback (most recent call last):
ValueError: I/O operation on closed file
We'll see that readers are more interesting once there's data in the
file object.
Data is added by using a writer, which is also created using the
`open()` method on the file, but requesting a write file mode:
>>> w = f.open("w")
>>> w.mode
'wb'
The `write()` method is used to add data to the file, but note that
the data may be buffered in the writer:
>>> _ = w.write(b"some text ")
>>> _ = w.write(b"more text")
The `flush()` method ensure that the data written so far is written to
the file object:
>>> w.flush()
We need to close the file first before determining its file size
>>> w.close()
>>> f.size
19
We can now use a reader to see that the data has been written to the
file:
>>> w = f.open("w")
>>> _ = w.write(b'some text more text')
>>> _ = w.write(b" still more")
>>> w.close()
>>> f.size
30
Now create a new reader and let's perform some seek operations.
>>> r = f.open()
The reader also has a `seek()` method that can be used to back up or
skip forward in the data stream. Simply passing an offset argument,
we see that the current position is moved to that offset from the
start of the file:
>>> _ = r.seek(20)
>>> r.read()
'still more'
That's equivalent to passing 0 as the `whence` argument:
>>> _ = r.seek(20, 0)
>>> r.read()
'still more'
We can skip backward and forward relative to the current position by
passing 1 for `whence`:
>>> _ = r.seek(-10, 1)
>>> r.read(5)
'still'
>>> _ = r.seek(2, 1)
>>> r.read()
'ore'
We can skip to some position backward from the end of the file using
the value 2 for `whence`:
>>> _ = r.seek(-10, 2)
>>> r.read()
'still more'
>>> _ = r.seek(0)
>>> _ = r.seek(-4, 2)
>>> r.read()
'more'
>>> r.close()
Attempting to write to a closed writer raises an exception:
>>> w = f.open('w')
>>> w.close()
>>> w.write(b'foobar')
Traceback (most recent call last):
ValueError: I/O operation on closed file
Similarly, using `seek()` or `tell()` on a closed reader raises an
exception:
>>> r.close()
>>> _ = r.seek(0)
Traceback (most recent call last):
ValueError: I/O operation on closed file
>>> r.tell()
Traceback (most recent call last):
ValueError: I/O operation on closed file
| zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/src/zope/file/README.rst | README.rst |
__docformat__ = "reStructuredText"
from contextlib import closing
import zope.component
import zope.formlib.form
import zope.formlib.interfaces
import zope.interface
import zope.schema
from zope.mimetype.interfaces import IContentTypeEncoded
from zope.mimetype.interfaces import IContentTypeInterface
from zope.mimetype.interfaces import ICharsetCodec
from zope.mimetype.interfaces import ICodecPreferredCharset
from zope.mimetype.event import changeContentType
from zope.mimetype.source import contentTypeSource
from zope.mimetype.source import codecSource
from zope.file.i18n import _
from zope.security.proxy import removeSecurityProxy
from zope.lifecycleevent import ObjectModifiedEvent
def validateCodecUse(file, iface, codec, codec_field):
"""Validate the use of `codec` for the data in `file`.
`iface` is used as the content-type interface for `file`. If
`iface` is None, no validation is performed and no error is
reported (this validation is considered irrelevant).
If `codec` is None, no error is reported, since that indicates
that no codec is known to be accurate for the data in `file`.
`codec_field` is the form field that is used to select the codec;
it is used to generate an error should one be necessary.
Returns a list of widget input errors that should be added to any
other errors the form determines are relevant.
"""
if codec is None or iface is None:
return []
if not iface.extends(IContentTypeEncoded):
return []
errs = []
# Need to test that this codec can be used for this
# document:
with closing(file.open("r")) as f:
content_data = f.read()
try:
_, consumed = codec.decode(content_data)
if consumed != len(content_data):
raise UnicodeError("not all data decoded")
except UnicodeError:
err = zope.formlib.interfaces.WidgetInputError(
codec_field.__name__,
codec_field.field.title,
"Selected encoding cannot decode document.")
errs.append(err)
return errs
class ContentTypeForm(zope.formlib.form.Form):
mimeType_field = zope.formlib.form.Field(
zope.schema.Choice(
__name__="mimeType",
title=_("Content type"),
description=_("Type of document"),
source=contentTypeSource,
))
encoding_field = zope.formlib.form.Field(
zope.schema.Choice(
__name__="encoding",
title=_("Encoding"),
description=_("Character data encoding"),
source=codecSource,
required=False,
))
def get_rendered_encoding(self):
charset = self.context.parameters.get("charset")
if charset:
return zope.component.queryUtility(ICharsetCodec, charset)
encoding_field.get_rendered = get_rendered_encoding
def get_rendered_mimeType(self):
# make sure we return the exact `IContentType`-derived
# interface that the context provides; there *must* be only
# one!
ifaces = zope.interface.directlyProvidedBy(
removeSecurityProxy(self.context))
for iface in ifaces:
if IContentTypeInterface.providedBy(iface):
return iface
mimeType_field.get_rendered = get_rendered_mimeType
def setUpWidgets(self, ignore_request=False):
# We need to re-compute the fields before initializing the widgets
fields = [self.mimeType_field]
if IContentTypeEncoded.providedBy(self.context):
self.have_encoded = True
fields.append(self.encoding_field)
else:
self.have_encoded = False
self.form_fields = zope.formlib.form.Fields(*fields)
super(ContentTypeForm, self).setUpWidgets(
ignore_request=ignore_request)
def save_validator(self, action, data):
errs = self.validate(None, data)
errs += validateCodecUse(
self.context, data.get("mimeType"), data.get("encoding"),
self.encoding_field)
return errs
@zope.formlib.form.action(_("Save"), validator=save_validator)
def save(self, action, data):
context = self.context
if data.get("mimeType"):
#
# XXX Note that the content type parameters are not
# modified; ideally, the IContentInfo adapter would filter
# the parameters for what makes sense for the current
# content type.
#
iface = data["mimeType"]
unwrapped = removeSecurityProxy(context)
changeContentType(unwrapped, iface)
# update the encoding, but only if the new content type is encoded
encoded = IContentTypeEncoded.providedBy(context)
# We only care about encoding if we're encoded now and were also
# encoded before starting the re
if encoded and self.have_encoded:
codec = data["encoding"]
if codec is None:
# remove any charset found, since the user said it was wrong;
# what it means to have no known charset is that the policy
# (IContentInfo) will have to decide how to treat encoding.
if "charset" in context.parameters:
# We can't just "del" the existing value, since
# the security model does not like that. We can
# set a new value for context.parameters, though.
parameters = dict(context.parameters)
del parameters["charset"]
context.parameters = parameters
else:
if "charset" in context.parameters:
old_codec = zope.component.queryUtility(
ICharsetCodec,
context.parameters["charset"])
else:
old_codec = None
if getattr(old_codec, "name", None) != codec.name:
# use the preferred charset for the new codec
new_charset = zope.component.getUtility(
ICodecPreferredCharset,
codec.name)
parameters = dict(context.parameters)
parameters["charset"] = new_charset.name
context.parameters = parameters
zope.event.notify(
ObjectModifiedEvent(removeSecurityProxy(context))) | zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/src/zope/file/contenttype.py | contenttype.py |
__docformat__ = "reStructuredText"
import zope.interface
import zope.mimetype.interfaces
import zope.schema
from zope.file.i18n import _
class IFile(zope.mimetype.interfaces.IContentTypeAware):
"""File content object for Zope."""
def open(mode="r"):
"""Return an object providing access to the file data.
Allowed values for `mode` are 'r' (read); 'w' (write); 'a' (append) and
'r+' (read/write). Other values cause `ValueError` to be raised.
If the file is opened in read mode, an object with an API (but
not necessarily interface) of `IFileReader` is returned; if
opened in write mode, an object with an API of `IFileWriter` is
returned; if in read/write, an object that implements both is
returned.
All readers and writers operate in 'binary' mode.
"""
def openDetached():
"""Return file data disconnected from database connection.
Read access only.
"""
size = zope.schema.Int(
title=_("Size"),
description=_("Size in bytes"),
readonly=True,
required=True,
)
# The remaining interfaces below serve only to document the kind of APIs
# to be expected, as described in IFile.open above.
class IFileAccessor(zope.interface.Interface):
"""Base accessor for `IFileReader` and `IFileWriter`."""
def close():
"""Release the accessor.
Resources held by the accessor are freed, and further use of
the accessor will result in a `ValueError` exception.
"""
mode = zope.schema.BytesLine(
title=_("Open mode passed to the corresponding file's open() method,"
" or the default value if not passed."),
required=True,
)
class IFileReader(IFileAccessor):
"""Read-accessor for file objects.
The methods here mirror the corresponding portions of the API for
Python file objects.
"""
def read(size=-1):
"""Read at most `size` bytes from the reader.
If the size argument is negative or omitted, read all data
until EOF is reached. The bytes are returned as a str. An
empty string is returned when EOF is encountered immediately.
"""
def seek(offset, whence=0):
"""Set the reader's current position.
The `offset` is a number of bytes. The direction and source
of the measurement is determined by the `whence` argument.
The `whence` argument is optional and defaults to 0 (absolute
file positioning); other recognized values are 1 (seek
relative to the current position) and 2 (seek relative to the
end).
There is no return value.
"""
def tell():
"""Return the current position, measured in bytes."""
class IFileWriter(IFileAccessor):
"""Write-accessor for file objects.
The methods here mirror the corresponding portions of the API for
Python file objects.
"""
def flush():
"""Ensure the file object has been updated.
This is used to make sure that any data buffered in the
accessor is stored in the file object, allowing other
accessors to use it.
"""
def write(bytes):
"""Write a string to the file.
Due to buffering, the string may not actually show up in the
file until the `flush()` or `close()` method is called.
There is no return value.
""" | zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/src/zope/file/interfaces.py | interfaces.py |
======================
Uploading a new file
======================
There's a simple view for uploading a new file. Let's try it:
>>> from io import BytesIO as StringIO
>>> sio = StringIO(b"some text")
>>> from zope.testbrowser.wsgi import Browser
>>> browser = Browser()
>>> browser.handleErrors = False
>>> browser.addHeader("Authorization", "Basic mgr:mgrpw")
>>> browser.addHeader("Accept-Language", "en-US")
>>> browser.open("http://localhost/@@+/zope.file.File")
>>> ctrl = browser.getControl(name="form.data")
>>> ctrl.add_file(
... sio, "text/plain; charset=utf-8", "plain.txt")
>>> browser.getControl("Add").click()
Now, let's request the download view of the file object and check the
result:
>>> print(http(b"""
... GET /plain.txt/@@download HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, handle_errors=False))
HTTP/1.0 200 Ok
Content-Disposition: attachment; filename="plain.txt"
Content-Length: 9
Content-Type: text/plain;charset=utf-8
<BLANKLINE>
some text
We'll peek into the database to make sure the object implements the
expected MIME type interface:
>>> from zope.mimetype import types
>>> ob = getRootFolder()["plain.txt"]
>>> types.IContentTypeTextPlain.providedBy(ob)
True
We can upload new data into our file object as well:
>>> sio = StringIO(b"new text")
>>> browser.open("http://localhost/plain.txt/@@edit.html")
>>> ctrl = browser.getControl(name="form.data")
>>> ctrl.add_file(
... sio, "text/plain; charset=utf-8", "stuff.txt")
>>> browser.getControl("Edit").click()
Now, let's request the download view of the file object and check the
result:
>>> print(http(b"""
... GET /plain.txt/@@download HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, handle_errors=False))
HTTP/1.0 200 Ok
Content-Disposition: attachment; filename="plain.txt"
Content-Length: 8
Content-Type: text/plain;charset=utf-8
<BLANKLINE>
new text
If we upload a file that has imprecise content type information (as we
expect from browsers generally, and MSIE most significantly), we can
see that the MIME type machinery will improve the information where
possible:
>>> sio = StringIO(b"<?xml version='1.0' encoding='utf-8'?>\n"
... b"<html>...</html>\n")
>>> browser.open("http://localhost/@@+/zope.file.File")
>>> ctrl = browser.getControl(name="form.data")
>>> ctrl.add_file(
... sio, "text/html; charset=utf-8", "simple.html")
>>> browser.getControl("Add").click()
Again, we'll request the download view of the file object and check
the result:
>>> print(http(b"""
... GET /simple.html/@@download HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, handle_errors=False))
HTTP/1.0 200 Ok
Content-Disposition: attachment; filename="simple.html"
Content-Length: 56
Content-Type: application/xhtml+xml;charset=utf-8
<BLANKLINE>
<?xml version='1.0' encoding='utf-8'?>
<html>...</html>
<BLANKLINE>
Further, if a browser is bad and sends a full path as the file name (as
sometimes happens in many browsers, apparently), the name is correctly
truncated and changed.
>>> sio = StringIO(b"<?xml version='1.0' encoding='utf-8'?>\n"
... b"<html>...</html>\n")
>>> browser.open("http://localhost/@@+/zope.file.File")
>>> ctrl = browser.getControl(name="form.data")
>>> ctrl.add_file(
... sio, "text/html; charset=utf-8", r"C:\Documents and Settings\Joe\naughty name.html")
>>> browser.getControl("Add").click()
Again, we'll request the download view of the file object and check
the result:
>>> print(http(b"""
... GET /naughty%20name.html/@@download HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, handle_errors=False))
HTTP/1.0 200 Ok
Content-Disposition: attachment; filename="naughty name.html"
Content-Length: 56
Content-Type: application/xhtml+xml;charset=utf-8
<BLANKLINE>
<?xml version='1.0' encoding='utf-8'?>
<html>...</html>
<BLANKLINE>
In zope.file <= 0.5.0, a redundant ObjectCreatedEvent was fired in the
Upload view. We'll demonstrate that this is no longer the case.
>>> import zope.component
>>> from zope.file.interfaces import IFile
>>> from zope.lifecycleevent import IObjectCreatedEvent
We'll register a subscriber for IObjectCreatedEvent that simply increments
a counter.
>>> count = 0
>>> def inc(*args):
... global count; count += 1
>>> zope.component.provideHandler(inc, (IFile, IObjectCreatedEvent))
>>> browser.open("http://localhost/@@+/zope.file.File")
>>> ctrl = browser.getControl(name="form.data")
>>> sio = StringIO(b"some data")
>>> ctrl.add_file(
... sio, "text/html; charset=utf-8", "name.html")
>>> browser.getControl("Add").click()
The subscriber was called only once.
>>> print(count)
1
| zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/src/zope/file/upload.rst | upload.rst |
==========================
Downloading File Objects
==========================
The file content type provides a view used to download the file,
regardless of the browser's default behavior for the content type.
This relies on browser support for the Content-Disposition header.
The download support is provided by two distinct objects: A view that
provides the download support using the information in the content
object, and a result object that can be used to implement a file
download by other views. The view can override the content-type or the
filename suggested to the browser using the standard IResponse.setHeader
method.
Note that result objects are intended to be used once and then
discarded.
Let's start by creating a file object we can use to demonstrate the
download support:
>>> import transaction
>>> from zope.file.file import File
>>> f = File()
>>> getRootFolder()['file'] = f
>>> transaction.commit()
Headers
=======
Now, let's get the headers for this file. We use a utility function called
``getHeaders``:
>>> from zope.file.download import getHeaders
>>> headers = getHeaders(f, contentDisposition='attachment')
Since there's no suggested download filename on the file, the
Content-Disposition header doesn't specify one, but does indicate that
the response body be treated as a file to save rather than to apply
the default handler for the content type:
>>> sorted(headers)
[('Content-Disposition', 'attachment; filename="file"'),
('Content-Length', '0'),
('Content-Type', 'application/octet-stream')]
Note that a default content type of 'application/octet-stream' is
used.
If the file object specifies a content type, that's used in the headers
by default:
>>> f.mimeType = "text/plain"
>>> headers = getHeaders(f, contentDisposition='attachment')
>>> sorted(headers)
[('Content-Disposition', 'attachment; filename="file"'),
('Content-Length', '0'),
('Content-Type', 'text/plain')]
Alternatively, a content type can be specified to ``getHeaders``:
>>> headers = getHeaders(f, contentType="text/xml",
... contentDisposition='attachment')
>>> sorted(headers)
[('Content-Disposition', 'attachment; filename="file"'),
('Content-Length', '0'),
('Content-Type', 'text/xml')]
The filename provided to the browser can be controlled similarly. If
the content object provides one, it will be used by default:
>>> headers = getHeaders(f, contentDisposition='attachment')
>>> sorted(headers)
[('Content-Disposition', 'attachment; filename="file"'),
('Content-Length', '0'),
('Content-Type', 'text/plain')]
Providing an alternate name to ``getHeaders`` overrides the download
name from the file:
>>> headers = getHeaders(f, downloadName="foo.txt",
... contentDisposition='attachment')
>>> sorted(headers)
[('Content-Disposition', 'attachment; filename="foo.txt"'),
('Content-Length', '0'),
('Content-Type', 'text/plain')]
The default Content-Disposition header can be overridden by providing
an argument to ``getHeaders``:
>>> headers = getHeaders(f, contentDisposition="inline")
>>> sorted(headers)
[('Content-Disposition', 'inline; filename="file"'),
('Content-Length', '0'),
('Content-Type', 'text/plain')]
If the ``contentDisposition`` argument is not provided, none will be
included in the headers:
>>> headers = getHeaders(f)
>>> sorted(headers)
[('Content-Length', '0'),
('Content-Type', 'text/plain')]
Body
====
We use DownloadResult to deliver the content to the browser. Since
there's no data in this file, there are no body chunks:
>>> transaction.commit()
>>> from zope.file.download import DownloadResult
>>> result = DownloadResult(f)
>>> list(result)
[]
We still need to see how non-empty files are handled. Let's write
some data to our file object:
>>> with f.open("w") as w:
... _ = w.write(b"some text")
... w.flush()
>>> transaction.commit()
Now we can create a result object and see if we get the data we
expect:
>>> result = DownloadResult(f)
>>> L = list(result)
>>> b"".join(L)
'some text'
If the body content is really large, the iterator may provide more
than one chunk of data:
>>> with f.open("w") as w:
... _ = w.write(b"*" * 1024 * 1024)
... w.flush()
>>> transaction.commit()
>>> result = DownloadResult(f)
>>> L = list(result)
>>> len(L) > 1
True
Once iteration over the body has completed, further iteration will not
yield additional data:
>>> list(result)
[]
The Download View
=================
Now that we've seen the ``getHeaders`` function and the result object,
let's take a look at the basic download view that uses them. We'll need
to add a file object where we can get to it using a browser:
>>> f = File()
>>> f.mimeType = "text/plain"
>>> with f.open("w") as w:
... _ = w.write(b"some text")
>>> transaction.commit()
>>> getRootFolder()["abcdefg"] = f
>>> transaction.commit()
Now, let's request the download view of the file object and check the
result:
>>> print(http(b"""
... GET /abcdefg/@@download HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, handle_errors=False))
HTTP/1.0 200 Ok
Content-Disposition: attachment; filename="abcdefg"
Content-Length: 9
Content-Type: text/plain
<BLANKLINE>
some text
The Inline View
===============
In addition, it is sometimes useful to view the data inline instead of
downloading it. A basic inline view is provided for this use case.
Note that browsers may decide not to display the image when this view
is used and there is not page that it's being loaded into: if this
view is being referenced directly via the URL, the browser may show
nothing:
>>> print(http(b"""
... GET /abcdefg/@@inline HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, handle_errors=False))
HTTP/1.0 200 Ok
Content-Disposition: inline; filename="abcdefg"
Content-Length: 9
Content-Type: text/plain
<BLANKLINE>
some text
The Default Display View
========================
This view is similar to the download and inline views, but no content
disposition is specified at all. This lets the browser's default
handling of the data in the current context to be applied:
>>> print(http(b"""
... GET /abcdefg/@@display HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, handle_errors=False))
HTTP/1.0 200 Ok
Content-Length: 9
Content-Type: text/plain
<BLANKLINE>
some text
Large Unicode Characters
========================
We need to be able to support Unicode characters in the filename
greater than what Latin-1 (the encoding used by WSGI) can support.
Let's rename a file to contain a high Unicode character and try to
download it; the filename will be encoded:
>>> getRootFolder()["abcdefg"].__name__ = u'Big \U0001F4A9'
>>> transaction.commit()
>>> print(http(b"""
... GET /abcdefg/@@download HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, handle_errors=False))
HTTP/1.0 200 Ok
Content-Disposition: attachment; filename="Big ð©"
Content-Length: 9
Content-Type: text/plain
<BLANKLINE>
some text
| zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/src/zope/file/download.rst | download.rst |
__docformat__ = "reStructuredText"
import zope.interface
import zope.mimetype.interfaces
import zope.publisher.browser
import zope.publisher.interfaces.http
import zope.security.proxy
class Download(zope.publisher.browser.BrowserView):
def __call__(self):
for k, v in getHeaders(self.context, contentDisposition="attachment"):
self.request.response.setHeader(k, v)
return DownloadResult(self.context)
class Inline(zope.publisher.browser.BrowserView):
def __call__(self):
for k, v in getHeaders(self.context, contentDisposition="inline"):
self.request.response.setHeader(k, v)
return DownloadResult(self.context)
class Display(zope.publisher.browser.BrowserView):
def __call__(self):
for k, v in getHeaders(self.context):
self.request.response.setHeader(k, v)
return DownloadResult(self.context)
def getHeaders(context, contentType=None, downloadName=None,
contentDisposition=None, contentLength=None):
if not contentType:
cti = zope.mimetype.interfaces.IContentInfo(context, None)
if cti is not None:
contentType = cti.contentType
contentType = contentType or "application/octet-stream"
headers = ("Content-Type", contentType),
downloadName = downloadName or context.__name__
if contentDisposition:
if downloadName:
# Headers must be native strings. Under Py2, we probably
# need to encode the name
if str is bytes:
if not isinstance(downloadName, bytes):
downloadName = downloadName.encode("utf-8")
else:
# Under Python 3, we need to pass the native string,
# but characters greater than 256 will fail to be encoded
# by the WSGI server, which should be using latin-1. The solution
# is to smuggle them through using double encoding, allowing the
# final recipient to decode its string using utf-8
downloadName = downloadName.encode('utf-8').decode('latin-1')
contentDisposition += (
'; filename="%s"' % downloadName
)
headers += ("Content-Disposition", contentDisposition),
if contentLength is None:
contentLength = context.size
headers += ("Content-Length", str(contentLength)),
return headers
@zope.interface.implementer(zope.publisher.interfaces.http.IResult)
class DownloadResult(object):
"""Result object for a download request."""
def __init__(self, context):
self._iter = bodyIterator(
zope.security.proxy.removeSecurityProxy(context.openDetached()))
def __iter__(self):
return self._iter
CHUNK_SIZE = 64 * 1024
def bodyIterator(f):
try:
while True:
chunk = f.read(CHUNK_SIZE)
if not chunk:
return
yield chunk
finally:
f.close() | zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/src/zope/file/download.py | download.py |
__docformat__ = "reStructuredText"
import re
import zope.contenttype.parse
import zope.component
import zope.event
import zope.file.file
import zope.formlib.form
import zope.schema
from zope.file.i18n import _
from zope.container.interfaces import INameChooser
from zope.mimetype.interfaces import IContentInfo
from zope.mimetype.interfaces import ICodecPreferredCharset
from zope.mimetype.interfaces import ICharsetCodec
from zope.mimetype.interfaces import IContentTypeInterface
from zope.mimetype.interfaces import IContentTypeEncoded
from zope.mimetype.interfaces import IMimeTypeGetter
from zope.mimetype.event import changeContentType
from zope.security.proxy import removeSecurityProxy
from zope.lifecycleevent import ObjectModifiedEvent
_nameFinder = re.compile(r'(.*[\\/:])?(.+)')
def nameFinder(fileob):
name = getattr(fileob, 'filename', None)
if name is None:
return None
match = _nameFinder.match(name)
if match is not None:
match = match.group(2)
return match
class Upload(zope.formlib.form.AddForm):
form_fields = zope.formlib.form.fields(
zope.schema.Bytes(
__name__="data",
title=_("Upload data"),
description=_("Upload file"),
),
)
def create(self, data):
ob = self._create_instance(data)
f = self.request.form["form.data"]
updateBlob(ob, f)
self._name = nameFinder(f)
return ob
def add(self, ob):
if self._name and self.context.nameAllowed():
nc = INameChooser(self.context.context)
name = nc.chooseName(self._name, ob)
self.context.contentName = name
res = super(Upload, self).add(ob)
# We need to slam on an interface based on the effective MIME type;
# start by getting the IContentInfo for ob:
ci = IContentInfo(ob, None)
if ci is not None and ci.effectiveMimeType:
# we might have *something*
iface = zope.component.queryUtility(
IContentTypeInterface,
ci.effectiveMimeType)
if iface is not None:
changeContentType(ob, iface)
return res
def _create_instance(self, data):
return zope.file.file.File()
class Reupload(zope.formlib.form.Form):
form_fields = zope.formlib.form.Fields(
zope.schema.Bytes(
__name__="data",
title=_("Upload data"),
description=_("Upload file to replace the current data"),
),
)
@zope.formlib.form.action(_("Edit"))
def upload(self, action, data):
context = self.context
old_codec = None
if "charset" in context.parameters:
old_codec = zope.component.queryUtility(
ICharsetCodec,
context.parameters["charset"])
if data.get("data") is not None:
updateBlob(context, self.request.form["form.data"])
# update the encoding, but only if the new content type is encoded
encoded = IContentTypeEncoded.providedBy(context)
if encoded and "charset" in context.parameters:
codec = zope.component.queryUtility(
ICharsetCodec,
context.parameters["charset"])
if codec and getattr(old_codec, "name", None) != codec.name:
# use the preferred charset for the new codec
new_charset = zope.component.getUtility(
ICodecPreferredCharset,
codec.name)
parameters = dict(context.parameters)
parameters["charset"] = new_charset.name
context.parameters = parameters
# these subscribers generally expect an unproxied object.
zope.event.notify(ObjectModifiedEvent(removeSecurityProxy(context)))
def updateBlob(ob, input):
# Bypass the widget machinery for now; we'd rather have a blob
# widget that exposes the interesting information from the
# upload.
f = input
# We need to seek back since the form machinery has already
# read all the data :-(
f.seek(0)
data = f.read()
contentType = f.headers.get("Content-Type")
mimeTypeGetter = zope.component.getUtility(IMimeTypeGetter)
mimeType = mimeTypeGetter(data=data, content_type=contentType,
name=nameFinder(f))
if not mimeType:
mimeType = "application/octet-stream"
if contentType:
_major, _minor, parameters = zope.contenttype.parse.parse(
contentType)
if "charset" in parameters:
parameters["charset"] = parameters["charset"].lower()
ob.mimeType = mimeType
ob.parameters = parameters
else:
ob.mimeType = mimeType
ob.parameters = {}
w = ob.open("w")
try:
# if we're security proxied, may not be able to use a `with`
w.write(data)
finally:
w.close() | zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/src/zope/file/upload.py | upload.py |
====================================
Content type and encoding controls
====================================
Files provide a view that supports controlling the MIME content type
and, where applicable, the content encoding. Content encoding is
applicable based on the specific content type of the file.
Let's demonstrate the behavior of the form with a simple bit of
content. We'll upload a bit of HTML as a sample document:
>>> from io import BytesIO
>>> sio = BytesIO(b"A <sub>little</sub> HTML."
... b" There's one 8-bit Latin-1 character: \xd8.")
>>> from zope.testbrowser.wsgi import Browser
>>> browser = Browser()
>>> browser.handleErrors = False
>>> browser.addHeader("Authorization", "Basic mgr:mgrpw")
>>> browser.addHeader("Accept-Language", "en-US")
>>> browser.open("http://localhost/@@+/zope.file.File")
>>> ctrl = browser.getControl(name="form.data")
>>> ctrl.add_file(
... sio, "text/html", "sample.html")
>>> browser.getControl("Add").click()
We can see that the MIME handlers have marked this as HTML content:
>>> import zope.mimetype.interfaces
>>> import zope.mimetype.mtypes
>>> file = getRootFolder()[u"sample.html"]
>>> zope.mimetype.mtypes.IContentTypeTextHtml.providedBy(file)
True
It's important to note that this also means the content is encoded
text:
>>> zope.mimetype.interfaces.IContentTypeEncoded.providedBy(file)
True
The "Content Type" page will show us the MIME type and encoding that
have been selected:
>>> browser.getLink("sample.html").click()
>>> browser.getLink("Content Type").click()
>>> browser.getControl(name="form.mimeType").value
['zope.mimetype.mtypes.IContentTypeTextHtml']
The empty string value indicates that we have no encoding
information:
>>> ctrl = browser.getControl(name="form.encoding")
>>> print(ctrl.value)
['']
Let's now set the encoding value to an old favorite, Latin-1:
>>> ctrl.value = ["iso-8859-1"]
>>> browser.handleErrors = False
>>> browser.getControl("Save").click()
We now see the updated value in the form, and can check the value in
the MIME content-type parameters on the object:
>>> ctrl = browser.getControl(name="form.encoding")
>>> print(ctrl.value)
['iso-8859-1']
>>> file = getRootFolder()["sample.html"]
>>> file.parameters
{'charset': 'iso-8859-1'}
Something more interesting is that we can now use a non-encoded
content type, and the encoding field will be removed from the form:
>>> ctrl = browser.getControl(name="form.mimeType")
>>> ctrl.value = ["zope.mimetype.mtypes.IContentTypeImageTiff"]
>>> browser.getControl("Save").click()
>>> browser.getControl(name="form.encoding")
Traceback (most recent call last):
...
LookupError: name 'form.encoding'
...
If we switch back to an encoded type, we see that our encoding wasn't
lost:
>>> ctrl = browser.getControl(name="form.mimeType")
>>> ctrl.value = ["zope.mimetype.mtypes.IContentTypeTextHtml"]
>>> browser.getControl("Save").click()
>>> browser.getControl(name="form.encoding").value
['iso-8859-1']
On the other hand, if we try setting the encoding to something which
simply cannot decode the input data, we get an error message saying
that's not going to work, and no changes are saved:
>>> ctrl = browser.getControl(name="form.encoding")
>>> ctrl.value = ["utf-8"]
>>> browser.getControl("Save").click()
>>> print(browser.contents)
<...Selected encoding cannot decode document...
| zope.file | /zope.file-1.2.0.tar.gz/zope.file-1.2.0/src/zope/file/contenttype.rst | contenttype.rst |
=========
Changes
=========
6.0 (2023-01-14)
================
- Drop support for Python 2.7, 3.5, 3.6.
- Add support for Python 3.9, 3.10, 3.11.
5.0.0 (2020-03-31)
==================
- Drop support for Python 3.4.
- Add support for Python 3.7 and 3.8.
- Ensure all objects have a consistent interface resolution order.
See `issue 7 <https://github.com/zopefoundation/zope.filerepresentation/issues/7>`_.
4.2.0 (2017-08-10)
==================
- Add support for Python 3.5 and 3.6.
- Drop support for Python 2.6 and 3.3.
4.1.0 (2014-12-27)
==================
- Add support for PyPy3.
- Add support for Python 3.4.
4.0.2 (2013-03-08)
==================
- Add Trove classifiers indicating CPython and PyPy support.
4.0.1 (2013-02-11)
==================
- Add tox.ini to release.
4.0.0 (2013-02-11)
==================
- Add support for Python 3.3 and PyPy.
- Drop support for Python 2.4 / 2.5.
3.6.1 (2011-11-29)
==================
- Add undeclared ``zope.schema`` dependency.
- Remove ``zope.testing`` test dependency and ``test`` extra.
3.6.0 (2009-10-08)
==================
- Add ``IRawReadFile`` and ``IRawWriteFile`` interfaces. These extend
``IReadFile`` and ``IWritefile``, respectively, to behave pretty much like a
standard Python file object with a few embellishments. This in turn allows
efficient, iterator- based implementations of file reading and writing.
- Remove dependency on ``zope.container``: ``IReadDirectory`` and
``IWriteDirectory`` inherit only from interfaces defined in ``zope.interface``
and ``zope.interface.common.mapping``.
3.5.0 (2009-01-31)
==================
- Change use of ``zope.app.container`` to ``zope.container``.
3.4.0 (2007-10-02)
==================
- Initial Zope-independent release.
| zope.filerepresentation | /zope.filerepresentation-6.0.tar.gz/zope.filerepresentation-6.0/CHANGES.rst | CHANGES.rst |
=============================
``zope.filerepresentation``
=============================
.. image:: https://img.shields.io/pypi/v/zope.filerepresentation.svg
:target: https://pypi.python.org/pypi/zope.filerepresentation/
:alt: Latest release
.. image:: https://img.shields.io/pypi/pyversions/zope.filerepresentation.svg
:target: https://pypi.org/project/zope.filerepresentation/
:alt: Supported Python versions
.. image:: https://github.com/zopefoundation/zope.filerepresentation/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/zope.filerepresentation/actions/workflows/tests.yml
.. image:: https://coveralls.io/repos/github/zopefoundation/zope.filerepresentation/badge.svg?branch=master
:target: https://coveralls.io/github/zopefoundation/zope.filerepresentation?branch=master
.. image:: https://readthedocs.org/projects/zopefilerepresentation/badge/?version=latest
:target: https://zopefilerepresentation.readthedocs.io/en/latest/
:alt: Documentation Status
The interfaces defined here are used for file-system and file-system-like
representations of objects, such as file-system synchronization, FTP, PUT, and
WebDAV.
Documentation is hosted at https://zopefilerepresentation.readthedocs.io/
| zope.filerepresentation | /zope.filerepresentation-6.0.tar.gz/zope.filerepresentation-6.0/README.rst | README.rst |
__docformat__ = 'restructuredtext'
# Pylint helpfully catches class definition errors, but they don't apply to
# interfaces.
# pylint:disable=inherit-non-class,no-method-argument,no-self-argument
# pylint:disable=unexpected-special-method-signature
from zope.interface import Interface
from zope.interface.common.mapping import IEnumerableMapping
from zope import schema
class IReadFile(Interface):
"""Provide read access to file data
"""
def read():
"""Return the file data
"""
def size():
"""Return the data length in bytes.
"""
class IWriteFile(Interface):
"""Provide write access to file data."""
def write(data):
"""Update the file data
"""
class ICommonFileOperations(Interface):
"""Common file operations used by :class:`IRawReadFile` and
:class:`IRawWriteFile`
"""
mimeType = schema.ASCIILine(
title="File MIME type",
description=("Provided if it makes sense for this file data. "
"May be set prior to writing data to a file that "
"is writeable. It is an error to set this on a "
"file that is not writable."),
readonly=True,
)
encoding = schema.Bool(
title="The encoding that this file uses",
description=("Provided if it makes sense for this file data. "
"May be set prior to writing data to a file that "
"is writeable. It is an error to set this on a "
"file that is not writable."),
required=False,
)
closed = schema.Bool(
title="Is the file closed?",
required=True,
)
name = schema.TextLine(
title="A representative file name",
description=("Provided if it makes sense for this file data. "
"May be set prior to writing data to a file that "
"is writeable. It is an error to set this on a "
"file that is not writable."),
required=False,
)
def seek(offset, whence=None):
"""Seek the file. See Python documentation for :class:`io.IOBase` for
details.
"""
def tell():
"""Return the file's current position.
"""
def close():
"""Close the file. See Python documentation for :class:`io.IOBase` for
details.
"""
class IRawReadFile(IReadFile, ICommonFileOperations):
"""Specialisation of IReadFile to make it act more like a Python file
object.
"""
def read(size=None):
"""Read at most ``size`` bytes of file data. If ``size`` is None,
return all the file data.
"""
def readline(size=None):
"""Read one entire line from the file. See Python documentation for
:class:`io.IOBase` for details.
"""
def readlines(sizehint=None):
"""Read until EOF using readline() and return a list containing the
lines thus read. See Python documentation for :class:`io.IOBase` for
details.
"""
def __iter__():
"""Return an iterator for the file.
Note that unlike a Python standard :class:`file`, this does not
necessarily have to return data line-by-line if doing so is
inefficient.
"""
def next():
"""Iterator protocol. See Python documentation for :class:`io.IOBase`
for details.
"""
class IRawWriteFile(IWriteFile, ICommonFileOperations):
"""Specialisation of IWriteFile to make it act more like a Python file
object.
"""
def write(data):
"""Write a chunk of data to the file. See Python documentation for
:class:`io.RawIOBase` for details.
"""
def writelines(sequence):
"""Write a sequence of strings to the file. See Python documentation
for :class:`io.IOBase` for details.
"""
def truncate(size):
"""Truncate the file. See Python documentation for :class:`io.IOBase`
for details.
"""
def flush():
"""Flush the file. See Python documentation for :class:`io.IOBase` for
details.
"""
class IReadDirectory(IEnumerableMapping):
"""Objects that should be treated as directories for reading
"""
class IWriteDirectory(Interface):
"""Objects that should be treated as directories for writing
"""
def __setitem__(name, object): # pylint:disable=redefined-builtin
"""Add the given *object* to the directory under the given name."""
def __delitem__(name):
"""Delete the named object from the directory."""
class IDirectoryFactory(Interface):
"""Factory for :class:`IReadDirectory`/:class:`IWriteDirectory` objects."""
def __call__(name): # pylint:disable=signature-differs
"""Create a directory
where a directory is an object with adapters to IReadDirectory
and IWriteDirectory.
"""
class IFileFactory(Interface):
"""Factory for :class:`IReadFile`/:class:`IWriteFile` objects."""
def __call__(name, content_type, data): # pylint:disable=signature-differs
"""Create a file
where a file is an object with adapters to `IReadFile`
and `IWriteFile`.
The file `name`, content `type`, and `data` are provided to help
create the object.
"""
# TODO: we will add additional interfaces for WebDAV and File-system
# synchronization. | zope.filerepresentation | /zope.filerepresentation-6.0.tar.gz/zope.filerepresentation-6.0/src/zope/filerepresentation/interfaces.py | interfaces.py |
Introduction
============
Fixers for Zope Component Architecture and the frameworks built with it.
Currently, there is only one fixer, fix_implements. This fixer will change
all uses of implements(IFoo) in a class body to the class decorator
@implementer(IFoo), which is the most likely Python 3 syntax for
zope.interfaces implements statements.
Usage
-----
Typically you will use zope.fixers together with Distribute's 2to3 support.
This is done by adding zope.fixers to some parameters in setup():
>>> setup(
... install_requires = ['zope.fixers'],
... use_2to3 = True,
... use_2to3_fixers = ['zope.fixers'],
... )
For an example usage of a complex case, look at:
http://svn.zope.org/zope.interface/branches/regebro-python3/setup.py?rev=106216&view=markup
That setup.py supports both distutils, setuptools and distribute, all versions
of python from 2.4 to 3.1, and has an optional C-extension, so don't worry if
it's overwhelming. For simple projects all you need is to use Distribute and
add the above three lines to the setup.py. Distribute has more documentation
on how to use it to support Python 3 porting.
If you don't want to use Distribute things get a bit more complex, as you have
to make the list of fixers yourself and call lib2to3 with that:
>>> from lib2to3.refactor import RefactoringTool, get_fixers_from_package
>>> fixers = get_fixers_from_package('lib2to3.fixes') + \
... get_fixers_from_package('zope.fixers')
And the run the fixing with the fixers:
>>> tool = RefactoringTool(fixers)
>>> tool.refactor(files, write=True)
Fixer Script
------------
The package also provides a console script called `zope-2to3` that has the
same arguments as `2to3` but applies the fixers defined in this package.
| zope.fixers | /zope.fixers-1.1.2.zip/zope.fixers-1.1.2/README.txt | README.txt |
import os, shutil, sys, tempfile
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
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", help="use a specific zc.buildout version")
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", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
options, args = parser.parse_args()
######################################################################
# load/install distribute
to_reload = False
try:
import pkg_resources, setuptools
if not hasattr(pkg_resources, '_distribute'):
to_reload = True
raise ImportError
except ImportError:
ez = {}
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
exec(urlopen('http://python-distribute.org/distribute_setup.py').read(), ez)
setup_args = dict(to_dir=tmpeggs, download_delay=0, no_fake=True)
ez['use_setuptools'](**setup_args)
if to_reload:
reload(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)
######################################################################
# Install buildout
ws = pkg_resources.working_set
cmd = [sys.executable, '-c',
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
distribute_path = ws.find(
pkg_resources.Requirement.parse('distribute')).location
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=[distribute_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)
import subprocess
if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=distribute_path)) != 0:
raise Exception(
"Failed to execute command:\n%s",
repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs) | zope.fixers | /zope.fixers-1.1.2.zip/zope.fixers-1.1.2/bootstrap.py | bootstrap.py |
# Local imports
from lib2to3.fixer_base import BaseFix
from lib2to3.patcomp import PatternCompiler
from lib2to3.fixer_util import syms, Name
from lib2to3.fixer_util import Node, Leaf
class Function2DecoratorBase(BaseFix):
IMPORT_PATTERN = """
import_from< 'from' dotted_name< 'zope' '.' 'interface' > 'import' import_as_names< any* (name='%(function_name)s') any* > >
|
import_from< 'from' dotted_name< 'zope' '.' 'interface' > 'import' name='%(function_name)s' any* >
|
import_from< 'from' dotted_name< 'zope' > 'import' name='interface' any* >
|
import_from< 'from' dotted_name< 'zope' '.' 'interface' > 'import' import_as_name< name='%(function_name)s' 'as' rename=(any) any*> >
|
import_from< 'from' dotted_name< 'zope' > 'import' import_as_name< name='interface' 'as' rename=(any) any*> >
|
import_from< 'from' 'zope' 'import' import_as_name< 'interface' 'as' interface_rename=(any) > >
"""
CLASS_PATTERN = """
decorated< decorator <any* > classdef< 'class' any* ':' suite< any* simple_stmt< power< statement=(%(match)s) trailer < '(' interface=any ')' > any* > any* > any* > > >
|
classdef< 'class' any* ':' suite< any* simple_stmt< power< statement=(%(match)s) trailer < '(' interface=any ')' > any* > any* > any* > >
"""
FUNCTION_PATTERN = """
simple_stmt< power< old_statement=(%s) trailer < '(' any* ')' > > any* >
"""
def should_skip(self, node):
module = str(node)
return not ('zope' in module and 'interface' in module)
def compile_pattern(self):
# Compile the import pattern.
self.named_import_pattern = PatternCompiler().compile_pattern(
self.IMPORT_PATTERN % {'function_name': self.FUNCTION_NAME})
def start_tree(self, tree, filename):
# Compile the basic class/function matches. This is done per tree,
# as further matches (based on what imports there are) also are done
# per tree.
self.class_patterns = []
self.function_patterns = []
self.fixups = []
self._add_pattern("'%s'" % self.FUNCTION_NAME)
self._add_pattern("'interface' trailer< '.' '%s' >" % self.FUNCTION_NAME)
self._add_pattern("'zope' trailer< '.' 'interface' > trailer< '.' '%s' >" % self.FUNCTION_NAME)
def _add_pattern(self, match):
self.class_patterns.append(PatternCompiler().compile_pattern(
self.CLASS_PATTERN % {'match': match}))
self.function_patterns.append(PatternCompiler().compile_pattern(
self.FUNCTION_PATTERN % match))
def match(self, node):
# Matches up the imports
results = {"node": node}
if self.named_import_pattern.match(node, results):
return results
# Now match classes on all import variants found:
for pattern in self.class_patterns:
if pattern.match(node, results):
return results
def transform(self, node, results):
if 'name' in results:
# This matched an import statement. Fix that up:
name = results["name"]
name.replace(Name(self.DECORATOR_NAME, prefix=name.prefix))
if 'rename' in results:
# The import statement use import as
self._add_pattern("'%s'" % results['rename'].value)
if 'interface_rename' in results:
self._add_pattern("'%s' trailer< '.' '%s' > " % (
results['interface_rename'].value, self.FUNCTION_NAME))
if 'statement' in results:
# This matched a class that has an <FUNCTION_NAME>(IFoo) statement.
# We must convert that statement to a class decorator
# and put it before the class definition.
statement = results['statement']
if not isinstance(statement, list):
statement = [statement]
# Make a copy for insertion before the class:
statement = [x.clone() for x in statement]
# Get rid of leading whitespace:
statement[0].prefix = ''
# Rename function to decorator:
if statement[-1].children:
func = statement[-1].children[-1]
else:
func = statement[-1]
if func.value == self.FUNCTION_NAME:
func.value = self.DECORATOR_NAME
interface = results['interface']
if not isinstance(interface, list):
interface = [interface]
interface = [x.clone() for x in interface]
# Create the decorator:
decorator = Node(syms.decorator, [Leaf(50, '@'),] + statement +
[Leaf(7, '(')] + interface + [Leaf(8, ')')])
# Take the current class constructor prefix, and stick it into
# the decorator, to set the decorators indentation.
nodeprefix = node.prefix
decorator.prefix = nodeprefix
# Preserve only the indent:
if '\n' in nodeprefix:
nodeprefix = nodeprefix[nodeprefix.rfind('\n')+1:]
# Then find the last line of the previous node and use that as
# indentation, and add that to the class constructors prefix.
previous = node.prev_sibling
if previous is None:
prefix = ''
else:
prefix = str(previous)
if '\n' in prefix:
prefix = prefix[prefix.rfind('\n')+1:]
prefix = prefix + nodeprefix
if not prefix or prefix[0] != '\n':
prefix = '\n' + prefix
node.prefix = prefix
new_node = Node(syms.decorated, [decorator, node.clone()])
# Look for the actual function calls in the new node and remove it.
for node in new_node.post_order():
for pattern in self.function_patterns:
if pattern.match(node, results):
parent = node.parent
previous = node.prev_sibling
# Remove the node
node.remove()
if not str(parent).strip():
# This is an empty class. Stick in a pass
if (len(parent.children) < 3 or
' ' in parent.children[2].value):
# This class had no body whitespace.
parent.insert_child(2, Leaf(0, ' pass'))
else:
# This class had body whitespace already.
parent.insert_child(2, Leaf(0, 'pass'))
parent.insert_child(3, Leaf(0, '\n'))
elif (prefix and isinstance(previous, Leaf) and
'\n' not in previous.value and
previous.value.strip() == ''):
# This is just whitespace, remove it:
previous.remove()
return new_node | zope.fixers | /zope.fixers-1.1.2.zip/zope.fixers-1.1.2/zope/fixers/base.py | base.py |
=========
Changes
=========
6.0 (2023-03-27)
================
- Add support for Python 3.11.
- Drop support for Python 2.7, 3.5, 3.6.
5.0.1 (2021-10-25)
==================
- Add support for Python 3.10.
5.0.0 (2021-10-25)
==================
Possibly breaking changes
-------------------------
- Fix checking of constraints on field contents. The ``prefix`` of an
``IFormField`` can still be empty and now officially allows dots.
See `pull request 35
<https://github.com/zopefoundation/zope.formlib/pull/35>`_.
Features
--------
- Add support for Python 3.9.
Other changes
-------------
- Remove unused non-BBB imports.
- Adjust checkbox widget test to new default for ``required`` on boolean
fields.
4.7.1 (2020-03-31)
==================
- Ensure all objects have consistent interface resolution orders.
See `issue 30
<https://github.com/zopefoundation/zope.formlib/issues/30>`_.
- Remove support for deprecated ``python setup.py test`` command.
4.7.0 (2020-02-27)
==================
- Move inline javascript function definitions containing "<", ">" or "&"
into external files to follow the XHTML recommendation concerning
XML/HTML compatibility
(`#25 <https://github.com/zopefoundation/zope.formlib/issues/25>`_)
- Add support for Python 3.8.
- Drop support for Python 3.4.
4.6.0 (2019-02-12)
==================
- Add support for Python 3.7.
- Make the tests compatible with ``zope.i18n >= 4.5``.
4.5.0 (2018-09-27)
==================
- Fix IE issue in /@@user-information?user_id=TestUser for
orderedSelectionList (GH#17)
- Move documentation to https://zopeformlib.readthedocs.io
4.4.0 (2017-08-15)
==================
- Add support for Python 3.5, and 3.6.
- Drop support for Python 2.6 and 3.3.
- Use ``UTF-8`` as default encoding when casting bytes to unicode for Python 2
*and* 3.
4.3.0 (2014-12-24)
==================
- Add support for PyPy. (PyPy3 is pending release of a fix for:
https://bitbucket.org/pypy/pypy/issue/1946)
- Add support for Python 3.4.
- Add support for testing on Travis.
- Explicitly hide span in ``orderedSelectionList.pt``. This only
contains hidden inputs, but Internet Explorer 10 was showing them
anyway.
- Support for CSRF protection.
- Added support for restricting the acceptable request method for the
form submit.
4.3.0a1 (2013-02-27)
====================
- Added support for Python 3.3.
4.2.1 (2013-02-22)
==================
- Moved default values for the ``BooleanDisplayWidget`` from module to class
definition to make them changeable in instance.
4.2.0 (2012-11-27)
==================
- LP #1017884: Add redirect status codes (303, 307) to the set which prevent
form rendering.
- Replaced deprecated ``zope.component.adapts`` usage with equivalent
``zope.component.adapter`` decorator.
- Replaced deprecated ``zope.interface.implements`` usage with equivalent
``zope.interface.implementer`` decorator.
- Dropped support for Python 2.5.
- Make separator of ``SourceSequenceDisplayWidget`` configurable.
4.1.1 (2012-03-16)
==================
- Added `ignoreContext` attribute to form classes to control whether
`checkInvariants` takes the context of the form into account when
checking interface invariants.
By default `ignoreContext` is set to ``False``. On the `AddForm` it is
``True`` by default because the context of this form is naturally not
suitable as context for the interface invariant.
4.1.0 (2012-03-15)
==================
- `checkInvariants` now takes the context of the form into account when
checking interface invariants.
- Tests are no longer compatible with Python 2.4.
4.0.6 (2011-08-20)
==================
- Fixed bug in ``orderedSelectionList.pt`` template.
4.0.5 (2010-09-16)
==================
- Fixed Action name parameter handling, since 4.0.3 all passed names were
lowercased.
4.0.4 (2010-07-06)
==================
- Fixed tests to pass under Python 2.7.
- Fix validation of "multiple" attributes in orderedSelectionList.pt.
4.0.3 (2010-05-06)
==================
- Keep Actions from raising exceptions when passed Unicode lables [LP:528468].
- Improve display of the "nothing selected" case for optional Choice fields
[LP:269782].
- Improve truth testing for ItemDisplayWidget [LP:159232].
- Don't blow up if TypeError raised during token conversion [LP:98491].
4.0.2 (2010-03-07)
==================
- Adapted tests for Python 2.4 (enforce sorting for short pprint output)
4.0.1 (2010-02-21)
==================
- Documentation uploaded to PyPI now contains widget documentation.
- Escape MultiCheckBoxWidget content [LP:302427].
4.0 (2010-01-08)
================
- Widget implementation and all widgets from zope.app.form have been
moved into zope.formlib, breaking zope.formlib's dependency on
zope.app.form (instead zope.app.form now depends on zope.formlib).
Widgets can all be imported from ``zope.formlib.widgets``.
Widget base classes and render functionality is in
``zope.formlib.widget``.
All relevant widget interfaces are now in ``zope.formlib.interfaces``.
3.10.0 (2009-12-22)
===================
- Use named template from zope.browserpage in favor of zope.app.pagetemplate.
3.9.0 (2009-12-22)
==================
- Use ViewPageTemplateFile from zope.browserpage.
3.8.0 (2009-12-22)
==================
- Adjusted test output to new zope.schema release.
3.7.0 (2009-12-18)
==================
- Rid ourselves from zope.app test dependencies.
- Fix: Button label needs escaping
3.6.0 (2009-05-18)
==================
- Remove deprecated imports.
- Remove dependency on zope.app.container (use ``IAdding`` from
``zope.browser.interfaces``) instead. Depend on
``zope.browser>=1.1`` (the version with ``IAdding``).
- Moved ``namedtemplate`` to ``zope.app.pagetemplate``, to cut some
dependencies on ``zope.formlib`` when using this feature. Left BBB
imports here.
3.5.2 (2009-02-21)
==================
- Adapt tests for Python 2.5 output.
3.5.1 (2009-01-31)
==================
- Adapt tests to upcoming zope.schema release 3.5.1.
3.5.0 (2009-01-26)
==================
New Features
------------
- Test dependencies are declared in a `test` extra now.
- Introduced ``zope.formlib.form.applyData`` which works like
``applyChanges`` but returns a dictionary with information about
which attribute of which schema changed. This information is then
sent along with the ``IObjectModifiedEvent``.
This fixes https://bugs.launchpad.net/zope3/+bug/98483.
Bugs Fixed
----------
- Actions that cause a redirect (301, 302) do not cause the `render` method to
be called anymore.
- The zope.formlib.form.Action class didn't fully implement
zope.formlib.interfaces.IAction.
- zope.formlib.form.setupWidgets and zope.formlib.form.setupEditWidgets did
not check for write access on the adapter but on context. This fixes
https://bugs.launchpad.net/zope3/+bug/219948
3.4.0 (2007-09-28)
==================
No further changes since 3.4.0a1.
3.4.0a1 (2007-04-22)
====================
Initial release as a separate project, corresponds to zope.formlib
from Zope 3.4.0a1
| zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/CHANGES.rst | CHANGES.rst |
==============
zope.formlib
==============
.. image:: https://github.com/zopefoundation/zope.formlib/actions/workflows/tests.yml/badge.svg
:target: https://github.com/zopefoundation/zope.formlib/actions/workflows/tests.yml
.. image:: https://readthedocs.org/projects/zopeformlib/badge/?version=latest
:target: https://zopeformlib.readthedocs.io/en/latest/
:alt: Documentation Status
Forms are web components that use widgets to display and input data.
Typically a template displays the widgets by accessing an attribute or
method on an underlying class.
Documentation is hosted at https://zopeformlib.readthedocs.io/en/latest/
| zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/README.rst | README.rst |
=================
Browser Widgets
=================
.. currentmodule:: zope.formlib.interfaces
Formlib defines widgets: views on bound schema fields. Many of these
are straightforward. For instance, see the `.TextWidget` in
textwidgets.py, which is a subclass of `.BrowserWidget` in widget.py.
It is registered as an
`zope.publisher.interfaces.browser.IBrowserRequest` view of an
`zope.schema.interfaces.ITextLine` schema field, providing the
`IInputWidget` interface::
<view
type="zope.publisher.interfaces.browser.IBrowserRequest"
for="zope.schema.interfaces.ITextLine"
provides="zope.formlib.interfaces.IInputWidget"
factory=".TextWidget"
permission="zope.Public"
/>
The widget then receives the field and the request as arguments to the factory
(i.e., the `.TextWidget` class).
Some widgets in formlib extend this pattern. The widget registration
is extended for `zope.schema.Choice` fields and for the ``collection`` fields.
Default Choice Field Widget Registration and Lookup
===================================================
All field widgets are obtained by looking up a browser `IInputWidget`
or `IDisplayWidget` view for the field object. For `zope.schema.Choice` fields,
the default registered widget defers all of its behavior to the result
of another lookup: a browser widget view for the field *and* the
Choice field's vocabulary.
This allows registration of Choice widgets that differ on the basis of
the vocabulary type. For example, a widget for a vocabulary of images
might have a significantly different user interface than a widget for
a vocabulary of words. A dynamic vocabulary might implement
`zope.schema.interfaces.IIterableVocabulary` if its contents are below
a certain length, but not implement the marker "iterable" interface if
the number of possible values is above the threshhold.
This also means that choice widget factories are called with with an additional
argument. Rather than being called with the field and the request as
arguments, choice widgets receive the field, vocabulary, and request as
arguments.
Some `zope.schema.Choice` widgets may also need to provide a source interface,
particularly if the vocabulary is too big to iterate over.
Default Collection Field Widget Registration and Lookup
=======================================================
The default configured lookup for collection fields -- List, Tuple, and Set, for
instance -- begins with the usual lookup for a browser widget view for the
field object. This widget defers its display to the result of another lookup:
a browser widget view registered for the field and the field's ``value_type``
(the type of the contained values). This allows registrations for collection
widgets that differ on the basis of the members -- a widget for entering a list
of text strings might differ significantly from a widget for entering a list of
dates...or even a list of choices, as discussed below.
This registration pattern has three implications that should be highlighted.
* First, collection fields that do not specify a ``value_type`` probably cannot
have a reasonable widget.
* Second, collection widgets that wish to be the default widget for a
collection with any ``value_type`` should be registered for the
collection field and a generic value_type: the
`zope.schema.interfaces.IField` interface. Do not register the
generic widget for the collection field only or you will break the
lookup behavior as described here.
* Third, like choice widget factories, sequence widget factories (classes or
functions) take three arguments. Typical sequence widgets receive the
field, the ``value_type``, and the request as arguments.
Collections of Choices
----------------------
If a collection field's ``value_type`` is a `zope.schema.Choice` field, the second widget
again defers its behavior, this time to a third lookup based on the collection
field and the choice's vocabulary. This means that a widget for a list of
large image choices can be different than a widget for a list of small image
choices (with a different vocabulary interface), different from a widget for a
list of keyword choices, and different from a set of keyword choices.
Some advanced applications may wish to do a further lookup on the basis of the
unique attribute of the collection field--perhaps looking up a named view with
a "unique" or "lenient" token depending on the field's value, but this is not
enabled in the default Zope 3 configuration.
Registering Widgets for a New Collection Field Type
---------------------------------------------------
Because of this lookup pattern, basic widget registrations for new field types
must follow a recipe. For example, a developer may introduce a new Bag field
type for simple shopping cart functionality and wishes to add widgets for it
within the default Zope 3 collection widget registration. The bag widgets
should be registered something like this.
The only hard requirement is that the developer must register the bag + choice
widget: the widget is just the factory for the third dispatch as described
above, so the developer can use the already implemented widgets listed below::
<view
type="zope.publisher.interfaces.browser.IBrowserRequest"
for="zope.schema.interfaces.IBag
zope.schema.interfaces.IChoice"
provides="zope.formlib.interfaces.IDisplayWidget"
factory=".ChoiceCollectionDisplayWidget"
permission="zope.Public"
/>
<view
type="zope.publisher.interfaces.browser.IBrowserRequest"
for="zope.schema.interfaces.IBag
zope.schema.interfaces.IChoice"
provides="zope.formlib.interfaces.IInputWidget"
factory=".ChoiceCollectionInputWidget"
permission="zope.Public"
/>
Beyond this, the developer may also have a generic bag widget she wishes to
register. This might look something like this, assuming there's a
``BagSequenceWidget`` available in this package::
<view
type="zope.publisher.interfaces.browser.IBrowserRequest"
for="zope.schema.interfaces.IBag
zope.schema.interfaces.IField"
provides="zope.formlib.interfaces.IInputWidget"
factory=".BagSequenceWidget"
permission="zope.Public"
/>
Then any widgets for the bag and a vocabulary would be registered according to
this general pattern, in which `zope.schema.interfaces.IIterableVocabulary` would be the interface of
any appropriate vocabulary and ``BagWidget`` is some appropriate widget::
<view
type="zope.publisher.interfaces.browser.IBrowserRequest"
for="zope.schema.interfaces.IBag
zope.schema.interfaces.IIterableVocabulary"
provides="zope.formlib.interfaces.IInputWidget"
factory=".BagWidget"
permission="zope.Public"
/>
Choice widgets and the missing value
====================================
Choice widgets for a non-required field include a "no value" item to allow for
not selecting any value at all. This value used to be omitted for required
fields on the assumption that the widget should avoid invalid input from the
start.
However, if the context object doesn't yet have a field value set and there's
no default value, a dropdown widget would have to select an arbitrary value
due to the way it is displayed in the browser. This way, the field would
always validate, but possibly with a value the user never chose consciously.
Starting with version zope.app.form 3.6.0, dropdown widgets for
required fields display a "no value" item even for required fields if
an arbitrary value would have to be selected by the widget otherwise.
To switch the old behaviour back on for backwards compatibility, do::
zope.formlib.itemswidgets.EXPLICIT_EMPTY_SELECTION = False
during application start-up.
| zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/widgets.rst | widgets.rst |
import binascii
import datetime
import os
import re
import sys
from html import escape
import pytz
import zope.browser.interfaces
import zope.event
import zope.i18n
import zope.i18nmessageid
import zope.interface.interfaces
import zope.publisher.browser
import zope.publisher.interfaces.browser
import zope.security
from zope.browserpage import ViewPageTemplateFile
from zope.browserpage import namedtemplate
from zope.i18nmessageid import MessageFactory
from zope.interface.common import idatetime
from zope.interface.interface import InterfaceClass
from zope.lifecycleevent import Attributes
from zope.lifecycleevent import ObjectCreatedEvent
from zope.lifecycleevent import ObjectModifiedEvent
from zope.publisher.interfaces.http import MethodNotAllowed
from zope.schema.interfaces import IField
from zope.schema.interfaces import ValidationError
from zope import component
from zope import interface
from zope import schema
from zope.formlib import interfaces
from zope.formlib.interfaces import IDisplayWidget
from zope.formlib.interfaces import IInputWidget
from zope.formlib.interfaces import InputErrors
from zope.formlib.interfaces import InvalidCSRFTokenError
from zope.formlib.interfaces import IWidgetInputErrorView
from zope.formlib.interfaces import WidgetInputError
_ = MessageFactory("zope")
interface.moduleProvides(interfaces.IFormAPI)
def expandPrefix(prefix):
"""Expand prefix string by adding a trailing period if needed.
expandPrefix(p) should be used instead of p+'.' in most contexts.
"""
if prefix and not prefix.endswith('.'):
return prefix + '.'
return prefix
@interface.implementer(interfaces.IFormField)
class FormField:
"""Implementation of `zope.formlib.interfaces.IFormField`. """
def __init__(self, field, name=None, prefix='',
for_display=None, for_input=None, custom_widget=None,
render_context=False, get_rendered=None, interface=None
):
self.field = field
if name is None:
name = field.__name__
assert name
self.__name__ = expandPrefix(prefix) + name
self.prefix = prefix
if interface is None:
interface = field.interface
self.interface = interface
self.for_display = for_display
self.for_input = for_input
self.custom_widget = custom_widget
self.render_context = render_context
self.get_rendered = get_rendered
Field = FormField
def _initkw(keep_readonly=(), omit_readonly=False, **defaults):
return keep_readonly, omit_readonly, defaults
@interface.implementer(interfaces.IFormFields)
class FormFields:
"""Implementation of `zope.formlib.interfaces.IFormFields`."""
def __init__(self, *args, **kw):
keep_readonly, omit_readonly, defaults = _initkw(**kw)
fields = []
for arg in args:
if isinstance(arg, InterfaceClass):
for name, field in schema.getFieldsInOrder(arg):
fields.append((name, field, arg))
elif IField.providedBy(arg):
name = arg.__name__
if not name:
raise ValueError(
"Field has no name")
fields.append((name, arg, arg.interface))
elif isinstance(arg, FormFields):
for form_field in arg:
fields.append(
(form_field.__name__,
form_field,
form_field.interface)
)
elif isinstance(arg, FormField):
fields.append((arg.__name__, arg, arg.interface))
else:
raise TypeError("Unrecognized argument type", arg)
seq = []
byname = {}
for name, field, iface in fields:
if isinstance(field, FormField):
form_field = field
else:
if field.readonly:
if omit_readonly and (name not in keep_readonly):
continue
form_field = FormField(field, interface=iface, **defaults)
name = form_field.__name__
if name in byname:
raise ValueError("Duplicate name", name)
seq.append(form_field)
byname[name] = form_field
self.__FormFields_seq__ = seq
self.__FormFields_byname__ = byname
def __len__(self):
return len(self.__FormFields_seq__)
def __iter__(self):
return iter(self.__FormFields_seq__)
def __getitem__(self, name):
return self.__FormFields_byname__[name]
def get(self, name, default=None):
return self.__FormFields_byname__.get(name, default)
def __add__(self, other):
if not isinstance(other, FormFields):
return NotImplemented
return self.__class__(self, other)
def select(self, *names):
"""Return a modified instance with an ordered subset of fields."""
return self.__class__(*[self[name] for name in names])
def omit(self, *names):
"""Return a modified instance omitting given fields."""
return self.__class__(*[ff for ff in self if ff.__name__ not in names])
Fields = FormFields
def fields_initkw(keep_all_readonly=False, **other):
return keep_all_readonly, other
# Backward compat
def fields(*args, **kw):
keep_all_readonly, other = fields_initkw(**kw)
other['omit_readonly'] = not keep_all_readonly
return FormFields(*args, **other)
@interface.implementer(interfaces.IWidgets)
class Widgets:
"""Implementation of `zope.formlib.interfaces.IWidgets`."""
def __init__(self, widgets, prefix_length=None, prefix=None):
self.__Widgets_widgets_items__ = widgets
self.__Widgets_widgets_list__ = [w for (i, w) in widgets]
if prefix is None:
# BBB Allow old code using the prefix_length argument.
if prefix_length is None:
raise TypeError(
"One of 'prefix_length' and 'prefix' is required."
)
self.__Widgets_widgets_dict__ = {
w.name[prefix_length:]: w for (i, w) in widgets
}
else:
prefix = expandPrefix(prefix)
self.__Widgets_widgets_dict__ = {
_widgetKey(w, prefix): w for (i, w) in widgets
}
def __iter__(self):
return iter(self.__Widgets_widgets_list__)
def __getitem__(self, name):
return self.__Widgets_widgets_dict__[name]
# TODO need test
def get(self, name):
return self.__Widgets_widgets_dict__.get(name)
def __iter_input_and_widget__(self):
return iter(self.__Widgets_widgets_items__)
# TODO need test
def __add__(self, other):
widgets = self.__class__([], 0)
widgets.__Widgets_widgets_items__ = (
self.__Widgets_widgets_items__ + other.__Widgets_widgets_items__)
widgets.__Widgets_widgets_list__ = (
self.__Widgets_widgets_list__ + other.__Widgets_widgets_list__)
widgets.__Widgets_widgets_dict__ = self.__Widgets_widgets_dict__.copy()
widgets.__Widgets_widgets_dict__.update(other.__Widgets_widgets_dict__)
return widgets
def canWrite(context, field):
writer = getattr(field, 'writer', None)
if writer is not None:
return zope.security.canAccess(context, writer.__name__)
return zope.security.canWrite(context, field.__name__)
def setUpWidgets(form_fields,
form_prefix=None, context=None, request=None, form=None,
data=(), adapters=None, ignore_request=False):
"""Sets up widgets."""
if request is None:
request = form.request
if context is None and form is not None:
context = form.context
if form_prefix is None:
form_prefix = form.prefix
widgets = []
adapter = None
for form_field in form_fields:
field = form_field.field
if form_field.render_context:
if adapters is None:
adapters = {}
# Adapt context, if necessary
interface = form_field.interface
adapter = adapters.get(interface)
if adapter is None:
if interface is None:
adapter = context
else:
adapter = interface(context)
adapters[interface] = adapter
if interface is not None:
adapters[interface.__name__] = adapter
field = field.bind(adapter)
else:
field = field.bind(context)
readonly = form_field.for_display
readonly = readonly or (field.readonly and not form_field.for_input)
readonly = readonly or (
(form_field.render_context & interfaces.DISPLAY_UNWRITEABLE)
and not canWrite(adapter, field)
)
if form_field.custom_widget is not None:
widget = form_field.custom_widget(field, request)
else:
if readonly:
widget = component.getMultiAdapter((field, request),
IDisplayWidget)
else:
widget = component.getMultiAdapter((field, request),
IInputWidget)
prefix = form_prefix
if form_field.prefix:
prefix = expandPrefix(prefix) + form_field.prefix
widget.setPrefix(prefix)
if ignore_request or readonly or not widget.hasInput():
# Get the value to render
if form_field.__name__ in data:
widget.setRenderedValue(data[form_field.__name__])
elif form_field.get_rendered is not None:
widget.setRenderedValue(form_field.get_rendered(form))
elif form_field.render_context:
widget.setRenderedValue(field.get(adapter))
else:
widget.setRenderedValue(field.default)
widgets.append((not readonly, widget))
return Widgets(widgets, prefix=form_prefix)
def setUpInputWidgets(form_fields, form_prefix, context, request,
form=None, ignore_request=False):
widgets = []
for form_field in form_fields:
field = form_field.field.bind(context)
widget = _createWidget(form_field, field, request, IInputWidget)
prefix = form_prefix
if form_field.prefix:
prefix = expandPrefix(prefix) + form_field.prefix
widget.setPrefix(prefix)
if ignore_request:
if form_field.get_rendered is not None:
value = form_field.get_rendered(form)
else:
value = field.default
widget.setRenderedValue(value)
widgets.append((True, widget))
return Widgets(widgets, prefix=form_prefix)
def _createWidget(form_field, field, request, iface):
if form_field.custom_widget is None:
return component.getMultiAdapter((field, request), iface)
else:
return form_field.custom_widget(field, request)
def getWidgetsData(widgets, form_prefix, data):
"""See `zope.formlib.interfaces.IFormAPI.getWidgetsData`"""
errors = []
form_prefix = expandPrefix(form_prefix)
for input, widget in widgets.__iter_input_and_widget__():
if input and IInputWidget.providedBy(widget):
name = _widgetKey(widget, form_prefix)
if not widget.hasInput():
continue
try:
data[name] = widget.getInputValue()
except ValidationError as error:
# convert field ValidationError to WidgetInputError
error = WidgetInputError(widget.name, widget.label, error)
errors.append(error)
except InputErrors as error:
errors.append(error)
return errors
def _widgetKey(widget, form_prefix):
name = widget.name
if name.startswith(form_prefix):
name = name[len(form_prefix):]
else:
raise ValueError("Name does not match prefix", name, form_prefix)
return name
def setUpEditWidgets(form_fields, form_prefix, context, request,
adapters=None, for_display=False,
ignore_request=False):
if adapters is None:
adapters = {}
widgets = []
for form_field in form_fields:
field = form_field.field
# Adapt context, if necessary
interface = form_field.interface
adapter = adapters.get(interface)
if adapter is None:
if interface is None:
adapter = context
else:
adapter = interface(context)
adapters[interface] = adapter
if interface is not None:
adapters[interface.__name__] = adapter
field = field.bind(adapter)
readonly = form_field.for_display
readonly = readonly or (field.readonly and not form_field.for_input)
readonly = readonly or (
(form_field.render_context & interfaces.DISPLAY_UNWRITEABLE)
and not canWrite(adapter, field)
)
readonly = readonly or for_display
if readonly:
iface = IDisplayWidget
else:
iface = IInputWidget
widget = _createWidget(form_field, field, request, iface)
prefix = form_prefix
if form_field.prefix:
prefix = expandPrefix(prefix) + form_field.prefix
widget.setPrefix(prefix)
if ignore_request or readonly or not widget.hasInput():
# Get the value to render
value = field.get(adapter)
widget.setRenderedValue(value)
widgets.append((not readonly, widget))
return Widgets(widgets, prefix=form_prefix)
def setUpDataWidgets(form_fields, form_prefix, context, request, data=(),
for_display=False, ignore_request=False):
widgets = []
for form_field in form_fields:
field = form_field.field.bind(context)
readonly = for_display or field.readonly or form_field.for_display
if readonly:
iface = IDisplayWidget
else:
iface = IInputWidget
widget = _createWidget(form_field, field, request, iface)
prefix = form_prefix
if form_field.prefix:
prefix = expandPrefix(prefix) + form_field.prefix
widget.setPrefix(prefix)
if ((form_field.__name__ in data)
and (ignore_request or readonly or not widget.hasInput())):
widget.setRenderedValue(data[form_field.__name__])
widgets.append((not readonly, widget))
return Widgets(widgets, prefix=form_prefix)
class NoInputData(interface.Invalid):
"""There was no input data because:
- It wasn't asked for
- It wasn't entered by the user
- It was entered by the user, but the value entered was invalid
This exception is part of the internal implementation of checkInvariants.
"""
class FormData:
def __init__(self, schema, data, context):
self._FormData_data___ = data
self._FormData_schema___ = schema
self._FormData_context___ = context
def __getattr__(self, name):
schema = self._FormData_schema___
data = self._FormData_data___
context = self._FormData_context___
try:
field = schema[name]
except KeyError:
raise AttributeError(name)
else:
value = data.get(name, data)
if value is data:
if context is None:
raise NoInputData(name)
# The value is not in the form look it up on the context:
field = schema[name]
adapted_context = schema(context)
if IField.providedBy(field):
value = field.get(adapted_context)
elif (zope.interface.interfaces.IAttribute.providedBy(field)
and
not zope.interface.interfaces.IMethod.providedBy(field)):
# Fallback for non-field schema contents:
value = getattr(adapted_context, name)
else:
# Don't know how to extract value
raise NoInputData(name)
if zope.interface.interfaces.IMethod.providedBy(field):
if not IField.providedBy(field):
raise RuntimeError(
"Data value is not a schema field", name)
def v(): return value
else:
v = value
setattr(self, name, v)
return v
raise AttributeError(name)
def checkInvariants(form_fields, form_data, context):
"""See `zope.formlib.interfaces.IFormAPI.checkInvariants`"""
# First, collect the data for the various schemas
schema_data = {}
for form_field in form_fields:
schema = form_field.interface
if schema is None:
continue
data = schema_data.get(schema)
if data is None:
data = schema_data[schema] = {}
if form_field.__name__ in form_data:
data[form_field.field.__name__] = form_data[form_field.__name__]
# Now validate the individual schemas
errors = []
for schema, data in schema_data.items():
try:
schema.validateInvariants(FormData(schema, data, context), errors)
except interface.Invalid:
pass # Just collect the errors
return [error for error in errors if not isinstance(error, NoInputData)]
def applyData(context, form_fields, data, adapters=None):
if adapters is None:
adapters = {}
descriptions = {}
for form_field in form_fields:
field = form_field.field
# Adapt context, if necessary
interface = form_field.interface
adapter = adapters.get(interface)
if adapter is None:
if interface is None:
adapter = context
else:
adapter = interface(context)
adapters[interface] = adapter
name = form_field.__name__
newvalue = data.get(name, form_field) # using form_field as marker
if (newvalue is not form_field) \
and (field.get(adapter) != newvalue):
descriptions.setdefault(interface, []).append(field.__name__)
field.set(adapter, newvalue)
return descriptions
def applyChanges(context, form_fields, data, adapters=None):
"""See `zope.formlib.interfaces.IFormAPI.applyChanges`"""
return bool(applyData(context, form_fields, data, adapters))
def _callify(meth):
"""Return method if it is callable,
otherwise return the form's method of the name"""
if callable(meth):
return meth
elif isinstance(meth, str):
return lambda form, *args: getattr(form, meth)(*args)
@interface.implementer(interfaces.IAction)
class Action:
"""See `zope.formlib.interfaces.IAction`"""
_identifier = re.compile('[A-Za-z][a-zA-Z0-9_]*$')
def __init__(self, label, success=None, failure=None,
condition=None, validator=None, prefix='actions',
name=None, data=None):
self.label = label
self.setPrefix(prefix)
self.setName(name)
self.bindMethods(success_handler=success,
failure_handler=failure,
condition=condition,
validator=validator)
if data is None:
data = {}
self.data = data
def bindMethods(self, **methods):
"""Bind methods to the action"""
for k, v in methods.items():
setattr(self, k, _callify(v))
def setName(self, name):
"""Make sure name is ASCIIfiable.
Use action label if name is None
"""
if name is None:
name = self.label
if self._identifier.match(name):
name = name.lower()
else:
if isinstance(name, str):
name = name.encode("utf-8")
name = binascii.hexlify(name).decode()
self.name = name
self.__name__ = self.prefix + name
def setPrefix(self, prefix):
"""Set prefix"""
self.prefix = expandPrefix(prefix)
def __get__(self, form, class_=None):
if form is None:
return self
result = self.__class__.__new__(self.__class__)
result.__dict__.update(self.__dict__)
result.form = form
result.__name__ = expandPrefix(form.prefix) + result.__name__
interface.alsoProvides(result, interfaces.IBoundAction)
return result
def available(self):
condition = self.condition
return (condition is None) or condition(self.form, self)
def validate(self, data):
if self.validator is not None:
return self.validator(self.form, self, data)
def success(self, data):
if self.success_handler is not None:
return self.success_handler(self.form, self, data)
def failure(self, data, errors):
if self.failure_handler is not None:
return self.failure_handler(self.form, self, data, errors)
def submitted(self):
return (self.__name__ in self.form.request.form) and self.available()
def update(self):
pass
render = namedtemplate.NamedTemplate('render')
@namedtemplate.implementation(interfaces.IAction)
def render_submit_button(self):
if not self.available():
return ''
label = self.label
if isinstance(label, zope.i18nmessageid.Message):
label = zope.i18n.translate(self.label, context=self.form.request)
return ('<input type="submit" id="%s" name="%s" value="%s"'
' class="button" />' %
(self.__name__, self.__name__, escape(label, quote=True))
)
class action:
"""See `zope.formlib.interfaces.IFormAPI.action`"""
def __init__(self, label, actions=None, **options):
caller_locals = sys._getframe(1).f_locals
if actions is None:
actions = caller_locals.get('actions')
if actions is None:
actions = caller_locals['actions'] = Actions()
self.actions = actions
self.label = label
self.options = options
def __call__(self, success):
action = Action(self.label, success=success, **self.options)
self.actions.append(action)
return action
@interface.implementer(interfaces.IActions)
class Actions:
def __init__(self, *actions):
self.actions = actions
self.byname = {a.__name__: a for a in actions}
def __iter__(self):
return iter(self.actions)
def __getitem__(self, name):
try:
return self.byname[name]
except TypeError:
if isinstance(name, slice):
return self.__class__(
*self.actions[name.start:name.stop:name.step]
)
def append(self, action):
self.actions += (action, )
self.byname[action.__name__] = action
# TODO need test
def __add__(self, other):
return self.__class__(*(self.actions + other.actions))
def copy(self):
return self.__class__(*self.actions)
def __get__(self, inst, class_):
if inst is None:
return self
return self.__class__(*[a.__get__(inst) for a in self.actions])
def handleSubmit(actions, data, default_validate=None):
"""Handle a submit."""
for action in actions:
if action.submitted():
errors = action.validate(data)
if errors is None and default_validate is not None:
errors = default_validate(action, data)
return errors, action
return None, None
# TODO need test for this
def availableActions(form, actions):
result = []
for action in actions:
condition = action.condition
if (condition is None) or condition(form, action):
result.append(action)
return result
@interface.implementer(interfaces.IForm)
class FormBase(zope.publisher.browser.BrowserPage):
label = ''
prefix = 'form'
status = ''
errors = ()
ignoreContext = False
method = None
protected = False
csrftoken = None
def setPrefix(self, prefix):
self.prefix = prefix
def setUpToken(self):
self.csrftoken = self.request.getCookies().get('__csrftoken__')
if self.csrftoken is None:
# It is possible another form, that is rendered as part of
# this request, already set a csrftoken. In that case we
# should find it in the response cookie and use that.
setcookie = self.request.response.getCookie('__csrftoken__')
if setcookie is not None:
self.csrftoken = setcookie['value']
else:
# Ok, nothing found, we should generate one and set
# it in the cookie ourselves. Note how we ``str()``
# the hex value of the ``os.urandom`` call here, as
# Python-3 will return bytes and the cookie roundtrip
# of a bytes values gets messed up.
self.csrftoken = str(binascii.hexlify(os.urandom(32)))
self.request.response.setCookie(
'__csrftoken__',
self.csrftoken,
path='/',
expires=None, # equivalent to "remove on browser quit"
httpOnly=True, # no javascript access please.
)
def checkToken(self):
cookietoken = self.request.getCookies().get('__csrftoken__')
if cookietoken is None:
# CSRF is enabled, so we really should get a token from the
# cookie. We didn't get it, so this submit is invalid!
raise InvalidCSRFTokenError(_('Invalid CSRF token'))
if cookietoken != self.request.form.get('__csrftoken__', None):
# The token in the cookie is different from the one in the
# form data. This submit is invalid!
raise InvalidCSRFTokenError(_('Invalid CSRF token'))
def setUpWidgets(self, ignore_request=False):
self.adapters = {}
self.widgets = setUpWidgets(
self.form_fields, self.prefix, self.context, self.request,
form=self, adapters=self.adapters, ignore_request=ignore_request)
def validate(self, action, data):
if self.method is not None:
# Verify the correct request method was used.
if self.method.upper() != self.request.method.upper():
raise MethodNotAllowed(self.context, self.request)
if self.protected:
self.checkToken() # This form has CSRF protection enabled.
if self.ignoreContext:
context = None
else:
context = self.context
return (getWidgetsData(self.widgets, self.prefix, data)
+ checkInvariants(self.form_fields, data, context))
template = namedtemplate.NamedTemplate('default')
# TODO also need to be able to show disabled actions
def availableActions(self):
return availableActions(self, self.actions)
def resetForm(self):
self.setUpWidgets(ignore_request=True)
form_result = None
form_reset = True
def update(self):
if self.protected:
self.setUpToken() # This form has CSRF protection enabled.
self.setUpWidgets()
self.form_reset = False
data = {}
errors, action = handleSubmit(self.actions, data, self.validate)
# the following part will make sure that previous error not
# get overriden by new errors. This is usefull for subforms. (ri)
if self.errors is None:
self.errors = errors
else:
if errors is not None:
self.errors += tuple(errors)
if errors:
self.status = _('There were errors')
result = action.failure(data, errors)
elif errors is not None:
self.form_reset = True
result = action.success(data)
else:
result = None
self.form_result = result
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
self.form_result = self.template()
return self.form_result
def __call__(self):
self.update()
if self.request.response.getStatus() in [301, 302, 303, 307]:
# Avoid rendering if the action caused a redirect.
result = self.form_result or ''
else:
result = self.render()
return result
def error_views(self):
for error in self.errors:
if isinstance(error, str):
yield error
else:
view = component.getMultiAdapter(
(error, self.request),
IWidgetInputErrorView)
title = getattr(error, 'widget_title', None) # duck typing
if title:
if isinstance(title, zope.i18n.Message):
title = zope.i18n.translate(
title, context=self.request)
yield '{}: {}'.format(title, view.snippet())
else:
yield view.snippet()
def haveInputWidgets(form, action):
for input, widget in form.widgets.__iter_input_and_widget__():
if input:
return True
else:
return False
class EditFormBase(FormBase):
def setUpWidgets(self, ignore_request=False):
self.adapters = {}
self.widgets = setUpEditWidgets(
self.form_fields, self.prefix, self.context, self.request,
adapters=self.adapters, ignore_request=ignore_request
)
@action(_("Apply"), condition=haveInputWidgets)
def handle_edit_action(self, action, data):
descriptions = applyData(self.context, self.form_fields, data,
self.adapters)
if descriptions:
descriptions = [Attributes(interface, *tuple(keys))
for interface, keys in descriptions.items()]
zope.event.notify(ObjectModifiedEvent(self.context, *descriptions))
formatter = self.request.locale.dates.getFormatter(
'dateTime', 'medium')
try:
time_zone = idatetime.ITZInfo(self.request)
except TypeError:
time_zone = pytz.UTC
status = _("Updated on ${date_time}",
mapping={'date_time':
formatter.format(
datetime.datetime.now(time_zone)
)
}
)
self.status = status
else:
self.status = _('No changes')
class DisplayFormBase(FormBase):
def setUpWidgets(self, ignore_request=False):
self.adapters = {}
self.widgets = setUpEditWidgets(
self.form_fields, self.prefix, self.context, self.request,
adapters=self.adapters, for_display=True,
ignore_request=ignore_request
)
actions = ()
@interface.implementer(interfaces.IAddFormCustomization,
zope.component.interfaces.IFactory)
@component.adapter(zope.browser.interfaces.IAdding,
zope.publisher.interfaces.browser.IBrowserRequest)
class AddFormBase(FormBase):
ignoreContext = True
def __init__(self, context, request):
self.__parent__ = context
super().__init__(context, request)
def setUpWidgets(self, ignore_request=False):
self.widgets = setUpInputWidgets(
self.form_fields, self.prefix, self.context, self.request,
ignore_request=ignore_request,
)
@action(_("Add"), condition=haveInputWidgets)
def handle_add(self, action, data):
self.createAndAdd(data)
# zope.formlib.interfaces.IAddFormCustomization
def createAndAdd(self, data):
ob = self.create(data)
zope.event.notify(ObjectCreatedEvent(ob))
return self.add(ob)
def create(self, data):
raise NotImplementedError(
"concrete classes must implement create() or createAndAdd()")
_finished_add = False
def add(self, object):
ob = self.context.add(object)
self._finished_add = True
return ob
def render(self):
if self._finished_add:
self.request.response.redirect(self.nextURL())
return ""
return super().render()
def nextURL(self):
return self.context.nextURL()
default_page_template = namedtemplate.NamedTemplateImplementation(
ViewPageTemplateFile('pageform.pt'), interfaces.IPageForm)
default_subpage_template = namedtemplate.NamedTemplateImplementation(
ViewPageTemplateFile('subpageform.pt'), interfaces.ISubPageForm)
@interface.implementer(interfaces.IPageForm)
class PageForm(FormBase):
pass
Form = PageForm
@interface.implementer(interfaces.IPageForm)
class PageEditForm(EditFormBase):
pass
EditForm = PageEditForm
@interface.implementer(interfaces.IPageForm)
class PageDisplayForm(DisplayFormBase):
pass
DisplayForm = PageDisplayForm
@interface.implementer(interfaces.IPageForm)
class PageAddForm(AddFormBase):
pass
AddForm = PageAddForm
@interface.implementer(interfaces.ISubPageForm)
class SubPageForm(FormBase):
pass
@interface.implementer(interfaces.ISubPageForm)
class SubPageEditForm(EditFormBase):
pass
@interface.implementer(interfaces.ISubPageForm)
class SubPageDisplayForm(DisplayFormBase):
pass | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/form.py | form.py |
"""Form interfaces
"""
import re
from zope.exceptions.interfaces import UserError
from zope.interface import Attribute
from zope.interface import Interface
from zope.interface import Invalid
from zope.interface import implementer
from zope.publisher.interfaces import IView
from zope.publisher.interfaces.browser import IBrowserPage
from zope.schema import Bool
from zope.schema.interfaces import ValidationError
from zope import schema
class IInvalidFormError(Interface):
def doc():
"""The form submit could not be validated.
"""
@implementer(IInvalidFormError)
class InvalidFormError(Exception):
"""The form submit could not be validated.
"""
class IInvalidCSRFTokenError(Interface):
def doc():
"""The form submit could not be handled as the CSRF token is missing
or incorrect.
"""
@implementer(IInvalidCSRFTokenError)
class InvalidCSRFTokenError(InvalidFormError):
"""The form submit could not be handled as the CSRF token is missing
or incorrect.
"""
class IWidgetInputError(Interface):
"""Placeholder for a snippet View"""
def doc():
"""Returns a string that represents the error message."""
@implementer(IWidgetInputError)
class WidgetInputError(UserError):
"""One or more user input errors occurred."""
def __init__(self, field_name, widget_title, errors=None):
"""Initialize Error
`errors` is a ``ValidationError`` or a list of ValidationError objects
"""
UserError.__init__(self, field_name, widget_title, errors)
self.field_name = field_name
self.widget_title = widget_title
self.errors = errors
def doc(self):
# TODO this duck typing is to get the code working. See
# collector issue 372
if isinstance(self.errors, str):
return self.errors
elif getattr(self.errors, 'doc', None) is not None:
return self.errors.doc()
return ''
class MissingInputError(WidgetInputError):
"""Required data was not supplied."""
@implementer(IWidgetInputError)
class ConversionError(Exception):
"""A conversion error occurred."""
def __init__(self, error_name, original_exception=None):
Exception.__init__(self, error_name, original_exception)
self.error_name = error_name
self.original_exception = original_exception
def doc(self):
return self.error_name
InputErrors = WidgetInputError, ValidationError, ConversionError
class ErrorContainer(Exception):
"""A base error class for collecting multiple errors."""
def append(self, error):
self.args += (error, )
def __len__(self):
return len(self.args)
def __iter__(self):
return iter(self.args)
def __getitem__(self, i):
return self.args[i]
def __str__(self):
return "\n".join(
["{}: {}".format(error.__class__.__name__, error)
for error in self.args]
)
__repr__ = __str__
class WidgetsError(ErrorContainer):
"""A collection of errors from widget processing.
widgetValues is a map containing the list of values that were obtained
from the widgets, keyed by field name.
"""
def __init__(self, errors, widgetsData={}):
ErrorContainer.__init__(self, *errors)
self.widgetsData = widgetsData
class IWidget(IView):
"""Generically describes the behavior of a widget.
Note that this level must be still presentation independent.
"""
name = Attribute(
"""The unique widget name
This must be unique within a set of widgets.""")
label = Attribute(
"""The widget label.
Label may be translated for the request.
The attribute may be implemented as either a read-write or read-only
property, depending on the requirements for a specific implementation.
""")
hint = Attribute(
"""A hint regarding the use of the widget.
Hints are traditionally rendered using tooltips in GUIs, but may be
rendered differently depending on the UI implementation.
Hint may be translated for the request.
The attribute may be implemented as either a read-write or read-only
property, depending on the requirements for a specific implementation.
""")
visible = Attribute(
"""A flag indicating whether or not the widget is visible.""")
def setRenderedValue(value):
"""Set the value to be rendered by the widget.
Calling this method will override any values provided by the user.
For input widgets (`IInputWidget` implementations), calling
this sets the value that will be rendered even if there is
already user input.
"""
def setPrefix(prefix):
"""Set the name prefix used for the widget
The widget name is used to identify the widget's data within
input data. For example, for HTTP forms, the widget name is
used for the form key.
It is acceptable to *reset* the prefix: set it once to read
values from the request, and again to redraw with a different
prefix but maintained state.
"""
class IInputWidget(IWidget):
"""A widget for editing a field value."""
required = Bool(
title="Required",
description="""If True, widget should be displayed as requiring input.
By default, this value is the field's 'required' attribute. This
field can be set to False for widgets that always provide input (e.g.
a checkbox) to avoid unnecessary 'required' UI notations.
""")
def getInputValue():
"""Return value suitable for the widget's field.
The widget must return a value that can be legally assigned to
its bound field or otherwise raise ``WidgetInputError``.
The return value is not affected by `setRenderedValue()`.
"""
def applyChanges(content):
"""Validate the user input data and apply it to the content.
Return a boolean indicating whether a change was actually applied.
This raises an error if there is no user input.
"""
def hasInput():
"""Returns ``True`` if the widget has input.
Input is used by the widget to calculate an 'input value', which is
a value that can be legally assigned to a field.
Note that the widget may return ``True``, indicating it has input, but
still be unable to return a value from `getInputValue`. Use
`hasValidInput` to determine whether or not `getInputValue` will return
a valid value.
A widget that does not have input should generally not be used
to update its bound field. Values set using
`setRenderedValue()` do not count as user input.
A widget that has been rendered into a form which has been
submitted must report that it has input. If the form
containing the widget has not been submitted, the widget
shall report that it has no input.
"""
def hasValidInput():
"""Returns ``True`` is the widget has valid input.
This method is similar to `hasInput` but it also confirms that the
input provided by the user can be converted to a valid field value
based on the field constraints.
"""
class IDisplayWidget(IWidget):
"""A widget for displaying a field value."""
required = Bool(
title="Required",
description="""If True, widget should be displayed as requiring input.
Display widgets should never be required.
""")
class IWidgetFactory(Interface):
"""A factory that creates the widget"""
def __call__(context, request):
"""Return a widget"""
class FormError(Exception):
"""There was an error in managing the form
"""
class IBrowserWidget(IWidget):
"""A widget for use in a web browser UI."""
def __call__():
"""Render the widget."""
def hidden():
"""Render the widget as a hidden field."""
def error():
"""Render the validation error for the widget, or return
an empty string if no error"""
class ISimpleInputWidget(IBrowserWidget, IInputWidget):
"""A widget that uses a single HTML element to collect user input."""
tag = schema.TextLine(
title='Tag',
description='The widget HTML element.')
type = schema.TextLine(
title='Type',
description='The element type attribute',
required=False)
cssClass = schema.TextLine(
title='CSS Class',
description='The element class attribute.',
required=False)
extra = schema.TextLine(
title='Extra',
description='The element extra attribute.',
required=False)
class ITextBrowserWidget(ISimpleInputWidget):
convert_missing_value = schema.Bool(
title='Translate Input Value',
description=(
'If True, an empty string is converted to field.missing_value.'),
default=True)
def reConstraint(pat, explanation, can_be_empty=False):
pat = re.compile(pat)
def constraint(value):
if not value and can_be_empty:
return True
if pat.match(value):
return True
raise Invalid(value, explanation)
return constraint
class IWidgetInputErrorView(Interface):
"""Display an input error as a snippet of text."""
def snippet():
"""Convert a widget input error to an html snippet."""
class ISourceQueryView(Interface):
"""View support for querying non-iterable sources
"""
def render(name):
"""Return a rendering of the search form elements
The query view should use `name` as the prefix for its widgets.
"""
def results(name):
"""Return the results of the query
The query view should use `name` as the prefix for its widgets.
The value returned is an iterable.
None may be returned to indicate that there are no results.
"""
class ISubPage(Interface):
"""A component that computes part of a page
"""
def update():
"""Update content ot view information based on user input
"""
def render():
"""Render the sub page, returning a unicode string
"""
prefix = schema.ASCII(
constraint=reConstraint(
'[a-zA-Z][a-zA-Z0-9_]*([.][a-zA-Z][a-zA-Z0-9_]*)*',
"Must be a sequence of not-separated identifiers"),
description="""Page-element prefix
All named or identified page elements in a subpage should have
names and identifiers that begin with a subpage prefix
followed by a dot.
""",
readonly=True,
)
def setPrefix(prefix):
"""Update the subpage prefix
"""
class IFormAPI(Interface):
"""API to facilitate creating forms, provided by `zope.formlib.form`
"""
def Field(schema_field, **options):
"""Define a form field from a schema field and usage options
The following options are supported:
name
Provide a name to use for the field.
prefix
The form-field prefix.
for_display
A flag indicating whether the form-field is to be used
for display. See IFormField.
for_input
A flag indicating whether the form-field is to be used
for input. See IFormField.
custom_widget
Factory to use for widget construction. See IFormField.
render_context
A flag indicating whether the default value to render
should come from the form context. See IFormField.
get_rendered
A callable or form method name to be used to get a default
rendered value. See IFormField.
"""
def Fields(*arguments, **options):
"""Create form-fields collection (`IFormFields`)
Creates a form-field collection from a collection of:
- Schemas
- Schema fields
- form fields (IFormField)
- form-field collections (IFormFields)
An IFormFields is returned.
The following options are supported:
name
Provide a name to use for the field.
prefix
The form-field prefix for new form-fields created.
When form-field collections are passed, their contents keep
their existing prefixes are retained.
for_display
A flag indicating whether the form-fiellds are to be used
for display. This value is used for for_display attributes
of all created form fields. This option does not effect
input from form-field collections.
for_input
A flag indicating whether the form-fiellds are to be used
for input. This value is used for for_input attributes
of all created form fields. This option does not effect
input from form-field collections.
render_context
A flag indicating whether the default values to render
should come from the form context. See IFormField.
"""
def setUpInputWidgets(form_fields, form_prefix, context, request,
ignore_request=False):
"""Set up widgets for input
An IWidgets is returned based on the give form fields.
All of the resulting widgets will be input widgets, regardless
of whether the form fields are for display or whether the
underlying schema fields are read only. This is so that one
can easily build an input form, such as an add form from an
existing schema.
The widgets will have prefixes that combine the given form
prefix and any form-field prefixes.
A context argument is provided to allow field binding.
If ignore_request passed a true value, then the widgets will
not initialize their values from the request.
"""
def setUpEditWidgets(form_fields, form_prefix, context, request,
adapters=None, for_display=False,
ignore_request=False):
"""Set up widgets for editing or displaying content
An IWidgets is returned based on the give form fields.
The resulting widgets will be input widgets unless:
- the corresponding form field was defined with the
for_display option,
- the underlying field is read only, or
- the for_display opetion to setUpEditWidgets was passed a
true value.
The widgets fields are bound to the context after it is
adapted to the field schema. A mapping object can be passed
to setUpEditWidgets to capture the adapters created. The
adapters are placed in the mapping using both interfaces and
interface names as keys.
If the ignore_request option is passed a true value, then
widget's rendered data will be set from the context, and user
inputs will be ignored.
"""
def setUpDataWidgets(form_fields, form_prefix, context, request, data=(),
for_display=False, ignore_request=False):
"""Set up widgets for input or display
An IWidgets is returned based on the give form fields.
The resulting widgets will be input widgets unless:
- the corresponding form field was defined with the
for_display option,
- the underlying field is read only, or
- the for_display opetion to setUpEditWidgets was passed a
true value.
A data mapping argument can be passed to provide initial
data.
If the ignore_request option is passed a true value, then
widget's rendered data will be set from the passed data or
from field defaults, and user inputs will be ignored.
"""
def getWidgetsData(widgets, form_prefix, data):
"""Get input data and input errors
A sequence of input errors are returned. Any data available
are added to the data argument, which must be a mapping
argument. The keys in the output mapping are
widget/form-field names without the form prefix.
"""
def checkInvariants(form_fields, form_data):
"""Check schema invariants for input data
For each schema that was used to define the form fields and
that had invariants relevent to the fields, the invariants are
checked. Invariants that refer to fields not included in the
form fields are ignored.
A list of errors is returned.
"""
def applyChanges(context, form_fields, data, adapters=None):
"""Apply form data to an object
For each form field that has data, the data are applied to the
context argument. The context is adapter to the schema for
each field. If an adapters mapping is passed, it will be used
as a cache. Typically, it would be a mapping object populated
when setUpEditWidgets was called.
"""
def Action(label, **options):
"""Define a submit action
options:
condition
A callable or name of a method to call to test whether
the action is applicable. if the value is a method
name, then the method will be passed the action when
called, otherwise, the callables will be passed the form
and the action.
validator
A callable or name of a method to call to validate and
collect inputs. This is called only if the action was
submitted and if the action either has no condition, or the
condition evaluates to a true value. If the validator is
provided as a method name, the method will be called the
action and a dictionary in which to save data. If the
validator is provided as a callable, the callable will be
called the form, the action, and a dictionary in which to
save data. The validator normally returns a (usually empty)
list of widget input errors. It may also return None to behave
as if the action wasn't submitted.
success
A handler, called when the the action was submitted and
there are no validation errors. The handler may be provided
as either a callable or a method name. If the handler is
provided as a method name, the method will be called the
action and a dictionary containing the form data. If the
success handler is provided as a callable, the callable will
be called the form, the action, and a dictionary containing
the data. The handler may return a form result (e.g. page),
or may return None to indicate that the form should generate
it's own output.
failure
A handler, called when the the action was submitted and
there are validation errors. The handler may be provided as
either a callable or a method name. If the handler is
provided as a method name, the method will be called the
action, a dictionary containing the form data, and a list of
errors. If the failure handler is provided as a callable,
the callable will be called the form, the action, a
dictionary containing the data, and a list of errors. The
handler may return a form result (e.g. page), or may return
None to indicate that the form should generate it's own
output.
prefix
A form prefix for the action. When generating submit
actions, the prefix should be combined with the action
name, separating the two with a dot. The default prefix
is "actions"form.
name
The action name, without a prefix. If the label is a
valid Python identifier, then the lowe-case label will
be used, otherwise, a hex encoding of the label will be
used. If for some strange reason the labels in a set of
actions with the same prefix is not unique, a name will
have to be given for some actions to get unique names.
css_class
The CSS class for the action. The class defaults to
"action"form.
data
A bag of extra information that can be used by handlers,
validators, or conditions.
"""
def action(label, **options):
"""Create an action factory
This function creates a factory for creating an action from a
function, using the function as the action success handler.
The options are the same as for the Action constructor except
that the options don't include the success option.
The function is designed to be used as a decorator, as in::
@action("Edit")
def handle_edit(self, action, data):
...
"""
def validate(form, actions, form_prefix, data, default_validate=None):
"""Process a submitted action, if any
Check each of the given actions to see if any were submitted.
If an action was submitted, then validate the input. The input
is called by calling the action's validator, ir it has one, or
by calling the default_validate passed in.
If the input is validated successfully, and the action has one
success handler, then the success handler is called.
If the input was validated and there were errors, then the
action's failure handler will be called, if it has one.
If an action was submitted, then the function returns the
result of validation and the action. The result of validation
is normally a boolean, but may be None if no validator was
provided.
If no action was submitted, then None is returned for both the
result of validation and the action.
"""
FormBase = Attribute("""Base class for creating forms
The FormBase class provides reuasable implementation for creating
forms. It implements ISubPage, IBrowserPage, and IFormBaseCustomization.
Subclasses will override or use attributes defined by
IFormBaseCustomization.
""")
class IFormBaseCustomization(ISubPage, IBrowserPage):
"""Attributes provided by the Form base class
These attributes may be used or overridden.
Note that the update and render methods are designed to to work
together. If you override one, you probably need to override the
other, unless you use original versions in your override.
"""
label = Attribute("A label to display at the top of a form")
status = Attribute(
"""An update status message
This is normally generated by success or failure handlers.
""")
errors = Attribute(
"""Sequence of errors encountered during validation
""")
form_result = Attribute(
"""Return from action result method
""")
form_reset = Attribute(
"""Boolean indicating whether the form needs to be reset
""")
form_fields = Attribute(
"""The form's form field definitions
This attribute is used by many of the default methods.
""")
widgets = Attribute(
"""The form's widgets
- set by setUpWidgets
- used by validate
""")
def setUpWidgets(ignore_request=False):
"""Set up the form's widgets.
The default implementation uses the form definitions in the
form_fields attribute and setUpInputWidgets.
The function should set the widgets attribute.
"""
def validate(action, data):
"""The default form validator
If an action is submitted and the action doesn't have it's own
validator then this function will be called.
"""
template = Attribute(
"""Template used to display the form
This can be overridden in 2 ways:
1. You can override the attribute in a subclass
2. You can register an alternate named template, named
"default" for your form.
""")
def resetForm():
"""Reset any cached data because underlying content may have changed
"""
def error_views():
"""Return views of any errors.
The errors are returned as an iterable.
"""
class IFormFields(Interface):
"""A colection of form fields (`IFormField` objects)
"""
def __len__():
"""Get the number of fields
"""
def __iter__():
"""Iterate over the form fields
"""
def __getitem__(name):
"""Return the form field with the given name
If the desired firld has a prefix, then the given name should
be the prefix, a dot, and the unprefixed name. Otherwise, the
given name is just the field name.
Raise a KeyError if a field can't be found for the given name.
"""
def get(name, default=None):
"""Return the form field with the given name
If the desired firld has a prefix, then the given name should
be the prefix, a dot, and the unprefixed name. Otherwise, the
given name is just the field name.
Return the default if a field can't be found for the given name.
"""
def __add__(form_fields):
"""Add two form fields collections (`IFormFields`)
Return a new IFormFields that is the concatination of the two
IFormFields.
"""
def select(*names):
"""Select fields with given names in order
Return a new `IFormFields` that is a selection from the original
`IFormFields` that has the named fields in the specified order.
"""
def omit(*names):
"""Omit fields with given names
"""
SKIP_UNAUTHORIZED = 2
DISPLAY_UNWRITEABLE = 4
class IFormField(Interface):
"""Definition of a field to be included in a form
This should not be confused with a schema field.
"""
__name__ = schema.ASCII(
constraint=reConstraint('[a-zA-Z][a-zA-Z0-9_]*',
"Must be an identifier"),
title="Field name",
description="""\
This is the name, without any proefix, used for the field.
It is usually the same as the name of the for field's schem field.
"""
)
field = Attribute(
"""Schema field that defines the data of the form field
"""
)
prefix = schema.ASCII(
constraint=reConstraint(
r'[a-zA-Z][a-zA-Z0-9_.]*', "Must be an identifier or empty",
can_be_empty=True),
title="Prefix",
description="""\
Form-field prefix. The form-field prefix is used to
disambiguate fields with the same name (e.g. from different
schema) within a collection of form fields.
""",
required=False,
default="",
)
for_display = schema.Bool(
title="Is the form field for display only?",
description="""\
If this attribute has a true value, then a display widget will be
used for the field even if it is writable.
"""
)
for_input = schema.Bool(
title="Is the form field for input?",
description="""\
If this attribute has a true value, then an input widget will be
used for the field even if it is readonly.
"""
)
custom_widget = Attribute(
"""Factory to use for widget construction.
If not set, normal view lookup will be used.
"""
)
render_context = schema.Choice(
title="Should the rendered value come from the form context?",
description="""\
If this attribute has a true value, and there is no other
source of rendered data, then use data from the form context
to set the rendered value for the widget. This attribute is
ignored if:
- There is user input and user input is not being ignored, or
- Data for the value is passed to setUpWidgets.
If the value is true, then it is evaluated as a collection of bit
flags with the flags:
DISPLAY_UNWRITEABLE
If the field isn't writable, then use a display widget
TODO untested
SKIP_UNAUTHORIZED
If the user is not priviledges to perform the requested
operation, then omit a widget.
TODO unimplemented
""",
vocabulary=schema.vocabulary.SimpleVocabulary.fromValues((
False, True,
DISPLAY_UNWRITEABLE,
SKIP_UNAUTHORIZED,
DISPLAY_UNWRITEABLE | SKIP_UNAUTHORIZED,
)),
default=False,
missing_value=False,
)
get_rendered = Attribute(
"""Object to call to get a rendered value
This attribute may be set to a callable object or to
a form method name to call to get a value to be rendered in a
widget.
This attribute is ignored if:
- There is user input and user input is not being ignored, or
- Data for the value is passed to setUpWidgets.
"""
)
class IWidgets(Interface):
"""A widget collection
IWidgets provide ordered collections of widgets that also support:
- Name-based lookup
- Keeping track of whether a widget is being used for input or
display
"""
def __iter__():
"""Return an interator in the widgets, in order
"""
def __getitem__(name):
"""Get the widget with the given name
Widgets are computed from form fields (IFormField). If the
form field used to create a widget has a prefix, then that
should be reflected in the name passed.
"""
def __iter_input_and_widget__():
"""Return an iterator of flag/widget pairs
The flags indicate whether the corresponding widgets are used
for input. This is necessary because there is currently no
way to introspect a widget to determine whether it is being
used for input.
"""
def __add__(widgets):
"""Add two widgets collections
The result has the widgets in the first collection followed by
the widgets in the second collection.
Widgets should have different names in the two collections.
The bahavior is undefined if the names overlap.
"""
class IForm(Interface):
"""Base type for forms
This exists primarily to provide something for which to register
form-related conponents.
"""
class ISubPageForm(IForm, ISubPage):
"""A component that displays a part of a page.
The rendered output must not have a form tag. It is the
responsibility of the surrounding page to supply a form tag.
"""
class IPageForm(IForm, IBrowserPage):
"""A component that displays a form as a page.
"""
class IAction(ISubPage):
"""Form submit actions
"""
label = schema.TextLine(title="Action label")
name = schema.TextLine(title="Action name")
__name__ = schema.TextLine(title="Action name with its prefix")
data = schema.Dict(title="Application data")
condition = Attribute(
"""Action condition
This is a callable object that will be passed a form and an
action and that returns a boolean to indicate whether the
action is available.
""")
validator = Attribute(
"""Action validator
This is a callable object that will be passed a form and an
action and that returns a (possibly empty) list of widget
input errors.
""")
def available():
"""Return a boolean indicating whether the action is available
"""
def submitted():
"""Return a boolean indicating whether the action was submitted
"""
def validate(data):
"""Validate inputs
If an action was submitted and has a custom validator, then
the validator result is returned. Otherwise, None is returned.
Validated inputs, if any, are placed into the mapping object
passed as an argument,
"""
def success(data):
"""Handle sucessful submition
This method is called when the action was submitted and the
submitted data was valid.
"""
def failure(data, errors):
"""Handle unsucessful submition
This method is called when the action was submitted and the
submitted data was not valid.
"""
def __get__(form, form_class=None):
"""Bind an action to a form
Note that the other methods defined in this interface are
valid only after the action has been bound to a form.
"""
class IActions(Interface):
"""An action collection
IActions provide ordered collections of actions that also support
name-based lookup.
"""
def __iter__():
"""Return an interator in the actions, in order
"""
def __getitem__(name):
"""Get the action with the given name
Actions are computed from form fields (IFormField). If the
form field used to create an action has a prefix, then that
should be reflected in the name passed.
"""
def __add__(actions):
"""Add two actions collections
The result has the actions in the first collection followed by
the actions in the second collection.
Actions should have different names in the two collections.
The bahavior is undefined if the names overlap.
"""
class IBoundAction(IAction):
"""An action that has been bound to a form
"""
form = Attribute("The form to which the action is bound")
class IAddFormCustomization(IFormBaseCustomization):
"""Form responsible for adding an object.
"""
def create(data):
"""Create and return an object to be added to the context.
The data argument is a dictionary with values supplied by the
form.
If any user errors occur, they should be collected into a list
and raised as a `WidgetsError`.
"""
def add(object):
"""Add an object to the context. Returns the added object.
"""
def createAndAdd(data):
"""Create and return an object that has been added to the context.
The data argument is a dictionary with values supplied by the
form.
If any user errors occur, they should be collected into a list
and raised as a `WidgetsError`.
This is normally expected to simply call the create() and
add() methods.
"""
def nextURL():
"""Return the URL to be displayed after the add operation.
This can be relative to the view's context.
The default implementation returns `self.context.nextURL()`,
i.e. it delegates to the `IAdding` view.
""" | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/interfaces.py | interfaces.py |
"""Browser widgets with text-based input
"""
import decimal
from xml.sax import saxutils
from zope.datetime import DateTimeError
from zope.datetime import parseDatetimetz
from zope.i18n.format import DateTimeParseError
from zope.interface import implementer
from zope.formlib._compat import toStr
from zope.formlib.i18n import _
from zope.formlib.interfaces import ConversionError
from zope.formlib.interfaces import ITextBrowserWidget
from zope.formlib.widget import DisplayWidget
from zope.formlib.widget import SimpleInputWidget
from zope.formlib.widget import renderElement
def escape(str):
if str is not None:
str = saxutils.escape(str)
return str
@implementer(ITextBrowserWidget)
class TextWidget(SimpleInputWidget):
"""Text widget.
Single-line text input
>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import TextLine
>>> field = TextLine(__name__='foo', title='on')
>>> request = TestRequest(form={'field.foo': 'Bob'})
>>> widget = TextWidget(field, request)
>>> widget.hasInput()
True
>>> widget.getInputValue()
'Bob'
>>> def normalize(s):
... return '\\n '.join(filter(None, s.split(' ')))
>>> print(normalize( widget() ))
<input
class="textType"
id="field.foo"
name="field.foo"
size="20"
type="text"
value="Bob"
/>
>>> print(normalize( widget.hidden() ))
<input
class="hiddenType"
id="field.foo"
name="field.foo"
type="hidden"
value="Bob"
/>
Calling `setRenderedValue` will change what gets output:
>>> widget.setRenderedValue("Barry")
>>> print(normalize( widget() ))
<input
class="textType"
id="field.foo"
name="field.foo"
size="20"
type="text"
value="Barry"
/>
Check that HTML is correctly encoded and decoded:
>>> request = TestRequest(
... form={'field.foo': '<h1>©</h1>'})
>>> widget = TextWidget(field, request)
>>> widget.getInputValue()
'<h1>©</h1>'
>>> print(normalize( widget() ))
<input
class="textType"
id="field.foo"
name="field.foo"
size="20"
type="text"
value="<h1>&copy;</h1>"
/>
"""
default = ''
displayWidth = 20
displayMaxWidth = ""
extra = ''
style = ''
convert_missing_value = True
def __init__(self, *args):
super().__init__(*args)
def __call__(self):
value = self._getFormValue()
if value is None or value == self.context.missing_value:
value = ''
kwargs = {'type': self.type,
'name': self.name,
'id': self.name,
'value': value,
'cssClass': self.cssClass,
'style': self.style,
'size': self.displayWidth,
'extra': self.extra}
if self.displayMaxWidth:
# TODO This is untested.
kwargs['maxlength'] = self.displayMaxWidth
return renderElement(self.tag, **kwargs)
def _toFieldValue(self, input):
if self.convert_missing_value and input == self._missing:
value = self.context.missing_value
else:
# We convert everything to str. This might seem a bit crude,
# but anything contained in a TextWidget should be representable
# as a string. Note that you always have the choice of overriding
# the method.
try:
value = toStr(input)
except ValueError as v:
raise ConversionError(_("Invalid text data"), v)
return value
class Text(SimpleInputWidget):
def _toFieldValue(self, input):
return super()._toFieldValue(input)
class Bytes(SimpleInputWidget):
def _toFieldValue(self, input):
value = super()._toFieldValue(input)
if isinstance(value, str):
try:
value = value.encode('ascii')
except UnicodeError as v:
raise ConversionError(_("Invalid textual data"), v)
return value
class BytesWidget(Bytes, TextWidget):
"""Bytes widget.
Single-line data (string) input
>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import BytesLine
>>> field = BytesLine(__name__='foo', title='on')
>>> request = TestRequest(form={'field.foo': 'Bob'})
>>> widget = BytesWidget(field, request)
>>> widget.hasInput()
True
>>> widget.getInputValue()
b'Bob'
"""
class BytesDisplayWidget(DisplayWidget):
"""Bytes display widget"""
def __call__(self):
if self._renderedValueSet():
content = self._data
else:
content = self.context.default
return renderElement("pre", contents=escape(content))
class ASCII(Text):
"""ASCII"""
class ASCIIWidget(TextWidget):
"""ASCII widget.
Single-line data (string) input
"""
class ASCIIDisplayWidget(DisplayWidget):
"""ASCII display widget"""
class URIDisplayWidget(DisplayWidget):
"""URI display widget.
:ivar linkTarget:
The value of the ``target`` attribute for the generated hyperlink.
If this is not set, no ``target`` attribute is generated.
"""
linkTarget = None
def __call__(self):
if self._renderedValueSet():
content = self._data
else:
content = self.context.default
if not content:
# If there is no content it is not useful to render an anchor.
return ''
content = escape(content)
kw = dict(contents=content, href=content)
if self.linkTarget:
kw["target"] = self.linkTarget
return renderElement("a", **kw)
class TextAreaWidget(SimpleInputWidget):
"""TextArea widget.
Multi-line text input.
>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import Text
>>> field = Text(__name__='foo', title='on')
>>> request = TestRequest(form={'field.foo': 'Hello\\r\\nworld!'})
>>> widget = TextAreaWidget(field, request)
>>> widget.hasInput()
True
>>> widget.getInputValue()
'Hello\\nworld!'
>>> def normalize(s):
... return '\\n '.join(filter(None, s.split(' ')))
>>> print(normalize( widget() ))
<textarea
cols="60"
id="field.foo"
name="field.foo"
rows="15"
>Hello\r
world!</textarea>
>>> print(normalize( widget.hidden() ))
<input
class="hiddenType"
id="field.foo"
name="field.foo"
type="hidden"
value="Hello world!"
/>
Calling `setRenderedValue` will change what gets output:
>>> widget.setRenderedValue("Hey\\ndude!")
>>> print(normalize( widget() ))
<textarea
cols="60"
id="field.foo"
name="field.foo"
rows="15"
>Hey\r
dude!</textarea>
Check that HTML is correctly encoded and decoded:
>>> request = TestRequest(
... form={'field.foo': '<h1>©</h1>'})
>>> widget = TextAreaWidget(field, request)
>>> widget.getInputValue()
'<h1>©</h1>'
>>> print(normalize( widget() ))
<textarea
cols="60"
id="field.foo"
name="field.foo"
rows="15"
><h1>&copy;</h1></textarea>
There was a but which caused the content of <textarea> tags not to be
rendered correctly when there was a conversion error. Make sure the quoting
works correctly::
>>> from zope.schema import Text
>>> field = Text(__name__='description', title='Description')
>>> from zope.formlib.interfaces import ConversionError
>>> class TestTextAreaWidget(TextAreaWidget):
... def _toFieldValue(self, input):
... if 'foo' in input:
... raise ConversionError("I don't like foo.")
... return input
...
>>> request = TestRequest(form={'field.description': '<p>bar</p>'})
>>> widget = TestTextAreaWidget(field, request)
>>> widget.getInputValue()
'<p>bar</p>'
>>> print(normalize( widget() ))
<textarea
cols="60"
id="field.description"
name="field.description"
rows="15"
><p>bar</p></textarea>
>>> request = TestRequest(form={'field.description': '<p>foo</p>'})
>>> widget = TestTextAreaWidget(field, request)
>>> try:
... widget.getInputValue()
... except ConversionError as error:
... print(error.doc())
I don't like foo.
>>> print(normalize( widget() ))
<textarea
cols="60"
id="field.description"
name="field.description"
rows="15"
><p>foo</p></textarea>
"""
default = ""
width = 60
height = 15
extra = ""
style = ''
def _toFieldValue(self, value):
value = super()._toFieldValue(value)
if value:
try:
value = toStr(value)
except ValueError as v:
raise ConversionError(_("Invalid test data"), v)
else:
value = value.replace("\r\n", "\n")
return value
def _toFormValue(self, value):
value = super()._toFormValue(value)
if value:
value = value.replace("\n", "\r\n")
else:
value = ''
return value
def __call__(self):
return renderElement("textarea",
name=self.name,
id=self.name,
cssClass=self.cssClass,
rows=self.height,
cols=self.width,
style=self.style,
contents=escape(self._getFormValue()),
extra=self.extra)
class BytesAreaWidget(Bytes, TextAreaWidget):
"""BytesArea widget.
Multi-line string input.
>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import Bytes
>>> field = Bytes(__name__='foo', title='on')
>>> request = TestRequest(form={'field.foo': 'Hello\\r\\nworld!'})
>>> widget = BytesAreaWidget(field, request)
>>> widget.hasInput()
True
>>> widget.getInputValue()
b'Hello\\nworld!'
"""
class ASCIIAreaWidget(Text, TextAreaWidget):
"""ASCIIArea widget.
Multi-line string input.
>>> from zope.publisher.browser import TestRequest
>>> from zope.schema import ASCII
>>> field = ASCII(__name__='foo', title='on')
>>> request = TestRequest(form={'field.foo': 'Hello\\r\\nworld!'})
>>> widget = ASCIIAreaWidget(field, request)
>>> widget.hasInput()
True
>>> widget.getInputValue()
'Hello\\nworld!'
"""
class PasswordWidget(TextWidget):
"""Password Widget"""
type = 'password'
def __call__(self):
displayMaxWidth = self.displayMaxWidth or 0
if displayMaxWidth > 0:
return renderElement(self.tag,
type=self.type,
name=self.name,
id=self.name,
value='',
cssClass=self.cssClass,
style=self.style,
size=self.displayWidth,
maxlength=displayMaxWidth,
extra=self.extra)
else:
return renderElement(self.tag,
type=self.type,
name=self.name,
id=self.name,
value='',
cssClass=self.cssClass,
style=self.style,
size=self.displayWidth,
extra=self.extra)
def _toFieldValue(self, input):
try:
existing = self.context.get(self.context.context)
except AttributeError:
existing = False
if (not input) and existing:
return self.context.UNCHANGED_PASSWORD
return super()._toFieldValue(input)
def hidden(self):
raise NotImplementedError(
'Cannot get a hidden tag for a password field')
class FileWidget(TextWidget):
"""File Widget"""
type = 'file'
def __call__(self):
displayMaxWidth = self.displayMaxWidth or 0
hidden = renderElement(self.tag,
type='hidden',
name=self.name + ".used",
id=self.name + ".used",
value="")
if displayMaxWidth > 0:
elem = renderElement(self.tag,
type=self.type,
name=self.name,
id=self.name,
cssClass=self.cssClass,
size=self.displayWidth,
maxlength=displayMaxWidth,
extra=self.extra)
else:
elem = renderElement(self.tag,
type=self.type,
name=self.name,
id=self.name,
cssClass=self.cssClass,
size=self.displayWidth,
extra=self.extra)
return "{} {}".format(hidden, elem)
def _toFieldValue(self, input):
if input is None or input == '':
return self.context.missing_value
try:
seek = input.seek
read = input.read
except AttributeError as e:
raise ConversionError(_('Form input is not a file object'), e)
else:
seek(0)
data = read()
if data or getattr(input, 'filename', ''):
return data
else:
return self.context.missing_value
def hasInput(self):
return ((self.name + ".used" in self.request.form)
or
(self.name in self.request.form)
)
class IntWidget(TextWidget):
"""Integer number widget.
Let's make sure that zeroes are rendered properly:
>>> from zope.schema import Int
>>> field = Int(__name__='foo', title='on')
>>> widget = IntWidget(field, None)
>>> widget.setRenderedValue(0)
>>> 'value="0"' in widget()
True
"""
displayWidth = 10
def _toFieldValue(self, input):
if input == self._missing:
return self.context.missing_value
else:
try:
return int(input)
except ValueError as v:
raise ConversionError(_("Invalid integer data"), v)
class FloatWidget(TextWidget):
displayWidth = 10
def _toFieldValue(self, input):
if input == self._missing:
return self.context.missing_value
else:
try:
return float(input)
except ValueError as v:
raise ConversionError(_("Invalid floating point data"), v)
class DecimalWidget(TextWidget):
displayWidth = 10
def _toFieldValue(self, input):
if input == self._missing:
return self.context.missing_value
else:
try:
return decimal.Decimal(input)
except decimal.InvalidOperation as v:
raise ConversionError(_("Invalid decimal data"), v)
def _toFormValue(self, value):
if value == self.context.missing_value:
value = self._missing
else:
return toStr(value)
class DatetimeWidget(TextWidget):
"""Datetime entry widget."""
displayWidth = 20
def _toFieldValue(self, input):
if input == self._missing:
return self.context.missing_value
else:
try:
# TODO: Currently datetimes return in local (server)
# time zone if no time zone information was given.
# Maybe offset-naive datetimes should be returned in
# this case? (DV)
return parseDatetimetz(input)
except (DateTimeError, ValueError, IndexError) as v:
raise ConversionError(_("Invalid datetime data"), v)
class DateWidget(DatetimeWidget):
"""Date entry widget.
"""
def _toFieldValue(self, input):
v = super()._toFieldValue(input)
if v != self.context.missing_value:
v = v.date()
return v
class DateI18nWidget(TextWidget):
"""I18n date entry widget.
The `displayStyle` attribute may be set to control the formatting of the
value.
`displayStyle` must be one of 'full', 'long', 'medium', 'short',
or None ('' is accepted an an alternative to None to support
provision of a value from ZCML).
"""
_category = "date"
displayWidth = 20
displayStyle = None
def _toFieldValue(self, input):
if input == self._missing:
return self.context.missing_value
else:
try:
formatter = self.request.locale.dates.getFormatter(
self._category, (self.displayStyle or None))
return formatter.parse(input)
except (DateTimeParseError, ValueError) as v:
raise ConversionError(_("Invalid datetime data"),
"{} ({!r})".format(v, input))
def _toFormValue(self, value):
value = super()._toFormValue(value)
if value:
formatter = self.request.locale.dates.getFormatter(
self._category, (self.displayStyle or None))
value = formatter.format(value)
return value
class DatetimeI18nWidget(DateI18nWidget):
"""I18n datetime entry widget.
The `displayStyle` attribute may be set to control the formatting of the
value.
`displayStyle` must be one of 'full', 'long', 'medium', 'short',
or None ('' is accepted an an alternative to None to support
provision of a value from ZCML).
NOTE: If you need timezone information you need to set `displayStyle`
to either 'long' or 'full' since other display styles just ignore it.
"""
_category = "dateTime"
class DateDisplayWidget(DisplayWidget):
"""Date display widget.
The `cssClass` and `displayStyle` attributes may be set to control
the formatting of the value.
`displayStyle` must be one of 'full', 'long', 'medium', 'short',
or None ('' is accepted an an alternative to None to support
provision of a value from ZCML).
"""
cssClass = "date"
displayStyle = None
_category = "date"
def __call__(self):
if self._renderedValueSet():
content = self._data
else:
content = self.context.default
if content == self.context.missing_value:
return ""
formatter = self.request.locale.dates.getFormatter(
self._category, (self.displayStyle or None))
content = formatter.format(content)
return renderElement("span", contents=escape(content),
cssClass=self.cssClass)
class DatetimeDisplayWidget(DateDisplayWidget):
"""Datetime display widget.
The `cssClass` and `displayStyle` attributes may be set to control
the formatting of the value.
`displayStyle` must be one of 'full', 'long', 'medium', 'short',
or None ('' is accepted an an alternative to None to support
provision of a value from ZCML).
"""
cssClass = "dateTime"
_category = "dateTime" | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/textwidgets.py | textwidgets.py |
==============
Source Widgets
==============
Sources are objects that represent sets of values from which one might choose
and are used with `zope.schema.Choice` schema fields. Source widgets currently fall into two
categories:
- widgets for iterable sources
- widgets for queryable sources
Sources (combined with the available adapters) may support both approaches, but
no widgets currently support both.
In both cases, the widgets need views that can be used to get tokens to
represent source values in forms, as well as textual representations of values.
We use the `zope.browser.interfaces.ITerms` views for that.
All of our examples will be using the component architecture::
>>> import zope.interface
>>> import zope.component
>>> import zope.schema
This ``ITerms`` implementation can be used for the sources involved in
our tests::
>>> import base64
>>> import binascii
>>> from zope.browser.interfaces import ITerms
>>> import zope.publisher.interfaces.browser
>>> from zope.schema.vocabulary import SimpleTerm
>>> from zope.formlib._compat import toStr
>>> @zope.interface.implementer(ITerms)
... class ListTerms:
...
... def __init__(self, source, request):
... pass # We don't actually need the source or the request :)
...
... def getTerm(self, value):
... title = toStr(value)
... try:
... token = base64.b64encode(title.encode()).strip().decode()
... except binascii.Error:
... raise LookupError(token)
... return SimpleTerm(value, token=token, title=title)
...
... def getValue(self, token):
... return base64.b64decode(token).decode()
This view just uses the unicode representations of values as titles and the
base-64 encoding of the titles as tokens. This is a very simple strategy
that's only approriate when the values have short and unique unicode
representations.
All of the source widgets are in a single module::
>>> import zope.formlib.source
We'll also need request objects::
>>> from zope.publisher.browser import TestRequest
Iterable Source Widgets
=======================
Iterable sources are expected to be simpler than queriable sources, so
they represent a good place to start. The most important aspect of
iterable sources for widgets is that it's actually possible to
enumerate all the values from the source. This allows each possible
value to be listed in a ``<select>`` form field.
Let's start with a simple example. We have a very trivial source,
which is basically a list::
>>> @zope.interface.implementer(zope.schema.interfaces.IIterableSource)
... class SourceList(list):
... pass
We need to register our ``ITerms`` view::
>>> zope.component.provideAdapter(
... ListTerms,
... (SourceList, zope.publisher.interfaces.browser.IBrowserRequest))
Let's define a choice field using our iterable source::
>>> dog = zope.schema.Choice(
... __name__ = 'dog',
... title=u"Dogs",
... source=SourceList(['spot', 'bowser', 'prince', 'duchess', 'lassie']),
... )
>>> dog = dog.bind(object())
When we get a choice input widget for a choice field, the default widget
factory gets a view on the field and the field's source. We'll just create the
view directly::
>>> request = TestRequest()
>>> widget = zope.formlib.source.SourceSelectWidget(
... dog, dog.source, request)
>>> print(widget())
<div>
<div class="value">
<select id="field.dog" name="field.dog" size="5" >
<option value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option value="bGFzc2ll">lassie</option>
</select>
</div>
<input name="field.dog-empty-marker" type="hidden" value="1" />
</div>
Since the field is required, an empty selection is not valid:
>>> widget.getInputValue() #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
MissingInputError: ('field.dog', 'Dogs', None)
Also, the widget is required in this case:
>>> widget.required
True
If the request contains a value, it is marked as selected::
>>> request.form["field.dog-empty-marker"] = "1"
>>> request.form["field.dog"] = "Ym93c2Vy"
>>> print(widget())
<div>
<div class="value">
<select id="field.dog" name="field.dog" size="5" >
<option value="c3BvdA==">spot</option>
<option selected="selected" value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option value="bGFzc2ll">lassie</option>
</select>
</div>
<input name="field.dog-empty-marker" type="hidden" value="1" />
</div>
If we set the displayed value for the widget, that value is marked as
selected::
>>> widget.setRenderedValue("duchess")
>>> print(widget())
<div>
<div class="value">
<select id="field.dog" name="field.dog" size="5" >
<option value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option selected="selected" value="ZHVjaGVzcw==">duchess</option>
<option value="bGFzc2ll">lassie</option>
</select>
</div>
<input name="field.dog-empty-marker" type="hidden" value="1" />
</div>
Dropdown widgets are achieved with `.SourceDropdownWidget`, which simply
generates a selection list of size 1::
>>> request = TestRequest()
>>> widget = zope.formlib.source.SourceDropdownWidget(
... dog, dog.source, request)
>>> print(widget()) # doctest: +ELLIPSIS
<div>
<div class="value">
<select id="field.dog" name="field.dog" size="1" >
<option selected="selected" value="">(nothing selected)</option>...
An alternative to `.SourceSelectWidget` for small numbers of items is
`.SourceRadioWidget` that provides a radio button group for the items::
>>> request = TestRequest()
>>> widget = zope.formlib.source.SourceRadioWidget(
... dog, dog.source, request)
>>> print(widget()) # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<label for="field.dog.0"><input class="radioType" id="field.dog.0"
name="field.dog" type="radio" value="c3BvdA==" /> spot</label><br
/><label for="field.dog.1"><input class="radioType" id="field.dog.1"
name="field.dog" type="radio" value="Ym93c2Vy" /> bowser</label><br
/><label for="field.dog.2"><input class="radioType" id="field.dog.2"
name="field.dog" type="radio" value="cHJpbmNl" /> prince</label><br
/><label for="field.dog.3"><input class="radioType" id="field.dog.3"
name="field.dog" type="radio" value="ZHVjaGVzcw==" /> duchess</label><br
/><label for="field.dog.4"><input class="radioType" id="field.dog.4"
name="field.dog" type="radio" value="bGFzc2ll" /> lassie</label>
</div>
<input name="field.dog-empty-marker" type="hidden" value="1" />
</div>
We'll select an item by setting the appropriate fields in the request::
>>> request.form['field.dog-empty-marker'] = '1'
>>> request.form['field.dog'] = 'bGFzc2ll'
>>>
>>> widget = zope.formlib.source.SourceRadioWidget(
... dog, dog.source, request)
>>> print(widget()) # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<label for="field.dog.0"><input class="radioType" id="field.dog.0"
name="field.dog" type="radio" value="c3BvdA==" /> spot</label><br
/><label for="field.dog.1"><input class="radioType" id="field.dog.1"
name="field.dog" type="radio" value="Ym93c2Vy" /> bowser</label><br
/><label for="field.dog.2"><input class="radioType" id="field.dog.2"
name="field.dog" type="radio" value="cHJpbmNl" /> prince</label><br
/><label for="field.dog.3"><input class="radioType" id="field.dog.3"
name="field.dog" type="radio" value="ZHVjaGVzcw==" /> duchess</label><br
/><label for="field.dog.4"><input class="radioType" checked="checked"
id="field.dog.4" name="field.dog" type="radio" value="bGFzc2ll"
/> lassie</label>
</div>
<input name="field.dog-empty-marker" type="hidden" value="1" />
</div>
For list-valued fields with items chosen from iterable sources, there are the
`.SourceMultiSelectWidget` and `.SourceOrderedMultiSelectWidget` widgets. The latter
widget includes support for re-ording the list items.
`.SourceOrderedMultiSelectWidget` is configured as the default widget for lists of
choices.
If you don't need ordering support through the web UI, then you can use
the simpler `.SourceMultiSelectWidget`::
>>> dogSource = SourceList([
... 'spot', 'bowser', 'prince', 'duchess', 'lassie'])
>>> dogs = zope.schema.List(
... __name__ = 'dogs',
... title=u"Dogs",
... value_type=zope.schema.Choice(
... source=dogSource,
... )
... )
>>> dogs = dogs.bind(object()) # give the field a context
>>> request = TestRequest()
>>> widget = zope.formlib.source.SourceMultiSelectWidget(
... dogs, dogSource, request)
Let's look at the rendered widget::
>>> print(widget()) # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<select id="field.dogs" multiple="multiple" name="field.dogs:list"
size="5" ><option value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option value="bGFzc2ll">lassie</option></select>
</div>
<input name="field.dogs-empty-marker" type="hidden" value="1" />
</div>
We have no input yet::
>>> try:
... widget.getInputValue()
... except zope.formlib.interfaces.MissingInputError:
... print('no input')
no input
Select an item::
>>> request.form['field.dogs-empty-marker'] = '1'
>>> request.form['field.dogs'] = ['bGFzc2ll']
>>> widget.getInputValue()
['lassie']
and another::
>>> request.form['field.dogs'] = ['cHJpbmNl', 'bGFzc2ll']
>>> widget.getInputValue()
['prince', 'lassie']
Finally, what does the widget look like now::
>>> print(widget()) # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<select id="field.dogs" multiple="multiple" name="field.dogs:list"
size="5" ><option value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option selected="selected" value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option selected="selected" value="bGFzc2ll">lassie</option></select>
</div>
<input name="field.dogs-empty-marker" type="hidden" value="1" />
</div>
An alternative for small numbers of items is to use `.SourceMultiCheckBoxWidget`::
>>> request = TestRequest()
>>> widget = zope.formlib.source.SourceMultiCheckBoxWidget(
... dogs, dogSource, request)
The rendered widget::
>>> print(widget()) # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<label for="field.dogs.0"><input class="checkboxType" id="field.dogs.0"
name="field.dogs" type="checkbox" value="c3BvdA==" /> spot</label><br
/><label for="field.dogs.1"><input class="checkboxType" id="field.dogs.1"
name="field.dogs" type="checkbox" value="Ym93c2Vy"
/> bowser</label><br
/><label for="field.dogs.2"><input class="checkboxType" id="field.dogs.2"
name="field.dogs" type="checkbox" value="cHJpbmNl"
/> prince</label><br
/><label for="field.dogs.3"><input class="checkboxType" id="field.dogs.3"
name="field.dogs" type="checkbox"
value="ZHVjaGVzcw==" /> duchess</label><br
/><label for="field.dogs.4"><input class="checkboxType" id="field.dogs.4"
name="field.dogs" type="checkbox" value="bGFzc2ll"
/> lassie</label>
</div>
<input name="field.dogs-empty-marker" type="hidden" value="1" />
</div>
We have no input yet::
>>> try:
... widget.getInputValue()
... except zope.formlib.interfaces.MissingInputError:
... print('no input')
no input
Select an item::
>>> request.form['field.dogs-empty-marker'] = '1'
>>> request.form['field.dogs'] = ['bGFzc2ll']
>>> widget.getInputValue()
['lassie']
and another::
>>> request.form['field.dogs'] = ['c3BvdA==', 'bGFzc2ll']
>>> widget.getInputValue()
['spot', 'lassie']
Finally, what does the widget look like now::
>>> print(widget()) # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<label for="field.dogs.0"><input class="checkboxType" checked="checked"
id="field.dogs.0" name="field.dogs" type="checkbox" value="c3BvdA=="
/> spot</label><br
/><label for="field.dogs.1"><input class="checkboxType" id="field.dogs.1"
name="field.dogs" type="checkbox" value="Ym93c2Vy"
/> bowser</label><br
/><label for="field.dogs.2"><input class="checkboxType" id="field.dogs.2"
name="field.dogs" type="checkbox" value="cHJpbmNl"
/> prince</label><br
/><label for="field.dogs.3"><input class="checkboxType" id="field.dogs.3"
name="field.dogs" type="checkbox"
value="ZHVjaGVzcw==" /> duchess</label><br
/><label for="field.dogs.4"><input class="checkboxType" checked="checked"
id="field.dogs.4" name="field.dogs" type="checkbox" value="bGFzc2ll"
/> lassie</label>
</div>
<input name="field.dogs-empty-marker" type="hidden" value="1" />
</div>
For list ordering support, use `.SourceOrderedMultiSelectWidget`::
>>> request = TestRequest()
>>> widget = zope.formlib.source.SourceOrderedMultiSelectWidget(
... dogs, dogSource, request)
The widget is too complicated to show in complete rendered form here.
Insted, we'll inspect the properties of the widget::
>>> from zope.formlib.interfaces import MissingInputError
>>> try:
... widget.getInputValue()
... except MissingInputError:
... print('no input')
no input
>>> widget.choices() == [
... {'text': 'spot', 'value': 'c3BvdA=='},
... {'text': 'bowser', 'value': 'Ym93c2Vy'},
... {'text': 'prince', 'value': 'cHJpbmNl'},
... {'text': 'duchess', 'value': 'ZHVjaGVzcw=='},
... {'text': 'lassie', 'value': 'bGFzc2ll'}
... ]
True
>>> widget.selected()
[]
Let's try out selecting items. Select one item::
>>> request.form['field.dogs-empty-marker'] = '1'
>>> request.form['field.dogs'] = ['bGFzc2ll']
>>> from pprint import pprint
>>> pprint(widget.selected()) # doctest: +NORMALIZE_WHITESPACE
[{'text': 'lassie', 'value': 'bGFzc2ll'}]
>>> widget.getInputValue()
['lassie']
Select two items::
>>> request.form['field.dogs'] = ['c3BvdA==', 'bGFzc2ll']
>>> pprint(widget.selected()) # doctest: +NORMALIZE_WHITESPACE
[{'text': 'spot', 'value': 'c3BvdA=='},
{'text': 'lassie', 'value': 'bGFzc2ll'}]
>>> widget.getInputValue()
['spot', 'lassie']
For set-valued fields, use `.SourceMultiSelectSetWidget`::
>>> dogSet = zope.schema.Set(
... __name__ = 'dogSet',
... title=u"Dogs",
... value_type=zope.schema.Choice(
... source=dogSource,
... )
... )
>>> dogSet = dogSet.bind(object()) # give the field a context
>>> request = TestRequest()
>>> widget = zope.formlib.source.SourceMultiSelectSetWidget(
... dogSet, dogSource, request)
>>> try:
... widget.getInputValue()
... except zope.formlib.interfaces.MissingInputError:
... print('no input')
no input
>>> print(widget()) # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<select id="field.dogSet" multiple="multiple"
name="field.dogSet:list" size="5" ><option value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option value="bGFzc2ll">lassie</option></select>
</div>
<input name="field.dogSet-empty-marker" type="hidden" value="1" />
</div>
Let's try out selecting items. Select one item::
>>> request.form['field.dogSet-empty-marker'] = '1'
>>> request.form['field.dogSet'] = ['bGFzc2ll']
>>> widget.getInputValue()
{'lassie'}
Select two items::
>>> request.form['field.dogSet'] = ['c3BvdA==', 'bGFzc2ll']
>>> sorted(widget.getInputValue())
['lassie', 'spot']
The rendered widget (still with the two items selected) looks like this::
>>> print(widget()) # doctest: +NORMALIZE_WHITESPACE
<div>
<div class="value">
<select id="field.dogSet" multiple="multiple"
name="field.dogSet:list" size="5" ><option selected="selected"
value="c3BvdA==">spot</option>
<option value="Ym93c2Vy">bowser</option>
<option value="cHJpbmNl">prince</option>
<option value="ZHVjaGVzcw==">duchess</option>
<option selected="selected" value="bGFzc2ll">lassie</option></select>
</div>
<input name="field.dogSet-empty-marker" type="hidden" value="1" />
</div>
Source Widget Query Framework
=============================
An important aspect of sources is that they may have too many values to
enumerate. Rather than listing all of the values, we, instead, provide
interfaces for querying values and selecting values from query results.
Matters are further complicated by the fact that different sources may have
very different interfaces for querying them.
To make matters more interesting, a source may be an aggregation of several
collections, each with their own querying facilities. An example of such a
source is a principal source, where principals might come from a number of
places, such as an LDAP database and ZCML-based principal definitions.
The default widgets for selecting values from sources use the
following approach:
- One or more query objects are obtained from the source by adapting the source
to `zope.schema.interfaces.ISourceQueriables`. If no adapter is obtained, then the
source itself is assumed to be queriable.
- For each queriable found, a
`zope.formlib.interfaces.ISourceQueryView` view is looked up. This
view is used to obtain the HTML for displaying a query form. The view is also
used to obtain search results.
Let's start with a simple example. We have a very trivial source,
which is basically a list:
>>> @zope.interface.implementer(zope.schema.interfaces.ISource)
... class SourceList(list):
... pass
We need to register our ``ITerms`` view::
>>> zope.component.provideAdapter(
... ListTerms,
... (SourceList, zope.publisher.interfaces.browser.IBrowserRequest))
We aren't going to provide an adapter to ``ISourceQueriables``, so the source
itself will be used as it's own queriable. We need to provide a query view
for the source::
>>> @zope.interface.implementer(
... zope.formlib.interfaces.ISourceQueryView)
... @zope.component.adapter(
... SourceList,
... zope.publisher.interfaces.browser.IBrowserRequest,
... )
... class ListQueryView:
...
... def __init__(self, source, request):
... self.source = source
... self.request = request
...
... def render(self, name):
... return (
... '<input name="%s.string">\n'
... '<input type="submit" name="%s" value="Search">'
... % (name, name)
... )
...
... def results(self, name):
... if name in self.request:
... search_string = self.request.get(name+'.string')
... if search_string is not None:
... return [value
... for value in self.source
... if search_string in value
... ]
... return None
>>> zope.component.provideAdapter(ListQueryView)
Now, we can define a choice field::
>>> dog = zope.schema.Choice(
... __name__ = 'dog',
... title=u"Dogs",
... source=SourceList(['spot', 'bowser', 'prince', 'duchess', 'lassie']),
... )
As before, we'll just create the view directly::
>>> request = TestRequest()
>>> widget = zope.formlib.source.SourceInputWidget(
... dog, dog.source, request)
Now if we render the widget, we'll see the input value (initially nothing) and
a form elements for seaching for values::
>>> print(widget())
<div class="value">
<div class="row">
<div class="label">
Selected
</div>
<div class="field">
Nothing
</div>
</div>
<input type="hidden" name="field.dog.displayed" value="y" />
<div class="queries">
<div class="query">
<div class="queryinput">
<input name="field.dog.query.string">
<input type="submit" name="field.dog.query" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
</div> <!-- queries -->
</div> <!-- value -->
This shows that we haven't selected a dog. We get a search box that we can type
seach strings into. Let's supply a search string. We do this by providing data
in the form and by "selecting" the submit button::
>>> request.form['field.dog.displayed'] = 'y'
>>> request.form['field.dog.query.string'] = 'o'
>>> request.form['field.dog.query'] = 'Search'
Because the field is required, a non-selection is not valid. Thus,
while the widget still
`~zope.formlib.interfaces.IInputWidget.hasInput`, it will raise an
error when you `~zope.formlib.interfaces.IInputWidget.getInputValue`::
>>> widget.hasInput()
True
>>> widget.getInputValue() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
MissingInputError: ('dog', 'Dogs', None)
If the field is not required::
>>> dog.required = False
then as long as the field is displayed, the widget still has input but returns
the field's missing value::
>>> widget.hasInput()
True
>>> widget.getInputValue() # None
Now if we render the widget, we'll see the search results::
>>> dog.required = True
>>> print(widget())
<div class="value">
<div class="row">
<div class="label">
Selected
</div>
<div class="field">
Nothing
</div>
</div>
<input type="hidden" name="field.dog.displayed" value="y" />
<div class="queries">
<div class="query">
<div class="queryinput">
<input name="field.dog.query.string">
<input type="submit" name="field.dog.query" value="Search">
</div> <!-- queryinput -->
<div class="queryresults">
<select name="field.dog.query.selection">
<option value="Ym93c2Vy">bowser</option>
<option value="c3BvdA==">spot</option>
</select>
<input type="submit" name="field.dog.query.apply" value="Apply" />
</div> <!-- queryresults -->
</div> <!-- query -->
</div> <!-- queries -->
</div> <!-- value -->
If we select an item::
>>> request.form['field.dog.displayed'] = 'y'
>>> del request.form['field.dog.query.string']
>>> del request.form['field.dog.query']
>>> request.form['field.dog.query.selection'] = 'c3BvdA=='
>>> request.form['field.dog.query.apply'] = 'Apply'
Then we'll show the newly selected value::
>>> print(widget())
<div class="value">
<div class="row">
<div class="label">
Selected
</div>
<div class="field">
spot
</div>
</div>
<input type="hidden" name="field.dog" value="c3BvdA==" />
<input type="hidden" name="field.dog.displayed" value="y" />
<div class="queries">
<div class="query">
<div class="queryinput">
<input name="field.dog.query.string">
<input type="submit" name="field.dog.query" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
</div> <!-- queries -->
</div> <!-- value -->
Note that we should have an input value now, since pressing the 'Apply' button
provides us with input::
>>> widget.hasInput()
True
We should also be able to get the input value::
>>> widget.getInputValue()
'spot'
Now, let's look at a more complicated example. We'll define a source that
combines multiple sources::
>>> @zope.interface.implementer(
... zope.schema.interfaces.ISource,
... zope.schema.interfaces.ISourceQueriables,
... )
... class MultiSource:
...
... def __init__(self, *sources):
... self.sources = [(toStr(i), s) for (i, s) in enumerate(sources)]
...
... def __contains__(self, value):
... for i, s in self.sources:
... if value in s:
... return True
... return False
...
... def getQueriables(self):
... return self.sources
This multi-source implements ``ISourceQueriables``. It assumes that the sources
it's given are queriable and just returns the sources as the queryable objects.
We can reuse our terms view::
>>> zope.component.provideAdapter(
... ListTerms,
... (MultiSource, zope.publisher.interfaces.browser.IBrowserRequest))
Now, we'll create a pet choice that combines dogs and cats::
>>> pet = zope.schema.Choice(
... __name__ = 'pet',
... title=u"Dogs and Cats",
... source=MultiSource(
... dog.source,
... SourceList(['boots', 'puss', 'tabby', 'tom', 'tiger']),
... ),
... )
and a widget::
>>> widget = zope.formlib.source.SourceInputWidget(
... pet, pet.source, request)
Now if we display the widget, we'll see search inputs for both dogs
and cats::
>>> print(widget())
<div class="value">
<div class="row">
<div class="label">
Selected
</div>
<div class="field">
Nothing
</div>
</div>
<input type="hidden" name="field.pet.displayed" value="y" />
<div class="queries">
<div class="query">
<div class="queryinput">
<input name="field.pet.MA__.string">
<input type="submit" name="field.pet.MA__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
<div class="query">
<div class="queryinput">
<input name="field.pet.MQ__.string">
<input type="submit" name="field.pet.MQ__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
</div> <!-- queries -->
</div> <!-- value -->
As before, we can perform a search::
>>> request.form['field.pet.displayed'] = 'y'
>>> request.form['field.pet.MQ__.string'] = 't'
>>> request.form['field.pet.MQ__'] = 'Search'
In which case, we'll get some results::
>>> print(widget())
<div class="value">
<div class="row">
<div class="label">
Selected
</div>
<div class="field">
Nothing
</div>
</div>
<input type="hidden" name="field.pet.displayed" value="y" />
<div class="queries">
<div class="query">
<div class="queryinput">
<input name="field.pet.MA__.string">
<input type="submit" name="field.pet.MA__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
<div class="query">
<div class="queryinput">
<input name="field.pet.MQ__.string">
<input type="submit" name="field.pet.MQ__" value="Search">
</div> <!-- queryinput -->
<div class="queryresults">
<select name="field.pet.MQ__.selection">
<option value="Ym9vdHM=">boots</option>
<option value="dGFiYnk=">tabby</option>
<option value="dGlnZXI=">tiger</option>
<option value="dG9t">tom</option>
</select>
<input type="submit" name="field.pet.MQ__.apply" value="Apply" />
</div> <!-- queryresults -->
</div> <!-- query -->
</div> <!-- queries -->
</div> <!-- value -->
from which we can choose::
>>> request.form['field.pet.displayed'] = 'y'
>>> del request.form['field.pet.MQ__.string']
>>> del request.form['field.pet.MQ__']
>>> request.form['field.pet.MQ__.selection'] = 'dGFiYnk='
>>> request.form['field.pet.MQ__.apply'] = 'Apply'
and get a selection::
>>> print(widget())
<div class="value">
<div class="row">
<div class="label">
Selected
</div>
<div class="field">
tabby
</div>
</div>
<input type="hidden" name="field.pet" value="dGFiYnk=" />
<input type="hidden" name="field.pet.displayed" value="y" />
<div class="queries">
<div class="query">
<div class="queryinput">
<input name="field.pet.MA__.string">
<input type="submit" name="field.pet.MA__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
<div class="query">
<div class="queryinput">
<input name="field.pet.MQ__.string">
<input type="submit" name="field.pet.MQ__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
</div> <!-- queries -->
</div> <!-- value -->
Note that we should have an input value now, since pressing the 'Apply' button
provides us with input::
>>> widget.hasInput()
True
and we can get the input value::
>>> widget.getInputValue()
'tabby'
There's a display widget, which doesn't use queriables, since it doesn't assign
values::
>>> request = TestRequest()
>>> widget = zope.formlib.source.SourceDisplayWidget(
... pet, pet.source, request)
>>> print(widget())
Nothing
>>> from zope.formlib.interfaces import IBrowserWidget
>>> IBrowserWidget.providedBy(widget)
True
>>> widget.setRenderedValue('tabby')
>>> print(widget())
tabby
Like any good display widget, input is not required::
>>> widget.required
False
If we specify a list of choices::
>>> pets = zope.schema.List(__name__ = 'pets', title=u"Pets",
... value_type=pet)
when a widget is computed for the field, a view will be looked up for the field
and the source, where, in this case, the field is a list field. We'll just call
the widget factory directly::
>>> widget = zope.formlib.source.SourceListInputWidget(
... pets, pets.value_type.source, request)
If we render the widget::
>>> print(widget())
<div class="value">
<input type="hidden" name="field.pets.displayed" value="y" />
<div class="queries">
<div class="query">
<div class="queryinput">
<input name="field.pets.MA__.string">
<input type="submit" name="field.pets.MA__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
<div class="query">
<div class="queryinput">
<input name="field.pets.MQ__.string">
<input type="submit" name="field.pets.MQ__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
</div> <!-- queries -->
</div> <!-- value -->
Here the output looks very similar to the simple choice case. We get a search
input for each source. In this case, we don't show any inputs
(TODO we probably should make it clearer that there are no selected values.)
As before, we can search one of the sources::
>>> request.form['field.pets.displayed'] = 'y'
>>> request.form['field.pets.MQ__.string'] = 't'
>>> request.form['field.pets.MQ__'] = 'Search'
In which case, we'll get some results::
>>> print(widget())
<div class="value">
<input type="hidden" name="field.pets.displayed" value="y" />
<div class="queries">
<div class="query">
<div class="queryinput">
<input name="field.pets.MA__.string">
<input type="submit" name="field.pets.MA__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
<div class="query">
<div class="queryinput">
<input name="field.pets.MQ__.string">
<input type="submit" name="field.pets.MQ__" value="Search">
</div> <!-- queryinput -->
<div class="queryresults">
<select name="field.pets.MQ__.selection:list" multiple>
<option value="Ym9vdHM=">boots</option>
<option value="dGFiYnk=">tabby</option>
<option value="dGlnZXI=">tiger</option>
<option value="dG9t">tom</option>
</select>
<input type="submit" name="field.pets.MQ__.apply" value="Apply" />
</div> <!-- queryresults -->
</div> <!-- query -->
</div> <!-- queries -->
</div> <!-- value -->
from which we can select some values::
>>> request.form['field.pets.displayed'] = 'y'
>>> del request.form['field.pets.MQ__.string']
>>> del request.form['field.pets.MQ__']
>>> request.form['field.pets.MQ__.selection'] = [
... 'dGFiYnk=', 'dGlnZXI=', 'dG9t']
>>> request.form['field.pets.MQ__.apply'] = 'Apply'
Which then leads to the selections appearing as widget selections::
>>> print(widget())
<div class="value">
<input type="checkbox" name="field.pets.checked:list" value="dGFiYnk=" />
tabby
<input type="hidden" name="field.pets:list" value="dGFiYnk=" />
<br />
<input type="checkbox" name="field.pets.checked:list" value="dGlnZXI=" />
tiger
<input type="hidden" name="field.pets:list" value="dGlnZXI=" />
<br />
<input type="checkbox" name="field.pets.checked:list" value="dG9t" />
tom
<input type="hidden" name="field.pets:list" value="dG9t" />
<br />
<input type="submit" name="field.pets.remove" value="Remove" />
<br />
<input type="hidden" name="field.pets.displayed" value="y" />
<div class="queries">
<div class="query">
<div class="queryinput">
<input name="field.pets.MA__.string">
<input type="submit" name="field.pets.MA__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
<div class="query">
<div class="queryinput">
<input name="field.pets.MQ__.string">
<input type="submit" name="field.pets.MQ__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
</div> <!-- queries -->
</div> <!-- value -->
We can get the selected values::
>>> widget.getInputValue()
['tabby', 'tiger', 'tom']
We now see the values we selected. We also have checkboxes and buttons that
allow us to remove selections::
>>> request.form['field.pets.displayed'] = 'y'
>>> request.form['field.pets'] = ['dGFiYnk=', 'dGlnZXI=', 'dG9t']
>>> del request.form['field.pets.MQ__.selection']
>>> del request.form['field.pets.MQ__.apply']
>>> request.form['field.pets.checked'] = ['dGFiYnk=', 'dG9t']
>>> request.form['field.pets.remove'] = 'Remove'
>>> print(widget())
<div class="value">
<input type="checkbox" name="field.pets.checked:list" value="dGlnZXI=" />
tiger
<input type="hidden" name="field.pets:list" value="dGlnZXI=" />
<br />
<input type="submit" name="field.pets.remove" value="Remove" />
<br />
<input type="hidden" name="field.pets.displayed" value="y" />
<div class="queries">
<div class="query">
<div class="queryinput">
<input name="field.pets.MA__.string">
<input type="submit" name="field.pets.MA__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
<div class="query">
<div class="queryinput">
<input name="field.pets.MQ__.string">
<input type="submit" name="field.pets.MQ__" value="Search">
</div> <!-- queryinput -->
</div> <!-- query -->
</div> <!-- queries -->
</div> <!-- value -->
Using vocabulary-dependent widgets with sources
===============================================
if you have a widget that uses old-style vocabularies but don't have the time
to rewrite it for sources, all is not lost! The wrapper
`.IterableSourceVocabulary` can be used to make sources and ``ITerms`` look like a
vocabulary. This allows us to use vocabulary-based widgets with sources
instead of vocabularies.
Usage::
>>> from zope.schema.vocabulary import SimpleTerm
>>> values = ['a', 'b', 'c']
>>> tokens = [ '0', '1', '2']
>>> titles = ['A', 'B', 'C']
>>> terms = [SimpleTerm(values[i], token=tokens[i], title=titles[i]) \
... for i in range(0,len(values))]
>>> @zope.interface.implementer(zope.schema.interfaces.IIterableSource)
... class TestSource(list):
... pass
>>> source = TestSource(values)
>>> @zope.interface.implementer(ITerms)
... class TestTerms(object):
... def __init__(self, source, request):
... pass
... def getTerm(self, value):
... index = values.index(value)
... return terms[index]
... def getValue(self, token):
... index = tokens.index(token)
... return values[index]
>>> zope.component.provideAdapter(
... TestTerms,
... (TestSource, zope.publisher.interfaces.browser.IBrowserRequest))
>>> from zope.formlib.source import IterableSourceVocabulary
>>> request = TestRequest()
>>> vocab = IterableSourceVocabulary(source, request)
>>> from zope.interface.verify import verifyClass, verifyObject
>>> verifyClass(zope.schema.interfaces.IVocabularyTokenized, \
... IterableSourceVocabulary)
True
>>> verifyObject(zope.schema.interfaces.IVocabularyTokenized, vocab)
True
>>> len(vocab)
3
>>> ('a' in vocab) and ('b' in vocab) and ('c' in vocab)
True
>>> [value for value in vocab] == terms
True
>>> term = vocab.getTerm('b')
>>> (term.value, term.token, term.title)
('b', '1', 'B')
>>> term = vocab.getTermByToken('2')
>>> (term.value, term.token, term.title)
('c', '2', 'C')
| zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/source.rst | source.rst |
=============
Object Widget
=============
The following example shows a ``Family`` with ``Mother`` and ``Father``.
First define the interface for a person:
>>> from zope.interface import Interface, implementer
>>> from zope.schema import TextLine
>>> class IPerson(Interface):
... """Interface for Persons."""
...
... name = TextLine(title='Name', description='The first name')
Let's define the class:
>>> @implementer(IPerson)
... class Person(object):
... def __init__(self, name=''):
... self.name = name
Let's define the interface family:
>>> from zope.schema import Object
>>> class IFamily(Interface):
... """The familiy interface."""
...
... mother = Object(title='Mother',
... required=False,
... schema=IPerson)
...
... father = Object(title='Father',
... required=False,
... schema=IPerson)
Let's define the class ``Family`` using
`zope.schema.fieldproperty.FieldProperty` for ``mother`` and ``father``.
``FieldProperty`` instances validate the values if they get added:
>>> from zope.schema.fieldproperty import FieldProperty
>>> @implementer(IFamily)
... class Family(object):
... """The familiy interface."""
... mother = FieldProperty(IFamily['mother'])
... father = FieldProperty(IFamily['father'])
...
... def __init__(self, mother=None, father=None):
... self.mother = mother
... self.father = father
Let's make an instance of Family with `None` attributes:
>>> family = Family()
>>> bool(family.mother == None)
True
>>> bool(family.father == None)
True
Let's make an instance of Family with None attributes:
>>> mother = Person('Margrith')
>>> father = Person('Joe')
>>> family = Family(mother, father)
>>> IPerson.providedBy(family.mother)
True
>>> IPerson.providedBy(family.father)
True
Let's define a dummy class which doesn't implements IPerson:
>>> class Dummy(object):
... """Dummy class."""
... def __init__(self, name=''):
... self.name = name
Raise a `zope.schema.interfaces.SchemaNotProvided` exception if we add a Dummy instance to a Family
object:
>>> foo = Dummy('foo')
>>> bar = Dummy('bar')
>>> family = Family(foo, bar)
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
SchemaNotProvided
Now let's setup a enviroment for use the widget like in a real application:
>>> from zope.publisher.browser import TestRequest
>>> from zope.schema.interfaces import ITextLine
>>> from zope.schema import TextLine
>>> from zope.formlib.widgets import TextWidget
>>> from zope.formlib.widgets import ObjectWidget
>>> from zope.formlib.interfaces import IInputWidget
Register the `zope.schema.TextLine` widget used in the IPerson interface for the field 'name'.
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from zope.component import provideAdapter
>>> provideAdapter(TextWidget, (ITextLine, IDefaultBrowserLayer),
... IInputWidget)
Let's define a request and provide input value for the mothers name used
in the family object:
>>> request = TestRequest(HTTP_ACCEPT_LANGUAGE='pl')
>>> request.form['field.mother.name'] = 'Margrith Ineichen'
Before we update the object let's check the value name of the mother
instance on the family object:
>>> family.mother.name
'Margrith'
Now let's initialize a `.ObjectWidget` with the right attributes:
>>> mother_field = IFamily['mother']
>>> factory = Person
>>> widget = ObjectWidget(mother_field, request, factory)
Now comes the magic. Apply changes means we force the `.ObjectWidget` to read
the request, extract the value and save it on the content. The `.ObjectWidget`
instance uses a real Person class (factory) for add the value. The value is
temporary stored in this factory class. The `.ObjectWidget` reads the value from
this factory and set it to the attribute 'name' of the instance mother
(The object mother is already there). If we don't have an instance mother
already stored in the family object, the factory instance will be stored
directly to the family attribute mother. For more information see the method
`zope.formlib.objectwidget.ObjectWidget.applyChanges`.
>>> widget.applyChanges(family)
True
Test the updated mother's name value on the object family:
>>> family.mother.name
'Margrith Ineichen'
>>> IPerson.providedBy(family.mother)
True
So, now you know my mothers and fathers name. I hope it's also clear how to
use the `zope.schema.Object` field and the `.ObjectWidget`.
| zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/objectwidget.rst | objectwidget.rst |
"""Browser Widget Definitions
"""
__docformat__ = 'restructuredtext'
import warnings
from xml.sax.saxutils import escape
from xml.sax.saxutils import quoteattr
from zope.component import getMultiAdapter
from zope.i18n import translate
from zope.interface import implementer
from zope.publisher.browser import BrowserView
from zope.schema.interfaces import IChoice
from zope.schema.interfaces import ICollection
from zope.schema.interfaces import ValidationError
from zope.formlib._compat import toStr
from zope.formlib.interfaces import ConversionError
from zope.formlib.interfaces import IBrowserWidget
from zope.formlib.interfaces import InputErrors
from zope.formlib.interfaces import ISimpleInputWidget
from zope.formlib.interfaces import IWidget
from zope.formlib.interfaces import IWidgetFactory
from zope.formlib.interfaces import IWidgetInputErrorView
from zope.formlib.interfaces import MissingInputError
from zope.formlib.interfaces import WidgetInputError
if quoteattr("\r") != '"&13;"':
_quoteattr = quoteattr
def quoteattr(data):
return _quoteattr(
data, {'\n': ' ', '\r': ' ', '\t': '	'})
@implementer(IWidget)
class Widget:
"""Mixin class providing functionality common across widget types."""
_prefix = 'field.'
_data_marker = object()
_data = _data_marker
visible = True
def __init__(self, context, request):
self.context = context
self.request = request
self.name = self._prefix + context.__name__
self.label = self.context.title
self.hint = self.context.description
def _translate(self, text):
return translate(text, context=self.request, default=text)
def _renderedValueSet(self):
"""Returns ``True`` if the the widget's rendered value has been set.
This is a convenience method that widgets can use to check whether
or not `setRenderedValue` was called.
"""
return self._data is not self._data_marker
def setPrefix(self, prefix):
if prefix and not prefix.endswith("."):
prefix += '.'
self._prefix = prefix
self.name = prefix + self.context.__name__
def setRenderedValue(self, value):
self._data = value
class InputWidget(Widget):
"""Mixin class providing some default input widget methods."""
def hasValidInput(self):
try:
self.getInputValue()
return True
except InputErrors:
return False
def applyChanges(self, content):
field = self.context
value = self.getInputValue()
if field.query(content, self) != value:
field.set(content, value)
return True
else:
return False
@implementer(IWidgetFactory)
class CustomWidgetFactory:
"""Custom Widget Factory."""
def __init__(self, widget_factory, *args, **kw):
self._widget_factory = widget_factory
self.args = args
self.kw = kw
def _create(self, args):
instance = self._widget_factory(*args)
for name, value in self.kw.items():
setattr(instance, name, value)
return instance
def __call__(self, context, request):
# Sequence widget factory
if ICollection.providedBy(context):
args = (context, context.value_type, request) + self.args
# Vocabulary widget factory
elif IChoice.providedBy(context):
args = (context, context.vocabulary, request) + self.args
# Regular widget factory
else:
args = (context, request) + self.args
return self._create(args)
@implementer(IBrowserWidget)
class BrowserWidget(Widget, BrowserView):
"""Base class for browser widgets.
>>> setUp()
The class provides some basic functionality common to all browser widgets.
Browser widgets have a `required` attribute, which indicates whether or
not the underlying field requires input. By default, the widget's required
attribute is equal to the field's required attribute:
>>> from zope.schema import Field
>>> from zope.publisher.browser import TestRequest
>>> field = Field(required=True)
>>> widget = BrowserWidget(field, TestRequest())
>>> widget.required
True
>>> field.required = False
>>> widget = BrowserWidget(field, TestRequest())
>>> widget.required
False
However, the two `required` values are independent of one another:
>>> field.required = True
>>> widget.required
False
Browser widgets have an error state, which can be rendered in a form using
the `error()` method. The error method delegates the error rendering to a
view that is registered as providing `IWidgetInputErrorView`. To
illustrate, we can create and register a simple error display view:
>>> from zope.component import provideAdapter
>>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer
>>> from zope.formlib.interfaces import IWidgetInputError
>>> @implementer(IWidgetInputErrorView)
... class SnippetErrorView:
... def __init__(self, context, request):
... self.context = context
... def snippet(self):
... return "The error: " + str(self.context.errors)
>>> provideAdapter(SnippetErrorView,
... (IWidgetInputError, IDefaultBrowserLayer),
... IWidgetInputErrorView, '')
Whever an error occurs, widgets should set _error:
>>> widget._error = WidgetInputError('foo', 'Foo', ('Err1', 'Err2'))
so that it can be displayed using the error() method:
>>> widget.error()
"The error: ('Err1', 'Err2')"
>>> tearDown()
"""
_error = None
def __init__(self, context, request):
super().__init__(context, request)
self.required = context.required
def error(self):
if self._error:
return getMultiAdapter((self._error, self.request),
IWidgetInputErrorView).snippet()
return ""
def hidden(self):
return ""
@implementer(ISimpleInputWidget)
class SimpleInputWidget(BrowserWidget, InputWidget):
"""A baseclass for simple HTML form widgets.
>>> setUp()
Simple input widgets read input from a browser form. To illustrate, we
will use a test request with two form values:
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest(form={
... 'field.foo': 'hello\\r\\nworld',
... 'baz.foo': 'bye world'})
Like all widgets, simple input widgets are a view to a field context:
>>> from zope.schema import Field
>>> field = Field(__name__='foo', title='Foo')
>>> widget = SimpleInputWidget(field, request)
Widgets are named using their field's name:
>>> widget.name
'field.foo'
The default implementation for the widget label is to use the field title:
>>> widget.label
'Foo'
According the request, the widget has input because 'field.foo' is
present:
>>> widget.hasInput()
True
>>> widget.getInputValue()
'hello\\r\\nworld'
Widgets maintain an error state, which is used to communicate invalid
input or other errors:
>>> widget._error is None
True
>>> widget.error()
''
`setRenderedValue` is used to specify the value displayed by the widget to
the user. This value, however, is not the same as the input value, which
is read from the request:
>>> widget.setRenderedValue('Hey\\nfolks')
>>> widget.getInputValue()
'hello\\r\\nworld'
>>> widget._error is None
True
>>> widget.error()
''
You can use 'setPrefix' to remove or modify the prefix used to create the
widget name as follows:
>>> widget.setPrefix('')
>>> widget.name
'foo'
>>> widget.setPrefix('baz')
>>> widget.name
'baz.foo'
`getInputValue` always returns a value that can legally be assigned to
the widget field. To illustrate widget validation, we can add a constraint
to its field:
>>> import re
>>> field.constraint = re.compile('.*hello.*').match
Because we modified the widget's name, the widget will now read different
form input:
>>> request.form[widget.name]
'bye world'
This input violates the new field constraint and therefore causes an
error when `getInputValue` is called:
>>> widget.getInputValue() #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
WidgetInputError: ('foo', 'Foo', ConstraintNotSatisfied('bye world'))
Simple input widgets require that input be available in the form request.
If input is not present, a ``MissingInputError`` is raised:
>>> del request.form[widget.name]
>>> widget.getInputValue() #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
MissingInputError: ('baz.foo', 'Foo', None)
A ``MissingInputError`` indicates that input is missing from the form
altogether. It does not indicate that the user failed to provide a value
for a required field. The ``MissingInputError`` above was caused by the
fact that the form does have any input for the widget:
>>> request.form[widget.name] #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
KeyError: 'baz.foo'
If a user fails to provide input for a field, the form will contain the
input provided by the user, namely an empty string:
>>> request.form[widget.name] = ''
In such a case, if the field is required, a ``WidgetInputError`` will be
raised on a call to `getInputValue`:
>>> field.required = True
>>> widget.getInputValue() #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
WidgetInputError: ('foo', 'Foo', RequiredMissing('foo'))
However, if the field is not required, the empty string will be converted
by the widget into the field's `missing_value` and read as a legal field
value:
>>> field.required = False
>>> widget.getInputValue() is field.missing_value
True
Another type of exception is a conversion error. It is raised when a value
cannot be converted to the desired Python object. Here is an example of a
floating point.
>>> from zope.schema import Float
>>> field = Float(__name__='price', title='Price')
>>> from zope.formlib.interfaces import ConversionError
>>> class FloatWidget(SimpleInputWidget):
... def _toFieldValue(self, input):
... try:
... return float(input)
... except ValueError as v:
... raise ConversionError('Invalid floating point data', v)
...
... def _toFormValue(self, value):
... value = super(FloatWidget, self)._toFormValue(value)
... return '%.2f' % value
>>> request = TestRequest(form={'field.price': '32.0'})
>>> widget = FloatWidget(field, request)
>>> widget.getInputValue()
32.0
>>> widget()
'<input class="textType" id="field.price" name="field.price" required="True" type="text" value="32.00" />'
>>> request = TestRequest(form={'field.price': '<p>foo</p>'})
>>> widget = FloatWidget(field, request)
>>> try:
... widget.getInputValue()
... except ConversionError as error:
... print(error.doc())
Invalid floating point data
>>> widget()
'<input class="textType" id="field.price" name="field.price" required="True" type="text" value="<p>foo</p>" />'
>>> tearDown()
""" # noqa: E501 line too long
tag = 'input'
type = 'text'
cssClass = ''
extra = ''
_missing = ''
def hasInput(self):
"""See IWidget.hasInput.
Returns ``True`` if the submitted request form contains a value for
the widget, otherwise returns False.
Some browser widgets may need to implement a more sophisticated test
for input. E.g. checkbox values are not supplied in submitted
forms when their value is 'off' -- in this case the widget will
need to add a hidden element to signal its presence in the form.
"""
return self.name in self.request.form
def getInputValue(self):
self._error = None
field = self.context
# form input is required, otherwise raise an error
if not self.hasInput():
raise MissingInputError(self.name, self.label, None)
# convert input to suitable value - may raise conversion error
try:
value = self._toFieldValue(self._getFormInput())
except ConversionError as error:
# ConversionError is already a WidgetInputError
self._error = error
raise self._error
# allow missing values only for non-required fields
if value == field.missing_value and not field.required:
return value
# value must be valid per the field constraints
try:
field.validate(value)
except ValidationError as v:
self._error = WidgetInputError(
self.context.__name__, self.label, v)
raise self._error
return value
def _getFormInput(self):
"""Returns current form input.
The value returned must be in a format that can be used as the 'input'
argument to `_toFieldValue`.
The default implementation returns the form value that corresponds to
the widget's name. Subclasses may override this method if their form
input consists of more than one form element or use an alternative
naming convention.
"""
return self.request.get(self.name)
def _toFieldValue(self, input):
"""Converts input to a value appropriate for the field type.
Widgets for non-string fields should override this method to
perform an appropriate conversion.
This method is used by getInputValue to perform the conversion
of form input (provided by `_getFormInput`) to an appropriate field
value.
"""
if input == self._missing:
return self.context.missing_value
else:
return input
def _toFormValue(self, value):
"""Converts a field value to a string used as an HTML form value.
This method is used in the default rendering of widgets that can
represent their values in a single HTML form value. Widgets whose
fields have more complex data structures should disregard this
method and override the default rendering method (__call__).
"""
if value == self.context.missing_value:
return self._missing
else:
return value
def _getCurrentValueHelper(self):
"""Helper to get the current input value.
Raises InputErrors if the data could not be validated/converted.
"""
input_value = None
if self._renderedValueSet():
input_value = self._data
else:
if self.hasInput():
# It's insane to use getInputValue this way. It can
# cause _error to get set spuriously. We'll work
# around this by saving and restoring _error if
# necessary.
error = self._error
try:
input_value = self.getInputValue()
finally:
self._error = error
else:
input_value = self._getDefault()
return input_value
def _getCurrentValue(self):
"""Returns the current input value.
Returns None if the data could not be validated/converted.
"""
try:
input_value = self._getCurrentValueHelper()
except InputErrors:
input_value = None
return input_value
def _getFormValue(self):
"""Returns a value suitable for use in an HTML form.
Detects the status of the widget and selects either the input value
that came from the request, the value from the _data attribute or the
default value.
"""
try:
input_value = self._getCurrentValueHelper()
except InputErrors:
form_value = self.request.form.get(self.name, self._missing)
else:
form_value = self._toFormValue(input_value)
return form_value
def _getDefault(self):
"""Returns the default value for this widget."""
return self.context.default
def __call__(self):
return renderElement(self.tag,
type=self.type,
name=self.name,
id=self.name,
value=self._getFormValue(),
cssClass=self.cssClass,
required=self.required,
extra=self.extra)
def hidden(self):
return renderElement(self.tag,
type='hidden',
name=self.name,
id=self.name,
value=self._getFormValue(),
cssClass=self.cssClass,
extra=self.extra)
class DisplayWidget(BrowserWidget):
def __init__(self, context, request):
super().__init__(context, request)
self.required = False
def __call__(self):
if self._renderedValueSet():
value = self._data
else:
value = self.context.default
if value == self.context.missing_value:
return ""
return escape(value)
class UnicodeDisplayWidget(DisplayWidget):
"""Display widget that converts the value to unicode before display."""
def __call__(self):
if self._renderedValueSet():
value = self._data
else:
value = self.context.default
if value == self.context.missing_value:
return ""
return escape(toStr(value))
def renderTag(tag, **kw):
"""Render the tag. Well, not all of it, as we may want to / it."""
attr_list = []
# special case handling for cssClass
cssClass = kw.pop('cssClass', '')
# If the 'type' attribute is given, append this plus 'Type' as a
# css class. This allows us to do subselector stuff in css without
# necessarily having a browser that supports css subselectors.
# This is important if you want to style radio inputs differently than
# text inputs.
cssWidgetType = kw.get('type', '')
if cssWidgetType:
cssWidgetType += 'Type'
names = [c for c in (cssClass, cssWidgetType) if c]
if names:
attr_list.append('class="%s"' % ' '.join(names))
style = kw.pop('style', '')
if style:
attr_list.append('style=%s' % quoteattr(style))
# special case handling for extra 'raw' code
if 'extra' in kw:
# could be empty string but we don't care
extra = " " + kw.pop('extra')
else:
extra = ''
# handle other attributes
if kw:
items = sorted(kw.items())
for key, value in items:
if value is None:
warnings.warn(
"None was passed for attribute %r. Passing None "
"as attribute values to renderTag is deprecated. "
"Passing None as an attribute value will be disallowed "
"starting in Zope 3.3."
% key,
DeprecationWarning, stacklevel=2)
value = key
attr_list.append('{}={}'.format(key, quoteattr(toStr(value))))
if attr_list:
attr_str = " ".join(attr_list)
return "<{} {}{}".format(tag, attr_str, extra)
else:
return "<{}{}".format(tag, extra)
def renderElement(tag, **kw):
contents = kw.pop('contents', None)
if contents is not None:
# Do not quote contents, since it often contains generated HTML.
return "{}>{}</{}>".format(renderTag(tag, **kw), contents, tag)
else:
return renderTag(tag, **kw) + " />"
def setUp():
import zope.component.testing
global setUp
setUp = zope.component.testing.setUp
setUp()
def tearDown():
import zope.component.testing
global tearDown
tearDown = zope.component.testing.tearDown
tearDown() | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/widget.py | widget.py |
"""Browser widgets for items
"""
__docformat__ = 'restructuredtext'
from xml.sax.saxutils import escape
from zope.browserpage import ViewPageTemplateFile
from zope.i18n import translate
from zope.schema.interfaces import InvalidValue
from zope.schema.interfaces import ITitledTokenizedTerm
from zope import component
from zope.formlib.i18n import _
from zope.formlib.interfaces import ConversionError
from zope.formlib.interfaces import IDisplayWidget
from zope.formlib.interfaces import IInputWidget
from zope.formlib.widget import SimpleInputWidget
from zope.formlib.widget import renderElement
# For choices, we want to make the widget a view of the field and vocabulary.
def ChoiceDisplayWidget(field, request):
return component.getMultiAdapter((field, field.vocabulary, request),
IDisplayWidget)
def ChoiceInputWidget(field, request):
return component.getMultiAdapter((field, field.vocabulary, request),
IInputWidget)
# for collections, we want to make the widget a view of the field and the
# value_type. If the value_type is None we may fall over. We may
# not be able to do any better than that.
def CollectionDisplayWidget(field, request):
return component.getMultiAdapter((field, field.value_type, request),
IDisplayWidget)
def CollectionInputWidget(field, request):
return component.getMultiAdapter((field, field.value_type, request),
IInputWidget)
# for collections of choices, we want to make the widget a view of the field,
# the value type, and the vocabulary.
def ChoiceCollectionDisplayWidget(field, value_type, request):
return component.getMultiAdapter((field, value_type.vocabulary, request),
IDisplayWidget)
def ChoiceCollectionInputWidget(field, value_type, request):
return component.getMultiAdapter((field, value_type.vocabulary, request),
IInputWidget)
class TranslationHook:
"""A mixin class that provides the translation capabilities."""
def translate(self, msgid):
return translate(msgid, context=self.request, default=msgid)
class ItemsWidgetBase(TranslationHook, SimpleInputWidget):
"""Convenience base class for widgets displaying items/choices."""
extra = ""
def __init__(self, field, vocabulary, request):
"""Initialize the widget."""
# only allow this to happen for a bound field
assert field.context is not None
self.vocabulary = vocabulary
super().__init__(field, request)
self.empty_marker_name = self.name + "-empty-marker"
def setPrefix(self, prefix):
"""Set the prefixes for the field names of the form."""
super().setPrefix(prefix)
# names for other information from the form
self.empty_marker_name = self.name + "-empty-marker"
def __call__(self):
"""Render the widget to HTML."""
raise NotImplementedError(
"__call__() must be implemented by a subclass; use _getFormValue()"
)
def textForValue(self, term):
"""Extract a string from the `term`.
The `term` must be a vocabulary tokenized term.
This can be overridden to support more complex `term`
objects. The token is returned here since it's the only thing
known to be a string, or str()able.
"""
titled = ITitledTokenizedTerm(term, None)
if titled is None:
return term.token
return self.translate(titled.title)
def convertTokensToValues(self, tokens):
"""Convert term tokens to the terms themselves.
Tokens are used in the HTML form to represent terms. This method takes
the form tokens and converts them back to terms.
"""
values = []
for token in tokens:
try:
term = self.vocabulary.getTermByToken(token)
except LookupError:
raise InvalidValue("token %r not found in vocabulary" % token)
else:
values.append(term.value)
return values
def _emptyMarker(self):
"""Mark the form so that empty selections are also valid."""
return '<input name="%s" type="hidden" value="1" />' % (
self.empty_marker_name)
def hasInput(self):
"""Check whether we have any input."""
return (self.name in self.request.form or
self.empty_marker_name in self.request.form)
def _toFieldValue(self, input):
"""See `SimpleInputWidget`"""
raise NotImplementedError(
"_toFieldValue(input) must be implemented by a subclass\n"
"It may be inherited from the mix-in classes SingleDataHelper\n"
"or MultiDataHelper")
class SingleDataHelper:
"""Mix-in helper class for getting the term from the HTML form.
This is used when we expect a single input, i.e. the Choice field.
"""
def _toFieldValue(self, input):
if input:
try:
return self.convertTokensToValues([input])[0]
except (InvalidValue, TypeError) as e:
raise ConversionError(_("Invalid value"), e)
else:
return self.context.missing_value
def hidden(self):
# XXX: _getFormValue() should return a string value that can be
# used in a HTML form, but it doesn't. When
# http://www.zope.org/Collectors/Zope3-dev/584 gets fixed
# this hack should be reverted.
# -- Bjorn Tillenius, 2006-04-12
value = self._getFormValue()
if value == self._missing:
form_value = ''
else:
form_value = self.vocabulary.getTerm(value).token
return renderElement('input',
type='hidden',
name=self.name,
id=self.name,
value=form_value,
cssClass=self.cssClass,
extra=self.extra)
class MultiDataHelper:
"""Mix-in helper class for getting the term from the HTML form.
This is used when we expect a multiple inputs, i.e. Sequence fields with a
Choice field as value_type.
"""
def _toFieldValue(self, input):
"""See SimpleInputWidget"""
if input is None:
input = []
elif not isinstance(input, list):
input = [input]
try:
values = self.convertTokensToValues(input)
except InvalidValue as e:
raise ConversionError(_("Invalid value"), e)
# All AbstractCollection fields have a `_type` attribute specifying
# the type of collection. Use it to generate the correct type,
# otherwise return a list. TODO: this breaks encapsulation.
if hasattr(self.context, '_type'):
_type = self.context._type
if isinstance(_type, tuple):
_type = _type[0]
return _type(values)
else:
return values
def _getDefault(self):
# Return the default value for this widget;
# may be overridden by subclasses.
val = self.context.default
if val is None:
val = []
return val
# Display-Widgets for Items-related fields.
class ItemDisplayWidget(SingleDataHelper, ItemsWidgetBase):
"""Simple single-selection display that can be used in many cases."""
def __init__(self, *args, **kw):
ItemsWidgetBase.__init__(self, *args, **kw)
self.required = False
_messageNoValue = _("item-missing-single-value-for-display", "")
def __call__(self):
"""See IBrowserWidget."""
value = self._getFormValue()
if value is None or value == '':
return self.translate(self._messageNoValue)
else:
term = self.vocabulary.getTerm(value)
return self.textForValue(term)
class ItemsMultiDisplayWidget(MultiDataHelper, ItemsWidgetBase):
"""Displays a sequence of items."""
def __init__(self, *args, **kw):
ItemsWidgetBase.__init__(self, *args, **kw)
self.required = False
_messageNoValue = _("vocabulary-missing-multiple-value-for-display", "")
itemTag = 'li'
tag = 'ol'
def __call__(self):
"""See IBrowserWidget."""
value = self._getFormValue()
if value:
rendered_items = self.renderItems(value)
return renderElement(self.tag,
id=self.name,
cssClass=self.cssClass,
contents="\n".join(rendered_items),
extra=self.extra)
else:
return self.translate(self._messageNoValue)
def renderItems(self, value):
"""Render items of sequence."""
items = []
cssClass = self.cssClass or ''
if cssClass:
cssClass += "-item"
tag = self.itemTag
for item in value:
term = self.vocabulary.getTerm(item)
items.append(renderElement(
tag,
cssClass=cssClass,
contents=escape(self.textForValue(term))))
return items
class ListDisplayWidget(ItemsMultiDisplayWidget):
"""Display widget for ordered multi-selection fields.
This can be used for both Sequence, List, and Tuple fields.
"""
tag = 'ol'
class SetDisplayWidget(ItemsMultiDisplayWidget):
"""Display widget for unordered multi-selection fields.
This can be used for both Set field.
"""
tag = 'ul'
# Edit-Widgets for Items-related fields.
# BBB Set to False to never display an item for the missing value if the field
# is required, which was the behaviour of versions up to and including 3.5.0.
EXPLICIT_EMPTY_SELECTION = True
class ItemsEditWidgetBase(SingleDataHelper, ItemsWidgetBase):
"""Widget Base for rendering item-related fields.
These widgets work with Choice fields and Sequence fields that have Choice
as value_type.
"""
size = 5
tag = 'select'
_displayItemForMissingValue = True
# Whether an empty selection should always be made explicit, i.e. even
# if the field is required.
explicit_empty_selection = False
def __init__(self, field, vocabulary, request):
"""Initialize the widget."""
super().__init__(field, vocabulary, request)
def setPrefix(self, prefix):
"""Set the prefix of the input name.
Once we set the prefix of input field, we use the name of the input
field and the postfix '-query' for the associated query view.
"""
super().setPrefix(prefix)
def __call__(self):
"""See IBrowserWidget."""
value = self._getFormValue()
contents = []
contents.append(self._div('value', self.renderValue(value)))
contents.append(self._emptyMarker())
return self._div(self.cssClass, "\n".join(contents))
def _div(self, cssClass, contents, **kw):
"""Render a simple div tag."""
if contents:
return renderElement('div',
cssClass=cssClass,
contents="\n%s\n" % contents,
**kw)
return ""
def renderItemsWithValues(self, values):
"""Render the list of possible values, with those found in
`values` being marked as selected."""
cssClass = self.cssClass
# multiple items with the same value are not allowed from a
# vocabulary, so that need not be considered here
rendered_items = []
count = 0
# Handle case of missing value
missing = self._toFormValue(self.context.missing_value)
if self._displayItemForMissingValue and (
not self.context.required or
EXPLICIT_EMPTY_SELECTION and
self.explicit_empty_selection and
missing in values and
self.context.default is None):
if missing in values:
render = self.renderSelectedItem
else:
render = self.renderItem
missing_item = render(count,
self.translate(self._messageNoValue),
missing,
self.name,
cssClass)
rendered_items.append(missing_item)
count += 1
# Render normal values
for term in self.vocabulary:
item_text = self.textForValue(term)
if term.value in values:
render = self.renderSelectedItem
else:
render = self.renderItem
rendered_item = render(count,
item_text,
term.token,
self.name,
cssClass)
rendered_items.append(rendered_item)
count += 1
return rendered_items
def renderItem(self, index, text, value, name, cssClass):
"""Render an item for a particular `value`."""
return renderElement('option',
contents=escape(text),
value=value,
cssClass=cssClass)
def renderSelectedItem(self, index, text, value, name, cssClass):
"""Render an item for a particular `value` that is selected."""
return renderElement('option',
contents=escape(text),
value=value,
cssClass=cssClass,
selected='selected')
class SelectWidget(ItemsEditWidgetBase):
"""Provide a selection list for the item."""
_messageNoValue = _("vocabulary-missing-single-value-for-edit",
"(nothing selected)")
def renderValue(self, value):
rendered_items = self.renderItems(value)
contents = "\n%s\n" % "\n".join(rendered_items)
return renderElement('select',
name=self.name,
id=self.name,
contents=contents,
size=self.size,
extra=self.extra)
def renderItems(self, value):
return self.renderItemsWithValues([value])
class DropdownWidget(SelectWidget):
"""Variation of the SelectWidget that uses a drop-down list."""
size = 1
explicit_empty_selection = True
class RadioWidget(SelectWidget):
"""Radio widget for single item choices.
This widget can be used when the number of selections is going
to be small.
"""
orientation = "vertical"
_messageNoValue = _("vocabulary-missing-single-value-for-edit",
"(nothing selected)")
def renderItem(self, index, text, value, name, cssClass):
"""Render an item of the list."""
return self._renderItem(index, text, value, name, cssClass)
def renderSelectedItem(self, index, text, value, name, cssClass):
"""Render a selected item of the list."""
return self._renderItem(index, text, value, name, cssClass,
checked=True)
def _renderItem(self, index, text, value, name, cssClass, checked=False):
kw = {}
if checked:
kw['checked'] = 'checked'
id = '{}.{}'.format(name, index)
elem = renderElement('input',
value=value,
name=name,
id=id,
cssClass=cssClass,
type='radio',
**kw)
return renderElement('label',
contents='{} {}'.format(elem, text),
**{'for': id})
def renderValue(self, value):
rendered_items = self.renderItems(value)
if self.orientation == 'horizontal':
return " ".join(rendered_items)
else:
return "<br />".join(rendered_items)
class ItemsMultiEditWidgetBase(MultiDataHelper, ItemsEditWidgetBase):
"""Items widget supporting multiple selections."""
_messageNoValue = _("vocabulary-missing-multiple-value-for-edit",
"(nothing selected)")
_displayItemForMissingValue = False
def renderItems(self, value):
if value == self.context.missing_value:
values = []
else:
values = list(value)
return self.renderItemsWithValues(values)
def renderValue(self, value):
# All we really add here is the ':list' in the name argument
# and mutliple='multiple' to renderElement().
rendered_items = self.renderItems(value)
return renderElement(self.tag,
name=self.name + ':list',
id=self.name,
multiple='multiple',
size=self.size,
contents="\n".join(rendered_items),
extra=self.extra)
def hidden(self):
items = []
for item in self._getFormValue():
items.append(
renderElement('input',
type='hidden',
name=self.name + ':list',
id=self.name,
value=self.vocabulary.getTerm(item).token,
cssClass=self.cssClass,
extra=self.extra))
return '\n'.join(items)
class MultiSelectWidget(ItemsMultiEditWidgetBase):
"""Provide a selection list for the list to be selected."""
class MultiSelectSetWidget(MultiSelectWidget):
"""Provide a selection list for the set to be selected."""
def _toFieldValue(self, input):
value = super()._toFieldValue(input)
if isinstance(value, list):
value = set(value)
return value
class MultiSelectFrozenSetWidget(MultiSelectWidget):
"""Provide a selection list for the set to be selected."""
def _toFieldValue(self, input):
value = super()._toFieldValue(input)
if isinstance(value, list):
value = frozenset(value)
return value
class OrderedMultiSelectWidget(ItemsMultiEditWidgetBase):
"""A multi-selection widget with ordering support."""
template = ViewPageTemplateFile('orderedSelectionList.pt')
def choices(self):
"""Return a set of tuples (text, value) that are available."""
# Not all content objects must necessarily support the attributes
if hasattr(self.context.context, self.context.__name__):
available_values = self.context.get(self.context.context)
else:
available_values = []
return [{'text': self.textForValue(term), 'value': term.token}
for term in self.vocabulary
if term.value not in available_values]
def selected(self):
"""Return a list of tuples (text, value) that are selected."""
# Get form values
values = self._getFormValue()
# Not all content objects must necessarily support the attributes
if hasattr(self.context.context, self.context.__name__):
# merge in values from content
for value in self.context.get(self.context.context):
if value not in values:
values.append(value)
terms = [self.vocabulary.getTerm(value)
for value in values]
return [{'text': self.textForValue(term), 'value': term.token}
for term in terms]
def __call__(self):
return self.template()
class MultiCheckBoxWidget(ItemsMultiEditWidgetBase):
"""Provide a list of checkboxes that provide the choice for the list."""
orientation = "vertical"
_joinButtonToMessageTemplate = "%s %s"
def renderValue(self, value):
rendered_items = self.renderItems(value)
if self.orientation == 'horizontal':
return " ".join(rendered_items)
else:
return "<br />".join(rendered_items)
def renderItem(self, index, text, value, name, cssClass):
"""Render an item of the list."""
return self._renderItem(index, text, value, name, cssClass)
def renderSelectedItem(self, index, text, value, name, cssClass):
"""Render a selected item of the list."""
return self._renderItem(index, text, value, name, cssClass,
checked=True)
def _renderItem(self, index, text, value, name, cssClass, checked=False):
kw = {}
if checked:
kw['checked'] = 'checked'
id = '{}.{}'.format(name, index)
elem = renderElement('input',
type="checkbox",
cssClass=cssClass,
name=name,
id=id,
value=value,
**kw)
contents = self._joinButtonToMessageTemplate % (elem, escape(text))
return renderElement('label',
contents=contents,
**{'for': id}) | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/itemswidgets.py | itemswidgets.py |
"""Browser widgets for sequences
"""
__docformat__ = 'restructuredtext'
from zope.browserpage import ViewPageTemplateFile
from zope.i18n import translate
from zope.interface import implementer
from zope.schema.interfaces import ValidationError
from zope import component
from zope.formlib.i18n import _
from zope.formlib.interfaces import IDisplayWidget
from zope.formlib.interfaces import IInputWidget
from zope.formlib.interfaces import MissingInputError
from zope.formlib.interfaces import WidgetInputError
from zope.formlib.widget import BrowserWidget
from zope.formlib.widget import DisplayWidget
from zope.formlib.widget import InputWidget
from zope.formlib.widget import renderElement
@implementer(IInputWidget)
class SequenceWidget(BrowserWidget, InputWidget):
"""A widget baseclass for a sequence of fields.
subwidget - Optional CustomWidget used to generate widgets for the
items in the sequence
"""
template = ViewPageTemplateFile('sequencewidget.pt')
_type = tuple
def __init__(self, context, field, request, subwidget=None):
super().__init__(context, request)
self.subwidget = subwidget
# The subwidgets are cached in this dict if preserve_widgets is True.
self._widgets = {}
self.preserve_widgets = False
def __call__(self):
"""Render the widget"""
self._update()
return self.template()
def _update(self):
"""Set various attributes for the template"""
sequence = self._getRenderedValue()
num_items = len(sequence)
self.need_add = (not self.context.max_length
or num_items < self.context.max_length)
self.need_delete = num_items and num_items > self.context.min_length
self.marker = self._getPresenceMarker(num_items)
def widgets(self):
"""Return a list of widgets to display"""
sequence = self._getRenderedValue()
result = []
for i, value in enumerate(sequence):
widget = self._getWidget(i)
widget.setRenderedValue(value)
result.append(widget)
return result
def addButtonLabel(self):
button_label = _('Add %s')
button_label = translate(button_label, context=self.request,
default=button_label)
title = self.context.title or self.context.__name__
title = translate(title, context=self.request, default=title)
return button_label % title
def _getWidget(self, i):
"""Return a widget for the i-th number of the sequence.
Normally this method creates a new widget each time, but when
the ``preserve_widgets`` attribute is True, it starts caching
widgets. We need it so that the errors on the subwidgets
would appear only if ``getInputValue`` was called.
``getInputValue`` on the subwidgets gets called on each
request that has data.
"""
if i not in self._widgets:
field = self.context.value_type
if self.subwidget is not None:
widget = self.subwidget(field, self.request)
else:
widget = component.getMultiAdapter(
(field, self.request), IInputWidget)
widget.setPrefix('%s.%d.' % (self.name, i))
if not self.preserve_widgets:
return widget
self._widgets[i] = widget
return self._widgets[i]
def hidden(self):
"""Render the list as hidden fields."""
# length of sequence info
sequence = self._getRenderedValue()
num_items = len(sequence)
# generate hidden fields for each value
parts = [self._getPresenceMarker(num_items)]
for i in range(num_items):
value = sequence[i]
widget = self._getWidget(i)
widget.setRenderedValue(value)
parts.append(widget.hidden())
return "\n".join(parts)
def _getRenderedValue(self):
"""Returns a sequence from the request or _data"""
if self._renderedValueSet():
if self._data is self.context.missing_value:
sequence = []
else:
sequence = list(self._data)
elif self.hasInput():
sequence = self._generateSequence()
elif self.context.default is not None:
sequence = self.context.default
else:
sequence = []
# ensure minimum number of items in the form
while len(sequence) < self.context.min_length:
# Shouldn't this use self.field.value_type.missing_value,
# instead of None?
sequence.append(None)
return sequence
def _getPresenceMarker(self, count=0):
return ('<input type="hidden" name="%s.count" value="%d" />'
% (self.name, count))
def getInputValue(self):
"""Return converted and validated widget data.
If there is no user input and the field is required, then a
``MissingInputError`` will be raised.
If there is no user input and the field is not required, then
the field default value will be returned.
A ``WidgetInputError`` is raised in the case of one or more
errors encountered, inputting, converting, or validating the data.
"""
if self.hasInput():
self.preserve_widgets = True
sequence = self._type(self._generateSequence())
if sequence != self.context.missing_value:
# catch and set field errors to ``_error`` attribute
try:
self.context.validate(sequence)
except WidgetInputError as error:
self._error = error
raise self._error
except ValidationError as error:
self._error = WidgetInputError(
self.context.__name__, self.label, error)
raise self._error
elif self.context.required:
raise MissingInputError(self.context.__name__,
self.context.title)
return sequence
raise MissingInputError(self.context.__name__, self.context.title)
# TODO: applyChanges isn't reporting "change" correctly (we're
# re-generating the sequence with every edit, and need to be smarter)
def applyChanges(self, content):
field = self.context
value = self.getInputValue()
change = field.query(content, self) != value
if change:
field.set(content, value)
return change
def hasInput(self):
"""Is there input data for the field
Return ``True`` if there is data and ``False`` otherwise.
"""
return (self.name + ".count") in self.request.form
def _generateSequence(self):
"""Extract the values of the subwidgets from the request.
Returns a list of values.
This can only be called if self.hasInput() returns true.
"""
if self.context.value_type is None:
# Why would this ever happen?
return []
# the marker field tells how many individual items were
# included in the input; we check for exactly that many input
# widgets
try:
count = int(self.request.form[self.name + ".count"])
except ValueError:
# could not convert to int; the input was not generated
# from the widget as implemented here
raise WidgetInputError(self.context.__name__, self.context.title)
# pre-populate
sequence = [None] * count
# now look through the request for interesting values
# in reverse so that we can remove items as we go
removing = self.name + ".remove" in self.request.form
for i in reversed(list(range(count))):
widget = self._getWidget(i)
if widget.hasValidInput():
# catch and set sequence widget errors to ``_error`` attribute
try:
sequence[i] = widget.getInputValue()
except WidgetInputError as error:
self._error = error
raise self._error
remove_key = "%s.remove_%d" % (self.name, i)
if remove_key in self.request.form and removing:
del sequence[i]
# add an entry to the list if the add button has been pressed
if self.name + ".add" in self.request.form:
# Should this be using self.context.value_type.missing_value
# instead of None?
sequence.append(None)
return sequence
class TupleSequenceWidget(SequenceWidget):
_type = tuple
class ListSequenceWidget(SequenceWidget):
_type = list
# Basic display widget
class SequenceDisplayWidget(DisplayWidget):
_missingValueMessage = _("sequence-value-not-provided",
"(no value available)")
_emptySequenceMessage = _("sequence-value-is-empty",
"(no values)")
tag = "ol"
itemTag = "li"
cssClass = "sequenceWidget"
extra = ""
def __init__(self, context, field, request, subwidget=None):
super().__init__(context, request)
self.subwidget = subwidget
def __call__(self):
# get the data to display:
if self._renderedValueSet():
data = self._data
else:
data = self.context.get(self.context.context)
# deal with special cases:
if data == self.context.missing_value:
return translate(self._missingValueMessage, self.request)
data = list(data)
if not data:
return translate(self._emptySequenceMessage, self.request)
parts = []
for i, item in enumerate(data):
widget = self._getWidget(i)
widget.setRenderedValue(item)
s = widget()
if self.itemTag:
s = "<{}>{}</{}>".format(self.itemTag, s, self.itemTag)
parts.append(s)
contents = "\n".join(parts)
if self.tag:
contents = "\n%s\n" % contents
contents = renderElement(self.tag,
cssClass=self.cssClass,
extra=self.extra,
contents=contents)
return contents
def _getWidget(self, i):
field = self.context.value_type
if self.subwidget is not None:
widget = self.subwidget(field, self.request)
else:
widget = component.getMultiAdapter(
(field, self.request), IDisplayWidget)
widget.setPrefix('%s.%d.' % (self.name, i))
return widget | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/sequencewidget.py | sequencewidget.py |
__docformat__ = 'restructuredtext'
from zope.schema import getFieldsInOrder
from zope import component
from zope.formlib.interfaces import IInputWidget
from zope.formlib.interfaces import InputErrors
from zope.formlib.interfaces import IWidget
from zope.formlib.interfaces import IWidgetFactory
from zope.formlib.interfaces import WidgetsError
# A marker that indicates 'no value' for any of the utility functions that
# accept a 'value' argument.
no_value = object()
def _fieldlist(names, schema):
if not names:
fields = getFieldsInOrder(schema)
else:
fields = [(name, schema[name]) for name in names]
return fields
def _createWidget(context, field, viewType, request):
"""Creates a widget given a `context`, `field`, and `viewType`."""
field = field.bind(context)
return component.getMultiAdapter((field, request), viewType)
def _widgetHasStickyValue(widget):
"""Returns ``True`` if the widget has a sticky value.
A sticky value is input from the user that should not be overridden
by an object's current field value. E.g. a user may enter an invalid
postal code, submit the form, and receive a validation error - the postal
code should be treated as 'sticky' until the user successfully updates
the object.
"""
return IInputWidget.providedBy(widget) and widget.hasInput()
def setUpWidget(view, name, field, viewType, value=no_value, prefix=None,
ignoreStickyValues=False, context=None):
"""Sets up a single view widget.
The widget will be an attribute of the `view`. If there is already
an attribute of the given name, it must be a widget and it will be
initialized with the given `value` if not ``no_value``.
If there isn't already a `view` attribute of the given name, then a
widget will be created and assigned to the attribute.
"""
if context is None:
context = view.context
widgetName = name + '_widget'
# check if widget already exists
widget = getattr(view, widgetName, None)
if widget is None:
# does not exist - create it
widget = _createWidget(context, field, viewType, view.request)
setattr(view, widgetName, widget)
elif IWidgetFactory.providedBy(widget):
# exists, but is actually a factory - use it to create the widget
widget = widget(field.bind(context), view.request)
setattr(view, widgetName, widget)
# widget must implement IWidget
if not IWidget.providedBy(widget):
raise TypeError(
"Unable to configure a widget for %s - attribute %s does not "
"implement IWidget" % (name, widgetName))
if prefix:
widget.setPrefix(prefix)
if value is not no_value and (
ignoreStickyValues or not _widgetHasStickyValue(widget)):
widget.setRenderedValue(value)
def setUpWidgets(view, schema, viewType, prefix=None, ignoreStickyValues=False,
initial={}, names=None, context=None):
"""Sets up widgets for the fields defined by a `schema`.
Appropriate for collecting input without a current object implementing
the schema (such as an add form).
`view` is the view that will be configured with widgets.
`viewType` is the type of widgets to create (e.g. IInputWidget or
IDisplayWidget).
`schema` is an interface containing the fields that widgets will be
created for.
`prefix` is a string that is prepended to the widget names in the generated
HTML. This can be used to differentiate widgets for different schemas.
`ignoreStickyValues` is a flag that, when ``True``, will cause widget
sticky values to be replaced with the context field value or a value
specified in initial.
`initial` is a mapping of field names to initial values.
`names` is an optional iterable that provides an ordered list of field
names to use. If names is ``None``, the list of fields will be defined by
the schema.
`context` provides an alternative context for acquisition.
"""
for (name, field) in _fieldlist(names, schema):
setUpWidget(view, name, field, viewType,
value=initial.get(name, no_value),
prefix=prefix,
ignoreStickyValues=ignoreStickyValues,
context=context)
def applyWidgetsChanges(view, schema, target=None, names=None):
"""Updates an object with values from a view's widgets.
`view` contained the widgets that perform the update. By default, the
widgets will update the view's context.
`target` can be specified as an alternative object to update.
`schema` contrains the values provided by the widgets.
`names` can be specified to update a subset of the schema constrained
values.
"""
errors = []
changed = False
if target is None:
target = view.context
for name, field in _fieldlist(names, schema):
widget = getattr(view, name + '_widget')
if IInputWidget.providedBy(widget) and widget.hasInput():
try:
changed = widget.applyChanges(target) or changed
except InputErrors as v:
errors.append(v)
if errors:
raise WidgetsError(errors)
return changed | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/utility.py | utility.py |
"""Source widgets support
"""
import base64
import xml.sax.saxutils
import zope.browser.interfaces
import zope.schema.interfaces
from zope.component import adapter
from zope.component import getMultiAdapter
from zope.interface import implementer
from zope.schema.interfaces import IIterableSource
from zope.schema.interfaces import ISourceQueriables
from zope.schema.interfaces import IVocabularyTokenized
from zope.schema.interfaces import ValidationError
import zope.formlib.interfaces
import zope.formlib.itemswidgets
import zope.formlib.widget
from zope.formlib.i18n import _
from zope.formlib.interfaces import IDisplayWidget
from zope.formlib.interfaces import IInputWidget
from zope.formlib.interfaces import ISourceQueryView
from zope.formlib.interfaces import IWidgetInputErrorView
from zope.formlib.interfaces import MissingInputError
from zope.formlib.interfaces import WidgetInputError
from zope.formlib.widget import DisplayWidget
from zope.formlib.widget import InputWidget
from zope.formlib.widgets import MultiCheckBoxWidget
from zope.formlib.widgets import MultiSelectFrozenSetWidget
from zope.formlib.widgets import MultiSelectSetWidget
from zope.formlib.widgets import MultiSelectWidget
from zope.formlib.widgets import OrderedMultiSelectWidget
from zope.formlib.widgets import RadioWidget
from zope.formlib.widgets import SelectWidget
def safeBase64Encode(obj):
return base64.b64encode(
obj.encode()).strip().replace(b'=', b'_').decode()
@implementer(IDisplayWidget)
class SourceDisplayWidget(DisplayWidget):
def __init__(self, field, source, request):
super().__init__(field, request)
self.source = source
required = False
def hidden(self):
return ''
def error(self):
return ''
def __call__(self):
"""Render the current value
"""
if self._renderedValueSet():
value = self._data
else:
value = self.context.default
if value == self.context.missing_value:
value = self._translate(_("SourceDisplayWidget-missing",
default="Nothing"))
else:
terms = getMultiAdapter((self.source, self.request),
zope.browser.interfaces.ITerms)
try:
term = terms.getTerm(value)
except LookupError:
value = self._translate(_("SourceDisplayWidget-invalid",
default="Invalid value"))
else:
value = self.renderTermForDisplay(term)
return value
def renderTermForDisplay(self, term):
# Provide a rendering of `term` for display; this is not for
# use when generating a select list.
return xml.sax.saxutils.escape(self._translate(term.title))
class SourceSequenceDisplayWidget(SourceDisplayWidget):
separator = '<br />\n'
def __call__(self):
if self._renderedValueSet():
seq = self._data
else:
seq = self.context.default
terms = getMultiAdapter((self.source, self.request),
zope.browser.interfaces.ITerms)
result = []
for value in seq:
try:
term = terms.getTerm(value)
except LookupError:
value = self._translate(_("SourceDisplayWidget-invalid",
default="Invalid value"))
else:
value = self.renderTermForDisplay(term)
result.append(value)
return self.separator.join(result)
@implementer(IInputWidget)
class SourceInputWidget(InputWidget):
_error = None
def __init__(self, field, source, request):
super().__init__(field, request)
self.source = source
self.terms = getMultiAdapter((source, self.request),
zope.browser.interfaces.ITerms)
def queryviews(self):
queriables = ISourceQueriables(self.source, None)
if queriables is None:
# treat the source itself as a queriable
queriables = ((self.name + '.query', self.source), )
else:
queriables = [
(self.name + '.' + safeBase64Encode(i), s)
for (i, s) in queriables.getQueriables()]
return [
(name, getMultiAdapter(
(source, self.request),
ISourceQueryView,
)
) for (name, source) in queriables]
queryviews = property(queryviews)
def _value(self):
if self._renderedValueSet():
value = self._data
else:
for name, queryview in self.queryviews:
if name + '.apply' in self.request:
token = self.request.form.get(name + '.selection')
if token is not None:
break
else:
token = self.request.form.get(self.name)
if token is not None:
try:
value = self.terms.getValue(str(token))
except LookupError:
value = self.context.missing_value
else:
value = self.context.missing_value
return value
def hidden(self):
value = self._value()
if value == self.context.missing_value:
return '' # Nothing to hide ;)
try:
term = self.terms.getTerm(value)
except LookupError:
# A value was set, but it's not valid. Treat
# it as if it was missing and return nothing.
return ''
return ('<input type="hidden" name="%s" value=%s />'
% (self.name, xml.sax.saxutils.quoteattr(term.token))
)
def error(self):
if self._error:
# TODO This code path is untested.
return getMultiAdapter((self._error, self.request),
IWidgetInputErrorView).snippet()
return ""
def __call__(self):
result = ['<div class="value">']
value = self._value()
field = self.context
term = None
if value == field.missing_value:
result.append(' <div class="row">')
result.append(' <div class="label">')
result.append(' ' +
self._translate(_("SourceDisplayWidget-label",
default="Selected"))
)
result.append(' </div>')
result.append(' <div class="field">')
result.append(' ' +
self._translate(_("SourceDisplayWidget-missing",
default="Nothing"))
)
result.append(' </div>')
result.append(' </div>')
else:
try:
term = self.terms.getTerm(value)
except LookupError:
result.append(' ' +
self._translate(_("SourceDisplayWidget-missing",
default="Nothing Valid"))
)
else:
result.append(' <div class="row">')
result.append(' <div class="label">')
result.append(' ' +
self._translate(_("SourceDisplayWidget-label",
default="Selected"))
)
result.append(' </div>')
result.append(' <div class="field">')
result.append(' ' + self.renderTermForDisplay(term))
result.append(' </div>')
result.append(' </div>')
result.append(
' <input type="hidden" name="%s" value=%s />'
% (self.name, xml.sax.saxutils.quoteattr(term.token)))
result.append(' <input type="hidden" name="%s.displayed" value="y" />'
% self.name)
result.append(' <div class="queries">')
for name, queryview in self.queryviews:
result.append(' <div class="query">')
result.append(' <div class="queryinput">')
result.append(queryview.render(name))
result.append(' </div> <!-- queryinput -->')
qresults = queryview.results(name)
if qresults:
result.append(' <div class="queryresults">\n%s' %
self._renderResults(qresults, name))
result.append(' </div> <!-- queryresults -->')
result.append(' </div> <!-- query -->')
result.append(' </div> <!-- queries -->')
result.append('</div> <!-- value -->')
return '\n'.join(result)
def _renderResults(self, results, name):
terms = []
for value in results:
term = self.terms.getTerm(value)
terms.append((self._translate(term.title), term.token))
terms.sort()
apply = self._translate(_("SourceInputWidget-apply", default="Apply"))
return (
'<select name="%s.selection">\n'
'%s\n'
'</select>\n'
'<input type="submit" name="%s.apply" value="%s" />'
% (name,
'\n'.join(
[('<option value="%s">%s</option>'
% (token, title))
for (title, token) in terms]),
name,
apply)
)
def renderTermForDisplay(self, term):
# Provide a rendering of `term` for display; this is not for
# use when generating a select list.
return xml.sax.saxutils.escape(self._translate(term.title))
required = property(lambda self: self.context.required)
def getInputValue(self):
for name, queryview in self.queryviews:
if name + '.apply' in self.request:
token = self.request.form.get(name + '.selection')
if token is not None:
break
else:
token = self.request.get(self.name)
field = self.context
if token is None:
if field.required:
# TODO This code path is untested.
raise MissingInputError(
field.__name__, self.label,
)
return field.missing_value
try:
value = self.terms.getValue(str(token))
except LookupError:
# TODO This code path is untested.
err = zope.schema.interfaces.ValidationError(
"Invalid value id", token)
raise WidgetInputError(field.__name__, self.label, err)
# Remaining code copied from SimpleInputWidget
# value must be valid per the field constraints
try:
field.validate(value)
except ValidationError as err:
# TODO This code path is untested.
self._error = WidgetInputError(field.__name__, self.label, err)
raise self._error
return value
def hasInput(self):
if (self.name in self.request
or self.name + '.displayed' in self.request):
return True
for name, queryview in self.queryviews:
if name + '.apply' in self.request:
token = self.request.form.get(name + '.selection')
if token is not None:
return True
return False
class SourceListInputWidget(SourceInputWidget):
def _input_value(self):
tokens = self.request.form.get(self.name)
for name, queryview in self.queryviews:
if name + '.apply' in self.request:
newtokens = self.request.form.get(name + '.selection')
if newtokens:
if tokens:
tokens = tokens + newtokens
else:
tokens = newtokens
if tokens:
remove = self.request.form.get(self.name + '.checked')
if remove and (self.name + '.remove' in self.request):
tokens = [token
for token in tokens
if token not in remove
]
value = []
for token in tokens:
try:
v = self.terms.getValue(str(token))
except LookupError:
pass # skip invalid tokens (shrug)
else:
value.append(v)
else:
if self.name + '.displayed' in self.request:
value = []
else:
value = self.context.missing_value
if value:
r = []
seen = {}
for s in value:
if s not in seen:
r.append(s)
seen[s] = 1
value = r
return value
def _value(self):
if self._renderedValueSet():
value = self._data
else:
value = self._input_value()
return value
def hidden(self):
value = self._value()
if value == self.context.missing_value:
return '' # Nothing to hide ;)
result = []
for v in value:
try:
term = self.terms.getTerm(value)
except LookupError:
# A value was set, but it's not valid. Treat
# it as if it was missing and skip
continue
else:
result.append(
'<input type="hidden" name="%s:list" value=%s />'
% (self.name, xml.sax.saxutils.quoteattr(term.token))
)
def __call__(self):
result = ['<div class="value">']
value = self._value()
if value:
for v in value:
try:
term = self.terms.getTerm(v)
except LookupError:
continue # skip
else:
result.append(
' <input type="checkbox" name="%s.checked:list"'
' value=%s />'
% (self.name, xml.sax.saxutils.quoteattr(term.token))
)
result.append(' ' + self.renderTermForDisplay(term))
result.append(
' <input type="hidden" name="%s:list" value=%s />'
% (self.name, xml.sax.saxutils.quoteattr(term.token)))
result.append(' <br />')
result.append(
' <input type="submit" name="%s.remove" value="%s" />'
% (self.name,
self._translate(_("MultipleSourceInputWidget-remove",
default="Remove")))
)
result.append(' <br />')
result.append(' <input type="hidden" name="%s.displayed" value="y" />'
% self.name)
result.append(' <div class="queries">')
for name, queryview in self.queryviews:
result.append(' <div class="query">')
result.append(' <div class="queryinput">')
result.append(queryview.render(name))
result.append(' </div> <!-- queryinput -->')
qresults = queryview.results(name)
if qresults:
result.append(' <div class="queryresults">\n%s' %
self._renderResults(qresults, name))
result.append(' </div> <!-- queryresults -->')
result.append(' </div> <!-- query -->')
result.append(' </div> <!-- queries -->')
result.append('</div> <!-- value -->')
return '\n'.join(result)
def _renderResults(self, results, name):
terms = []
apply = self._translate(_("SourceListInputWidget-apply",
default="Apply"))
for value in results:
term = self.terms.getTerm(value)
terms.append((self._translate(term.title), term.token))
terms.sort()
return (
'<select name="%s.selection:list" multiple>\n'
'%s\n'
'</select>\n'
'<input type="submit" name="%s.apply" value="%s" />'
% (name,
'\n'.join([(f'<option value="{token}">{title}</option>')
for (title, token) in terms]),
name,
apply)
)
def getInputValue(self):
value = self._input_value()
# Remaining code copied from SimpleInputWidget
# value must be valid per the field constraints
field = self.context
try:
field.validate(value)
except ValidationError as err:
# TODO This code path is untested.
self._error = WidgetInputError(field.__name__, self.label, err)
raise self._error
return value
def hasInput(self):
return self.name + '.displayed' in self.request.form
# Input widgets for IIterableSource:
# These widgets reuse the old-style vocabulary widgets via the class
# IterableSourceVocabulary that adapts a source (and its ITerms object)
# into a vocabulary. When/if vocabularies go away, these classes
# should be updated into full implementations.
@implementer(IVocabularyTokenized)
@adapter(IIterableSource)
class IterableSourceVocabulary:
"""Adapts an iterable source into a legacy vocabulary.
This can be used to wrap sources to make them usable with widgets that
expect vocabularies. Note that there must be an ITerms implementation
registered to obtain the terms.
"""
def __init__(self, source, request):
self.source = source
self.terms = getMultiAdapter((source, request),
zope.browser.interfaces.ITerms)
def getTerm(self, value):
return self.terms.getTerm(value)
def getTermByToken(self, token):
value = self.terms.getValue(token)
return self.getTerm(value)
def __iter__(self):
return map(
lambda value: self.getTerm(value), self.source.__iter__())
def __len__(self):
return self.source.__len__()
def __contains__(self, value):
return self.source.__contains__(value)
class SourceSelectWidget(SelectWidget):
"""Provide a selection list for the item."""
def __init__(self, field, source, request):
super().__init__(
field, IterableSourceVocabulary(source, request), request)
# BBB
if not zope.formlib.itemswidgets.EXPLICIT_EMPTY_SELECTION:
# Even if the field is required, no input is needed, so don't
# worry the user about it:
self.required = False
class SourceDropdownWidget(SourceSelectWidget):
"""Variation of the SourceSelectWidget that uses a drop-down list."""
size = 1
explicit_empty_selection = True
class SourceRadioWidget(RadioWidget):
"""Radio widget for single item choices."""
def __init__(self, field, source, request):
super().__init__(
field, IterableSourceVocabulary(source, request), request)
class SourceMultiSelectWidget(MultiSelectWidget):
"""A multi-selection widget with ordering support."""
def __init__(self, field, source, request):
super().__init__(
field, IterableSourceVocabulary(source, request), request)
class SourceOrderedMultiSelectWidget(OrderedMultiSelectWidget):
"""A multi-selection widget with ordering support."""
def __init__(self, field, source, request):
super().__init__(
field, IterableSourceVocabulary(source, request), request)
class SourceMultiSelectSetWidget(MultiSelectSetWidget):
"""Provide a selection list for the set to be selected."""
def __init__(self, field, source, request):
super().__init__(
field, IterableSourceVocabulary(source, request), request)
class SourceMultiSelectFrozenSetWidget(MultiSelectFrozenSetWidget):
"""Provide a selection list for the frozenset to be selected."""
def __init__(self, field, source, request):
super().__init__(
field, IterableSourceVocabulary(source, request), request)
class SourceMultiCheckBoxWidget(MultiCheckBoxWidget):
"""Provide a list of checkboxes that provide the choice for the list."""
def __init__(self, field, source, request):
super().__init__(
field, IterableSourceVocabulary(source, request), request) | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/source.py | source.py |
"""Browser widgets for items
"""
__docformat__ = 'restructuredtext'
from zope.schema.vocabulary import SimpleVocabulary
from zope.formlib.i18n import _
from zope.formlib.itemswidgets import DropdownWidget
from zope.formlib.itemswidgets import RadioWidget
from zope.formlib.itemswidgets import SelectWidget
from zope.formlib.widget import DisplayWidget
from zope.formlib.widget import SimpleInputWidget
from zope.formlib.widget import renderElement
class CheckBoxWidget(SimpleInputWidget):
"""A checkbox widget used to display Bool fields.
For more detailed documentation, including sample code, see
``tests/test_checkboxwidget.py``.
"""
type = 'checkbox'
default = 0
extra = ''
def __init__(self, context, request):
super().__init__(context, request)
self.required = False
def __call__(self):
"""Render the widget to HTML."""
value = self._getFormValue()
if value == 'on':
kw = {'checked': 'checked'}
else:
kw = {}
return "{} {}".format(
renderElement(self.tag,
type='hidden',
name=self.name + ".used",
id=self.name + ".used",
value=""
),
renderElement(self.tag,
type=self.type,
name=self.name,
id=self.name,
cssClass=self.cssClass,
extra=self.extra,
value="on",
**kw),
)
def _toFieldValue(self, input):
"""Convert from HTML presentation to Python bool."""
return input == 'on'
def _toFormValue(self, value):
"""Convert from Python bool to HTML representation."""
return value and 'on' or ''
def hasInput(self):
"""Check whether the field is represented in the form."""
return self.name + ".used" in self.request.form or \
super().hasInput()
def _getFormInput(self):
"""Returns the form input used by `_toFieldValue`.
Return values:
``'on'`` checkbox is checked
``''`` checkbox is not checked
``None`` form input was not provided
"""
if self.request.get(self.name) == 'on':
return 'on'
elif self.name + '.used' in self.request:
return ''
else:
return None
def BooleanRadioWidget(field, request, true=_('on'), false=_('off')):
vocabulary = SimpleVocabulary.fromItems(((true, True), (false, False)))
widget = RadioWidget(field, vocabulary, request)
widget.required = False
return widget
def BooleanSelectWidget(field, request, true=_('on'), false=_('off')):
vocabulary = SimpleVocabulary.fromItems(((true, True), (false, False)))
widget = SelectWidget(field, vocabulary, request)
widget.size = 2
widget.required = False
return widget
def BooleanDropdownWidget(field, request, true=_('on'), false=_('off')):
vocabulary = SimpleVocabulary.fromItems(((true, True), (false, False)))
widget = DropdownWidget(field, vocabulary, request)
widget.required = False
return widget
class BooleanDisplayWidget(DisplayWidget):
_msg_true = _("True")
_msg_false = _("False")
def __call__(self):
if self._renderedValueSet():
value = self._data
else:
value = self.context.default
if value:
return self._msg_true
else:
return self._msg_false | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/boolwidgets.py | boolwidgets.py |
"""Browser widgets
"""
# Widgets for boolean fields
from zope.formlib.boolwidgets import BooleanDisplayWidget
from zope.formlib.boolwidgets import BooleanDropdownWidget
from zope.formlib.boolwidgets import BooleanRadioWidget
from zope.formlib.boolwidgets import BooleanSelectWidget
from zope.formlib.boolwidgets import CheckBoxWidget
# Widgets that let you choose several items from a list
# These widgets are multi-views on (field, vocabulary)
# Widgets that let you choose a single item from a list
# These widgets are multi-views on (field, vocabulary)
# Widgets for fields with vocabularies.
# Note that these are only dispatchers for the widgets below.
# Choice and Sequence Display Widgets
from zope.formlib.itemswidgets import ChoiceCollectionDisplayWidget
from zope.formlib.itemswidgets import ChoiceCollectionInputWidget
from zope.formlib.itemswidgets import ChoiceDisplayWidget
from zope.formlib.itemswidgets import ChoiceInputWidget
from zope.formlib.itemswidgets import CollectionDisplayWidget
from zope.formlib.itemswidgets import CollectionInputWidget
from zope.formlib.itemswidgets import DropdownWidget
from zope.formlib.itemswidgets import ItemDisplayWidget
from zope.formlib.itemswidgets import ItemsMultiDisplayWidget
from zope.formlib.itemswidgets import ListDisplayWidget
from zope.formlib.itemswidgets import MultiCheckBoxWidget
from zope.formlib.itemswidgets import MultiSelectFrozenSetWidget
from zope.formlib.itemswidgets import MultiSelectSetWidget
from zope.formlib.itemswidgets import MultiSelectWidget
from zope.formlib.itemswidgets import OrderedMultiSelectWidget
from zope.formlib.itemswidgets import RadioWidget
from zope.formlib.itemswidgets import SelectWidget
from zope.formlib.itemswidgets import SetDisplayWidget
from zope.formlib.objectwidget import ObjectWidget
# Widgets that let you enter several items in a sequence
# These widgets are multi-views on (sequence type, value type)
from zope.formlib.sequencewidget import ListSequenceWidget
from zope.formlib.sequencewidget import SequenceDisplayWidget
from zope.formlib.sequencewidget import SequenceWidget
from zope.formlib.sequencewidget import TupleSequenceWidget
from zope.formlib.textwidgets import ASCIIAreaWidget
from zope.formlib.textwidgets import ASCIIDisplayWidget
from zope.formlib.textwidgets import ASCIIWidget
from zope.formlib.textwidgets import BytesAreaWidget
from zope.formlib.textwidgets import BytesDisplayWidget
from zope.formlib.textwidgets import BytesWidget
from zope.formlib.textwidgets import DateDisplayWidget
from zope.formlib.textwidgets import DateI18nWidget
from zope.formlib.textwidgets import DatetimeDisplayWidget
from zope.formlib.textwidgets import DatetimeI18nWidget
from zope.formlib.textwidgets import DatetimeWidget
from zope.formlib.textwidgets import DateWidget
from zope.formlib.textwidgets import DecimalWidget
from zope.formlib.textwidgets import FileWidget
from zope.formlib.textwidgets import FloatWidget
from zope.formlib.textwidgets import IntWidget
from zope.formlib.textwidgets import PasswordWidget
from zope.formlib.textwidgets import TextAreaWidget
from zope.formlib.textwidgets import TextWidget
from zope.formlib.textwidgets import URIDisplayWidget
from zope.formlib.widget import BrowserWidget
from zope.formlib.widget import DisplayWidget
from zope.formlib.widget import UnicodeDisplayWidget | zope.formlib | /zope.formlib-6.0.tar.gz/zope.formlib-6.0/src/zope/formlib/widgets.py | widgets.py |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.