code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
import datetime import time from random import randint import persistent from BTrees.OOBTree import OOBTree from BTrees.OIBTree import OIBTree import zope.event import zope.interface import zope.datetime from zope.annotation.interfaces import IAnnotations from zope.traversing.api import getPath from zope.app.versioncontrol import nonversioned, utility, event from zope.app.versioncontrol.history import VersionHistory from zope.app.versioncontrol.interfaces import VersionControlError from zope.app.versioncontrol.interfaces import IVersionable, IVersioned from zope.app.versioncontrol.interfaces import ICheckedIn, ICheckedOut from zope.app.versioncontrol.interfaces import IRepository from zope.app.versioncontrol.interfaces import CHECKED_IN, CHECKED_OUT from zope.app.versioncontrol.interfaces import ACTION_CHECKIN, ACTION_CHECKOUT from zope.app.versioncontrol.interfaces import ACTION_UNCHECKOUT, ACTION_UPDATE VERSION_INFO_KEY = "%s.%s" % (utility.__name__, utility.VersionInfo.__name__) class Repository(persistent.Persistent): """The repository implementation manages the actual data of versions and version histories. It does not handle user interface issues.""" zope.interface.implements(IRepository) def __init__(self): # These keep track of symbolic label and branch names that # have been used to ensure that they don't collide. self._branches = OIBTree() self._branches['mainline'] = 1 self._labels = OIBTree() self._histories = OOBTree() self._created = datetime.datetime.utcnow() def createVersionHistory(self): """Internal: create a new version history for a resource.""" # When one creates the first version in a version history, neither # the version or version history yet have a _p_jar, which causes # copy operations to fail. To work around that, we share our _p_jar. history_id = None while history_id is None or self._histories.has_key(history_id): history_id = str(randint(1, 9999999999)) history = VersionHistory(history_id) history.__parent__ = self self._histories[history_id] = history return history def getVersionHistory(self, history_id): """Internal: return a version history given a version history id.""" return self._histories[history_id] def replaceState(self, obj, new_state): """Internal: replace the state of a persistent object. """ non_versioned = nonversioned.getNonVersionedData(obj) # TODO There ought to be some way to do this more cleanly. # This fills the __dict__ of the old object with new state. # The other way to achieve the desired effect is to replace # the object in its container, but this method preserves the # identity of the object. if obj.__class__ is not new_state.__class__: raise VersionControlError( "The class of the versioned object has changed. %s != %s" % (repr(obj.__class__, new_state.__class__))) obj._p_changed = 1 obj.__dict__.clear() obj.__dict__.update(new_state.__dict__) if non_versioned: # Restore the non-versioned data into the new state. nonversioned.restoreNonVersionedData(obj, non_versioned) return obj ##################################################################### # This is the implementation of the public version control interface. ##################################################################### def isResourceUpToDate(self, object, require_branch=False): info = self.getVersionInfo(object) history = self.getVersionHistory(info.history_id) branch = 'mainline' if info.sticky: if info.sticky[0] == 'B': branch = info.sticky[1] elif require_branch: # The object is updated to a particular version # rather than a branch. The caller # requires a branch. return False return history.isLatestVersion(info.version_id, branch) def isResourceChanged(self, object): # Return true if the state of a resource has changed in a transaction # *after* the version bookkeeping was saved. Note that this method is # not appropriate for detecting changes within a transaction! info = self.getVersionInfo(object) info.version_id # deghostify info itime = getattr(info, '_p_serial', None) if itime is None: return False mtime = utility._findModificationTime(object) if mtime is None: return False return mtime > itime def getVersionInfo(self, object): # Return the VersionInfo associated with the given object. # # The VersionInfo object contains version control bookkeeping # information. If the object is not under version control, a # VersionControlError will be raised. # if IVersioned.providedBy(object): annotations = IAnnotations(object) return annotations[VERSION_INFO_KEY] raise VersionControlError( "Object is not under version control.") def queryVersionInfo(self, object, default=None): if IVersioned.providedBy(object): annotations = IAnnotations(object) return annotations[VERSION_INFO_KEY] return default def applyVersionControl(self, object, message=None): if IVersioned.providedBy(object): raise VersionControlError( 'The resource is already under version control.' ) if not IVersionable.providedBy(object): raise VersionControlError( 'This resource cannot be put under version control.' ) # Need to check the parent to see if the container of the object # being put under version control is itself a version-controlled # object. If so, we need to use the branch id of the container. branch = 'mainline' parent = getattr(object, '__parent__', None) if parent is None: p_info = None else: p_info = self.queryVersionInfo(parent) if p_info is not None: sticky = p_info.sticky if sticky and sticky[0] == 'B': branch = sticky[1] # Create a new version history and initial version object. history = self.createVersionHistory() version = history.createVersion(object, branch) history_id = history.__name__ version_id = version.__name__ # Add bookkeeping information to the version controlled object. declare_checked_in(object) info = utility.VersionInfo(history_id, version_id, CHECKED_IN) annotations = IAnnotations(object) annotations[VERSION_INFO_KEY] = info if branch != 'mainline': info.sticky = ('B', branch) # Save an audit record of the action being performed. history.addLogEntry(version_id, ACTION_CHECKIN, getPath(object), message is None and 'Initial checkin.' or message ) zope.event.notify(event.VersionControlApplied(object, info, message)) def checkoutResource(self, object): info = self.getVersionInfo(object) if info.status != CHECKED_IN: raise VersionControlError( 'The selected resource is already checked out.' ) if info.sticky and info.sticky[0] != 'B': raise VersionControlError( 'The selected resource has been updated to a particular ' 'version, label or date. The resource must be updated to ' 'the mainline or a branch before it may be checked out.' ) if not self.isResourceUpToDate(object): raise VersionControlError( 'The selected resource is not up to date!' ) history = self.getVersionHistory(info.history_id) ob_path = getPath(object) # Save an audit record of the action being performed. history.addLogEntry(info.version_id, ACTION_CHECKOUT, ob_path ) # Update bookkeeping information. info.status = CHECKED_OUT info.touch() declare_checked_out(object) zope.event.notify(event.VersionCheckedOut(object, info)) def checkinResource(self, object, message=''): info = self.getVersionInfo(object) if info.status != CHECKED_OUT: raise VersionControlError( 'The selected resource is not checked out.' ) if info.sticky and info.sticky[0] != 'B': raise VersionControlError( 'The selected resource has been updated to a particular ' 'version, label or date. The resource must be updated to ' 'the mainline or a branch before it may be checked in.' ) if not self.isResourceUpToDate(object): raise VersionControlError( 'The selected resource is not up to date!' ) history = self.getVersionHistory(info.history_id) ob_path = getPath(object) branch = 'mainline' if info.sticky is not None and info.sticky[0] == 'B': branch = info.sticky[1] version = history.createVersion(object, branch) # Save an audit record of the action being performed. history.addLogEntry(version.__name__, ACTION_CHECKIN, ob_path, message ) # Update bookkeeping information. info.version_id = version.__name__ info.status = CHECKED_IN info.touch() declare_checked_in(object) zope.event.notify(event.VersionCheckedIn(object, info, message)) def uncheckoutResource(self, object): info = self.getVersionInfo(object) if info.status != CHECKED_OUT: raise VersionControlError( 'The selected resource is not checked out.' ) history = self.getVersionHistory(info.history_id) ob_path = getPath(object) version = history.getVersionById(info.version_id) # Save an audit record of the action being performed. history.addLogEntry(info.version_id, ACTION_UNCHECKOUT, ob_path ) # Replace the state of the object with a reverted state. self.replaceState(object, version.copyState()) # Update bookkeeping information. info = utility.VersionInfo(info.history_id, info.version_id, CHECKED_IN) annotations = IAnnotations(object) annotations[VERSION_INFO_KEY] = info declare_checked_in(object) zope.event.notify(event.VersionReverted(object, info)) def updateResource(self, object, selector=None): info = self.getVersionInfo(object) if info.status != CHECKED_IN: raise VersionControlError( 'The selected resource must be checked in to be updated.' ) history = self.getVersionHistory(info.history_id) oldversion = info.version_id version = None sticky = info.sticky if not selector: # If selector is null, update to the latest version taking any # sticky attrs into account (branch, date). Note that the sticky # tag could also be a date or version id. We don't bother checking # for those, since in both cases we do nothing (because we'll # always be up to date until the sticky tag changes). if sticky and sticky[0] == 'L': # A label sticky tag, so update to that label (since it is # possible, but unlikely, that the label has been moved). version = history.getVersionByLabel(sticky[1]) elif sticky and sticky[0] == 'B': # A branch sticky tag. Update to latest version on branch. version = history.getLatestVersion(selector) else: # Update to mainline, forgetting any date or version id # sticky tag that was previously associated with the object. version = history.getLatestVersion('mainline') sticky = None else: # If the selector is non-null, we find the version specified # and update the sticky tag. Later we'll check the version we # found and decide whether we really need to update the object. if history.hasVersionId(selector): version = history.getVersionById(selector) sticky = ('V', selector) elif self._labels.has_key(selector): version = history.getVersionByLabel(selector) sticky = ('L', selector) elif self._branches.has_key(selector): version = history.getLatestVersion(selector) if selector == 'mainline': sticky = None else: sticky = ('B', selector) else: try: date = DateTime(selector) except: raise VersionControlError( 'Invalid version selector: %s' % selector ) else: timestamp = date.timeTime() sticky = ('D', timestamp) # Fix! branch = history.findBranchId(info.version_id) version = history.getVersionByDate(branch, timestamp) # If the state of the resource really needs to be changed, do the # update and make a log entry for the update. version_id = version and version.__name__ or info.version_id if version and (version_id != info.version_id): self.replaceState(object, version.copyState()) declare_checked_in(object) history.addLogEntry(version_id, ACTION_UPDATE, getPath(object)) # Update bookkeeping information. info = utility.VersionInfo(info.history_id, version_id, CHECKED_IN) if sticky is not None: info.sticky = sticky annotations = IAnnotations(object) annotations[VERSION_INFO_KEY] = info zope.event.notify(event.VersionUpdated(object, info, oldversion)) def copyVersion(self, object, selector): info = self.getVersionInfo(object) if info.status != CHECKED_OUT: raise VersionControlError( 'The selected resource is not checked out.' ) history = self.getVersionHistory(info.history_id) if history.hasVersionId(selector): version = history.getVersionById(selector) elif self._labels.has_key(selector): version = history.getVersionByLabel(selector) elif self._branches.has_key(selector): version = history.getLatestVersion(selector) else: raise VersionControlError( 'Invalid version selector: %s' % selector ) self.replaceState(object, version.copyState()) IAnnotations(object)[VERSION_INFO_KEY] = info declare_checked_out(object) def labelResource(self, object, label, force=0): info = self.getVersionInfo(object) if info.status != CHECKED_IN: raise VersionControlError( 'The selected resource must be checked in to be labeled.' ) # Make sure that labels and branch ids do not collide. if self._branches.has_key(label) or label == 'mainline': raise VersionControlError( 'The label value given is already in use as a branch id.' ) if not self._labels.has_key(label): self._labels[label] = 1 history = self.getVersionHistory(info.history_id) history.labelVersion(info.version_id, label, force) zope.event.notify(event.VersionLabelled(object, info, label)) def makeBranch(self, object, branch_id=None): # Note - this is not part of the official version control API yet. # It is here to allow unit testing of the architectural aspects # that are already in place to support activities in the future. info = self.getVersionInfo(object) if info.status != CHECKED_IN: raise VersionControlError( 'The selected resource must be checked in.' ) history = self.getVersionHistory(info.history_id) if branch_id is None: i = 1 while 1: branch_id = "%s.%d" % (info.version_id, i) if not (history._branches.has_key(branch_id) or self._labels.has_key(branch_id) ): break i += 1 # Make sure that branch ids and labels do not collide. if self._labels.has_key(branch_id) or branch_id == 'mainline': raise VersionControlError( 'The value given is already in use as a version label.' ) if not self._branches.has_key(branch_id): self._branches[branch_id] = 1 if history._branches.has_key(branch_id): raise VersionControlError( 'The resource is already associated with the given branch.' ) history.createBranch(branch_id, info.version_id) zope.event.notify(event.BranchCreated(object, info, branch_id)) return branch_id def getVersionOfResource(self, history_id, selector): history = self.getVersionHistory(history_id) sticky = None if not selector or selector == 'mainline': version = history.getLatestVersion('mainline') else: if history.hasVersionId(selector): version = history.getVersionById(selector) sticky = ('V', selector) elif self._labels.has_key(selector): version = history.getVersionByLabel(selector) sticky = ('L', selector) elif self._branches.has_key(selector): version = history.getLatestVersion(selector) sticky = ('B', selector) else: try: timestamp = zope.datetime.time(selector) except zope.datetime.DateTimeError: raise VersionControlError( 'Invalid version selector: %s' % selector ) else: sticky = ('D', timestamp) version = history.getVersionByDate('mainline', timestamp) object = version.copyState() declare_checked_in(object) info = utility.VersionInfo(history_id, version.__name__, CHECKED_IN) if sticky is not None: info.sticky = sticky annotations = IAnnotations(object) annotations[VERSION_INFO_KEY] = info zope.event.notify(event.VersionRetrieved(object, info)) return object def getVersionIds(self, object): info = self.getVersionInfo(object) history = self.getVersionHistory(info.history_id) return history.getVersionIds() def getLabelsForResource(self, object): info = self.getVersionInfo(object) history = self.getVersionHistory(info.history_id) return history.getLabels() def getLogEntries(self, object): info = self.getVersionInfo(object) history = self.getVersionHistory(info.history_id) return history.getLogEntries() def declare_checked_in(object): """Apply bookkeeping needed to recognize an object version controlled. """ ifaces = zope.interface.directlyProvidedBy(object) if ICheckedOut in ifaces: ifaces -= ICheckedOut ifaces += ICheckedIn zope.interface.directlyProvides(object, *ifaces) def declare_checked_out(object): """Apply bookkeeping needed to recognize an object version controlled. """ ifaces = zope.interface.directlyProvidedBy(object) if ICheckedIn in ifaces: ifaces -= ICheckedIn ifaces += ICheckedOut zope.interface.directlyProvides(object, *ifaces)
zope.app.versioncontrol
/zope.app.versioncontrol-0.1.tar.gz/zope.app.versioncontrol-0.1/src/zope/app/versioncontrol/repository.py
repository.py
import sys import time import persistent from BTrees.IOBTree import IOBTree from BTrees.IIBTree import IIBTree from BTrees.OOBTree import OOBTree import zope.location import zope.app.versioncontrol.utility import zope.app.versioncontrol.version from zope.app.versioncontrol.interfaces import VersionControlError class VersionHistory(persistent.Persistent, zope.location.Location): """A version history maintains the information about the changes to a particular version-controlled resource over time.""" def __init__(self, history_id): # The _versions mapping maps version ids to version objects. All # of the actual version data is looked up there. The _labels # mapping maps labels to specific version ids. The _branches map # manages BranchInfo objects that maintain branch information. self._eventLog = EventLog() self._versions = OOBTree() self._branches = OOBTree() self._labels = OOBTree() mainline = self.createBranch('mainline', None) self.__name__ = history_id def addLogEntry(self, version_id, action, path=None, message=''): """Add a new log entry associated with this version history.""" entry = LogEntry(version_id, action, path, message) self._eventLog.addEntry(entry) def getLogEntries(self): """Return a sequence of the log entries for this version history.""" return self._eventLog.getEntries() def getLabels(self): return self._labels.keys() def labelVersion(self, version_id, label, force=0): """Associate a particular version in a version history with the given label, removing any existing association with that label if force is true, or raising an error if force is false and an association with the given label already exists.""" current = self._labels.get(label) if current is not None: if current == version_id: return if not force: raise VersionControlError( 'The label %s is already associated with a version.' % ( label )) del self._labels[label] self._labels[label] = version_id def createBranch(self, branch_id, version_id): """Create a new branch associated with the given branch_id. The new branch is rooted at the version named by version_id.""" if self._branches.has_key(branch_id): raise VersionControlError( 'Branch already exists: %s' % branch_id ) branch = BranchInfo(branch_id, version_id) branch.__parent__ = self self._branches[branch_id] = branch return branch def createVersion(self, object, branch_id): """Create a new version in the line of descent named by the given branch_id, returning the newly created version object.""" branch = self._branches.get(branch_id) if branch is None: branch = self.createBranch(branch_id, None) if branch.__name__ != 'mainline': version_id = '%s.%d' % (branch.__name__, len(branch) + 1) else: version_id = '%d' % (len(branch) + 1) version = zope.app.versioncontrol.version.Version(version_id) # Update the predecessor, successor and branch relationships. # This is something of a hedge against the future. Versions will # always know enough to reconstruct their lineage without the help # of optimized data structures, which will make it easier to change # internals in the future if we need to. latest = branch.latest() if latest is not None: last = self._versions[latest] last.next = last.next + (version_id,) version.prev = latest # If the branch is not the mainline, store the branch name in the # version. Versions have 'mainline' as the default class attribute # which is the common case and saves a minor bit of storage space. if branch.__name__ != 'mainline': version.branch = branch.__name__ branch.append(version) self._versions[version_id] = version # Call saveState() only after version has been linked into the # database, ensuring it goes into the correct database. version.saveState(object) version.__parent__ = self return version def hasVersionId(self, version_id): """Return true if history contains a version with the given id.""" return self._versions.has_key(version_id) def isLatestVersion(self, version_id, branch_id): """Return true if version id is the latest in its branch.""" branch = self._branches[branch_id] return version_id == branch.latest() def getLatestVersion(self, branch_id): """Return the latest version object within the given branch, or None if the branch contains no versions. """ branch = self._branches[branch_id] version = self._versions[branch.latest()] return version def findBranchId(self, version_id): """Given a version id, return the id of the branch of the version. Note that we cheat, since we can find this out from the id. """ parts = version_id.split('.') if len(parts) > 1: return parts[-2] return 'mainline' def getVersionById(self, version_id): """Return the version object named by the given version id, or raise a VersionControlError if the version is not found. """ version = self._versions.get(version_id) if version is None: raise VersionControlError( 'Unknown version id: %s' % version_id ) return version def getVersionByLabel(self, label): """Return the version associated with the given label, or None if no version matches the given label. """ version_id = self._labels.get(label) version = self._versions.get(version_id) if version is None: return None return version def getVersionByDate(self, branch_id, timestamp): """Return the last version committed in the given branch on or before the given time value. The timestamp should be a float (time.time format) value in UTC. """ branch = self._branches[branch_id] tvalue = int(timestamp / 60.0) while 1: # Try to find a version with a commit date <= the given time # using the timestamp index in the branch information. if branch.m_order: try: match = branch.m_date.maxKey(tvalue) match = branch.m_order[branch.m_date[match]] return self._versions[match] except ValueError: pass # If we've run out of lineage without finding a version with # a commit date <= the given timestamp, we return None. It is # up to the caller to decide what to do in this situation. if branch.root is None: return None # If the branch has a root (a version in another branch), then # we check the root and do it again with the ancestor branch. rootver = self._versions[branch.root] if int(rootver.date_created / 60.0) < tvalue: return rootver branch = self._branches[rootver.branch] def getVersionIds(self, branch_id=None): """Return a sequence of version ids for versions in this history. If a branch_id is given, only version ids from that branch will be returned. Note that the sequence of ids returned does not include the id of the branch root. """ if branch_id is not None: return self._branches[branch_id].versionIds() return self._versions.keys() class BranchInfo(persistent.Persistent, zope.location.Location): """A utility class to hold branch (line-of-descent) information. It maintains the name of the branch, the version id of the root of the branch and indices to allow for efficient lookups. """ def __init__(self, name, root): # m_order maintains a newest-first mapping of int -> version id. # m_date maintains a mapping of a packed date (int # of minutes # since the epoch) to a lookup key in m_order. The two structures # are separate because we only support minute precision for date # lookups (and multiple versions could be added in a minute). self.date_created = time.time() self.m_order = IOBTree() self.m_date = IIBTree() self.__name__ = name self.root = root def append(self, version): """Append a version to the branch information. Note that this does not store the actual version, but metadata about the version to support ordering and date lookups. """ if len(self.m_order): key = self.m_order.minKey() - 1 else: key = sys.maxint self.m_order[key] = version.__name__ timestamp = int(version.date_created / 60.0) self.m_date[timestamp] = key def versionIds(self): """Return a newest-first sequence of version ids in the branch.""" return self.m_order.values() def latest(self): """Return the version id of the latest version in the branch.""" mapping = self.m_order if not len(mapping): return self.root return mapping[mapping.keys()[0]] def __len__(self): return len(self.m_order) class EventLog(persistent.Persistent): """An EventLog encapsulates a collection of log entries.""" def __init__(self): self._data = IOBTree() def addEntry(self, entry): """Add a new log entry.""" if len(self._data): key = self._data.minKey() - 1 else: key = sys.maxint self._data[key] = entry def getEntries(self): """Return a sequence of log entries.""" return self._data.values() def __len__(self): return len(self._data) def __nonzero__(self): return bool(self._data) class LogEntry(persistent.Persistent): """A LogEntry contains audit information about a version control operation. Actions that cause audit records to be created include checkout and checkin. Log entry information can be read (but not changed) by restricted code.""" def __init__(self, version_id, action, path=None, message=''): self.timestamp = time.time() self.version_id = version_id self.action = action self.message = message self.user_id = zope.app.versioncontrol.utility._findUserId() self.path = path
zope.app.versioncontrol
/zope.app.versioncontrol-0.1.tar.gz/zope.app.versioncontrol-0.1/src/zope/app/versioncontrol/history.py
history.py
Version Control =============== This package provides a framework for managing multiple versions of objects within a ZODB database. The framework defines several interfaces that objects may provide to participate with the framework. For an object to participate in version control, it must provide `IVersionable`. `IVersionable` is an interface that promises that there will be adapters to: - `INonVersionedData`, and - `IPhysicallyLocatable`. It also requires that instances support `IPersistent` and `IAnnotatable`. Normally, the INonVersionedData and IPhysicallyLocatable interfaces will be provided by adapters. To simplify the example, we'll just create a class that already implements the required interfaces directly. We need to be careful to avoid including the `__name__` and `__parent__` attributes in state copies, so even a fairly simple implementation of INonVersionedData has to deal with these for objects that contain their own location information. >>> import persistent >>> import zope.interface >>> import zope.component >>> import zope.traversing.interfaces >>> import zope.annotation.attribute >>> import zope.annotation.interfaces >>> from zope.app.versioncontrol import interfaces >>> marker = object() >>> class Sample(persistent.Persistent): ... zope.interface.implements( ... interfaces.IVersionable, ... interfaces.INonVersionedData, ... zope.annotation.interfaces.IAttributeAnnotatable, ... zope.traversing.interfaces.IPhysicallyLocatable, ... ) ... ... # Methods defined by INonVersionedData ... # This is a trivial implementation; using INonVersionedData ... # is discussed later. ... ... def listNonVersionedObjects(self): ... return () ... ... def removeNonVersionedData(self): ... if "__name__" in self.__dict__: ... del self.__name__ ... if "__parent__" in self.__dict__: ... del self.__parent__ ... ... def getNonVersionedData(self): ... return (getattr(self, "__name__", marker), ... getattr(self, "__parent__", marker)) ... ... def restoreNonVersionedData(self, data): ... name, parent = data ... if name is not marker: ... self.__name__ = name ... if parent is not marker: ... self.__parent__ = parent ... ... # Method from IPhysicallyLocatable that is actually used: ... def getPath(self): ... return '/' + self.__name__ ... ... def __repr__(self): ... return "<%s object>" % self.__class__.__name__ >>> zope.component.provideAdapter( ... zope.annotation.attribute.AttributeAnnotations) Now we need to create a database with an instance of our sample object to work with: >>> from ZODB.tests import util >>> import transaction >>> db = util.DB() >>> connection = db.open() >>> root = connection.root() >>> samp = Sample() >>> samp.__name__ = "samp" >>> root["samp"] = samp >>> transaction.commit() Some basic queries may be asked of objects without using an instance of `IRepository`. In particular, we can determine whether an object can be managed by version control by checking for the `IVersionable` interface: >>> interfaces.IVersionable.providedBy(samp) True >>> interfaces.IVersionable.providedBy(42) False We can also determine whether an object is actually under version control using the `IVersioned` interface: >>> interfaces.IVersioned.providedBy(samp) False >>> interfaces.IVersioned.providedBy(42) False Placing an object under version control requires an instance of an `IRepository` object. This package provides an implementation of this interface on the `Repository` class (from `zope.app.versioncontrol.repository`). Only the `IRepository` instance is responsible for providing version control operations; an object should never be asked to perform operations directly. >>> import zope.app.versioncontrol.repository >>> import zope.interface.verify >>> repository = zope.app.versioncontrol.repository.Repository() >>> zope.interface.verify.verifyObject( ... interfaces.IRepository, repository) True In order to actually use version control, there must be an interaction. This is needed to allow the framework to determine the user making changes. Let's set up an interaction now. >>> import zope.security.testing >>> principal = zope.security.testing.Principal('bob') >>> participation = zope.security.testing.Participation(principal) >>> import zope.security.management >>> zope.security.management.newInteraction(participation) Let's register some subscribers so we can check that interesting events are being fired for version control actions: >>> @zope.component.adapter(None, interfaces.IVersionEvent) ... def printEvent(object, event): ... print event ... >>> zope.component.provideHandler(printEvent) Now, let's put an object under version control and verify that we can determine that fact by checking against the interface: >>> repository.applyVersionControl(samp) applied version control to <Sample object> >>> interfaces.IVersioned.providedBy(samp) True >>> transaction.commit() Once an object is under version control, it's possible to get an information object that provides some interesting bits of data: >>> info = repository.getVersionInfo(samp) >>> type(info.history_id) <type 'str'> It's an error to ask for the version info for an object which isn't under revision control: >>> samp2 = Sample() >>> repository.getVersionInfo(samp2) Traceback (most recent call last): ... VersionControlError: Object is not under version control. >>> repository.getVersionInfo(42) Traceback (most recent call last): ... VersionControlError: Object is not under version control. The function `queryVersionInfo` returns a default value if an object isn't under version control: >>> print repository.queryVersionInfo(samp2) None >>> print repository.queryVersionInfo(samp2, 0) 0 >>> repository.queryVersionInfo(samp).version_id '1' You can retrieve a version of an object using the `.history_id` and a version selector. A version selector is a string that specifies which available version to return. The value `mainline` tells the `IRepository` to return the most recent version on the main branch. >>> ob = repository.getVersionOfResource(info.history_id, 'mainline') retrieved <Sample object>, version 1 >>> type(ob) <class 'zope.app.versioncontrol.README.Sample'> >>> ob is samp False >>> root["ob"] = ob >>> ob.__name__ = "ob" >>> ob_info = repository.getVersionInfo(ob) >>> ob_info.history_id == info.history_id True >>> ob_info is info False Once version control has been applied, the object can be "checked out", modified and "checked in" to create new versions. For many applications, this parallels form-based changes to objects, but this is a matter of policy. When version control is applied to an object, or when an object is retrieved from the repository, it is checked in. It provides `ICheckedIn`: >>> interfaces.ICheckedIn.providedBy(samp) True >>> interfaces.ICheckedIn.providedBy(ob) True It is not checked out: >>> interfaces.ICheckedOut.providedBy(samp) False >>> interfaces.ICheckedOut.providedBy(ob) False Let's save some information about the current version of the object so we can see that it changes: >>> orig_history_id = info.history_id >>> orig_version_id = info.version_id Now, let's check out the object: >>> repository.checkoutResource(ob) checked out <Sample object>, version 1 At this point, the object provides `ICheckedOut` and not `ICheckedIn`: >>> interfaces.ICheckedOut.providedBy(ob) True >>> interfaces.ICheckedIn.providedBy(ob) False Now, we'll and add an attribute: >>> ob.value = 42 >>> repository.checkinResource(ob) checked in <Sample object>, version 2 >>> transaction.commit() We can now compare information about the updated version with the original information: >>> newinfo = repository.getVersionInfo(ob) >>> newinfo.history_id == orig_history_id True >>> newinfo.version_id != orig_version_id True Retrieving both versions of the object allows use to see the differences between the two: >>> o1 = repository.getVersionOfResource(orig_history_id, ... orig_version_id) retrieved <Sample object>, version 1 >>> o2 = repository.getVersionOfResource(orig_history_id, ... newinfo.version_id) retrieved <Sample object>, version 2 >>> o1.value Traceback (most recent call last): ... AttributeError: 'Sample' object has no attribute 'value' >>> o2.value 42 We can determine whether an object that's been checked out is up-to-date with the most recent version from the repository: >>> repository.isResourceUpToDate(o1) False >>> repository.isResourceUpToDate(o2) True Asking whether a non-versioned object is up-to-date produces an error: >>> repository.isResourceUpToDate(42) Traceback (most recent call last): ... VersionControlError: Object is not under version control. >>> repository.isResourceUpToDate(samp2) Traceback (most recent call last): ... VersionControlError: Object is not under version control. It's also possible to check whether an object has been changed since it was checked out. Since we're only looking at changes that have been committed to the database, we'll start by making a change and committing it without checking a new version into the version control repository. >>> repository.updateResource(samp) updated <Sample object> from version 1 to 2 >>> repository.checkoutResource(samp) checked out <Sample object>, version 2 >>> interfaces.ICheckedOut.providedBy(samp) True >>> interfaces.ICheckedIn.providedBy(samp) False >>> transaction.commit() >>> repository.isResourceChanged(samp) False >>> samp.value += 1 >>> transaction.commit() We can now see that the object has been changed since it was last checked in: >>> repository.isResourceChanged(samp) True Checking in the object and commiting shows that we can now veryify that the object is considered up-to-date after a subsequent checkout. We'll also demonstrate that `checkinResource()` can take an optional message argument; we'll see later how this can be used. >>> repository.checkinResource(samp, 'sample checkin') checked in <Sample object>, version 3 >>> interfaces.ICheckedIn.providedBy(samp) True >>> interfaces.ICheckedOut.providedBy(samp) False >>> transaction.commit() >>> repository.checkoutResource(samp) checked out <Sample object>, version 3 >>> transaction.commit() >>> repository.isResourceUpToDate(samp) True >>> repository.isResourceChanged(samp) False >>> repository.getVersionInfo(samp).version_id '3' It's also possible to use version control to discard changes that haven't been checked in yet, even though they've been committed to the database for the "working copy". This is done using the `uncheckoutResource()` method of the `IRepository` object: >>> samp.value 43 >>> samp.value += 2 >>> samp.value 45 >>> transaction.commit() >>> repository.isResourceChanged(samp) True >>> repository.uncheckoutResource(samp) reverted <Sample object> to version 3 >>> transaction.commit() >>> samp.value 43 >>> repository.isResourceChanged(samp) False >>> version_id = repository.getVersionInfo(samp).version_id >>> version_id '3' An old copy of an object can be "updated" to the most recent version of an object: >>> ob = repository.getVersionOfResource(orig_history_id, orig_version_id) retrieved <Sample object>, version 1 >>> ob.__name__ = "foo" >>> repository.isResourceUpToDate(ob) False >>> repository.getVersionInfo(ob).version_id '1' >>> repository.updateResource(ob, version_id) updated <Sample object> from version 1 to 3 >>> repository.getVersionInfo(ob).version_id == version_id True >>> ob.value 43 It's possible to get a list of all the versions of a particular object from the repository as well. We can use any copy of the object to make the request: >>> list(repository.getVersionIds(samp)) ['1', '2', '3'] >>> list(repository.getVersionIds(ob)) ['1', '2', '3'] No version information is available for objects that have not had version control applied: >>> repository.getVersionIds(samp2) Traceback (most recent call last): ... VersionControlError: Object is not under version control. >>> repository.getVersionIds(42) Traceback (most recent call last): ... VersionControlError: Object is not under version control. Naming specific revisions ------------------------- Similar to other version control systems, specific versions may be given symbolic names, and these names may be used to retrieve versions from the repository. This package calls these names *labels*; they are similar to *tags* in CVS. Labels can be assigned to objects that are checked into the repository: >>> repository.labelResource(samp, 'my-first-label') created label my-first-label from version 3 of <Sample object> >>> repository.labelResource(samp, 'my-second-label') created label my-second-label from version 3 of <Sample object> The list of labels assigned to some version of an object can be retrieved using the repository's `getLabelsForResource()` method: >>> list(repository.getLabelsForResource(samp)) ['my-first-label', 'my-second-label'] The labels can be retrieved using any object that refers to the same line of history in the repository: >>> list(repository.getLabelsForResource(ob)) ['my-first-label', 'my-second-label'] Labels can be used to retrieve specific versions of an object from the repository: >>> repository.getVersionInfo(samp).version_id '3' >>> ob = repository.getVersionOfResource(orig_history_id, 'my-first-label') retrieved <Sample object>, version 3 >>> repository.getVersionInfo(ob).version_id '3' It's also possible to move a label from one version to another, but only when this is specifically indicated as allowed: >>> ob = repository.getVersionOfResource(orig_history_id, orig_version_id) retrieved <Sample object>, version 1 >>> ob.__name__ = "bar" >>> repository.labelResource(ob, 'my-second-label') ... # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... VersionControlError: The label my-second-label is already associated with a version. >>> repository.labelResource(ob, 'my-second-label', force=True) created label my-second-label from version 1 of <Sample object> Labels can also be used to update an object to a specific version: >>> repository.getVersionInfo(ob).version_id '1' >>> repository.updateResource(ob, 'my-first-label') updated <Sample object> from version 1 to 3 >>> repository.getVersionInfo(ob).version_id '3' >>> ob.value 43 Sticky settings --------------- Similar to CVS, this package supports a sort of "sticky" updating: if an object is updated to a specific date, determination of whether it is up-to-date or changed is based on the version it was updated to. >>> repository.updateResource(samp, orig_version_id) updated <Sample object> from version 3 to 1 >>> transaction.commit() >>> samp.value Traceback (most recent call last): ... AttributeError: 'Sample' object has no attribute 'value' >>> repository.getVersionInfo(samp).version_id == orig_version_id True >>> repository.isResourceChanged(samp) False >>> repository.isResourceUpToDate(samp) False The `isResourceUpToDate()` method indicates whether `checkoutResource()` will succeed or raise an exception: >>> repository.checkoutResource(samp) ... # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... VersionControlError: The selected resource has been updated to a particular version, label or date. The resource must be updated to the mainline or a branch before it may be checked out. TODO: Figure out how to write date-based tests. Perhaps the repository should implement a hook used to get the current date so tests can hook that. Examining the change history ---------------------------- >>> actions = { ... interfaces.ACTION_CHECKIN: "Check in", ... interfaces.ACTION_CHECKOUT: "Check out", ... interfaces.ACTION_UNCHECKOUT: "Uncheckout", ... interfaces.ACTION_UPDATE: "Update", ... } >>> entries = repository.getLogEntries(samp) >>> for entry in entries: ... print "Action:", actions[entry.action] ... print "Version:", entry.version_id ... print "Path:", entry.path ... if entry.message: ... print "Message:", entry.message ... print "--" Action: Update Version: 1 Path: /samp -- Action: Update Version: 3 Path: /bar -- Action: Update Version: 3 Path: /foo -- Action: Uncheckout Version: 3 Path: /samp -- Action: Check out Version: 3 Path: /samp -- Action: Check in Version: 3 Path: /samp Message: sample checkin -- Action: Check out Version: 2 Path: /samp -- Action: Update Version: 2 Path: /samp -- Action: Check in Version: 2 Path: /ob -- Action: Check out Version: 1 Path: /ob -- Action: Check in Version: 1 Path: /samp Message: Initial checkin. -- Note that the entry with the checkin entry for version 3 includes the comment passed to `checkinResource()`. The version history also contains the principal id related to each entry: >>> entries[0].user_id 'bob' Branches -------- We may wish to create parallel versions of objects. For example, we might want to create a version of content from an old version. We can do this by making a branch. To make a branch, we need to get an object for the version we want to branch from. Here's we'll get an object for revision 2: >>> obranch = repository.getVersionOfResource(orig_history_id, '2') retrieved <Sample object>, version 2 >>> obranch.__name__ = "obranch" >>> root["obranch"] = obranch >>> repository.getVersionInfo(obranch).version_id '2' Now we can use this object to make a branch: >>> repository.makeBranch(obranch) created branch 2.1 from version 2 of <Sample object> '2.1' The `makeBranch` method returns the new branch name. This is needed to check out a working version for the branch. To create a new version on the branch, we first have to check out the object on the branch: >>> repository.updateResource(obranch, '2.1') updated <Sample object> from version 2 to 2 >>> repository.checkoutResource(obranch) checked out <Sample object>, version 2 >>> repository.getVersionInfo(obranch).version_id '2' >>> obranch.value 42 >>> obranch.value = 100 >>> repository.checkinResource(obranch) checked in <Sample object>, version 2.1.1 >>> transaction.commit() >>> repository.getVersionInfo(obranch).version_id '2.1.1' Note that the new version number is the branch name followed by a number on the branch. Supporting separately versioned subobjects ------------------------------------------ `INonVersionedData` is responsible for dealing with parts of the object state that should *not* be versioned as part of this object. This can include both subobjects that are versioned independently as well as object-specific data that isn't part of the abstract resource the version control framework is supporting. For the sake of examples, let's create a simple class that actually implements these two interfaces. In this example, we'll create a simple object that excludes any versionable subobjects and any subobjects with names that start with "bob". Note that, as for the `Sample` class above, we're still careful to consider the values for `__name__` and `__parent__` to be non-versioned: >>> def ignored_item(name, ob): ... """Return True for non-versioned items.""" ... return (interfaces.IVersionable.providedBy(ob) ... or name.startswith("bob") ... or (name in ["__name__", "__parent__"])) >>> class SampleContainer(Sample): ... ... # Methods defined by INonVersionedData ... def listNonVersionedObjects(self): ... return [ob for (name, ob) in self.__dict__.items() ... if ignored_item(name, ob) ... ] ... ... def removeNonVersionedData(self): ... for name, value in self.__dict__.items(): ... if ignored_item(name, value): ... del self.__dict__[name] ... ... def getNonVersionedData(self): ... return [(name, ob) for (name, ob) in self.__dict__.items() ... if ignored_item(name, ob) ... ] ... ... def restoreNonVersionedData(self, data): ... for name, value in data: ... if name not in self.__dict__: ... self.__dict__[name] = value Let's take a look at how the `INonVersionedData` interface is used. We'll start by creating an instance of our sample container and storing it in the database: >>> box = SampleContainer() >>> box.__name__ = "box" >>> root[box.__name__] = box We'll also add some contained objects: >>> box.aList = [1, 2, 3] >>> samp1 = Sample() >>> samp1.__name__ = "box/samp1" >>> samp1.__parent__ = box >>> box.samp1 = samp1 >>> box.bob_list = [3, 2, 1] >>> bob_samp = Sample() >>> bob_samp.__name__ = "box/bob_samp" >>> bob_samp.__parent__ = box >>> box.bob_samp = bob_samp >>> transaction.commit() Let's apply version control to the container: >>> repository.applyVersionControl(box) applied version control to <SampleContainer object> We'll start by showing some basics of how the INonVersionedData interface is used. The `getNonVersionedData()`, `removeNonVersionedData()`, and `restoreNonVersionedData()` methods work together, allowing the version control framework to ensure that data that is not versioned as part of the object is not lost or inappropriately stored in the repository as part of version control operations. The basic pattern for this trio of operations is simple: 1. Use `getNonVersionedData()` to get a value that can be used to restore the current non-versioned data of the object. 2. Use `removeNonVersionedData()` to remove any non-versioned data from the object so it doesn't enter the repository as object state is copied around. 3. Make object state changes based on the version control operation being performed. 4. Use `restoreNonVersionedData()` to restore the data retrieved using `getNonVersionedData()`. This is fairly simple to see in an example. Step 1 is to save the non-versioned data: >>> saved = box.getNonVersionedData() While the version control framework treats this as an opaque value, we can take a closer look to make sure we got what we expected (since we know our implementation): >>> names = [name for (name, ob) in saved] >>> names.sort() >>> names ['__name__', 'bob_list', 'bob_samp', 'samp1'] Step 2 is to remove the data from the object: >>> box.removeNonVersionedData() The non-versioned data should no longer be part of the object: >>> box.bob_samp Traceback (most recent call last): ... AttributeError: 'SampleContainer' object has no attribute 'bob_samp' While versioned data should remain present: >>> box.aList [1, 2, 3] At this point, the version control framework will perform any appropriate state copies are needed. Once that's done, `restoreNonVersionedData()` will be called with the saved data to perform the restore operation: >>> box.restoreNonVersionedData(saved) We can verify that the restoraion has been performed by checking the non-versioned data: >>> box.bob_list [3, 2, 1] >>> type(box.samp1) <class 'zope.app.versioncontrol.README.Sample'> We can see how this is affects object state by making some changes to the container object's versioned and non-versioned data and watching how those attributes are affected by updating to specific versions using `updateResource()` and retrieving specific versions using `getVersionOfResource()`. Let's start by generating some new revisions in the repository: >>> repository.checkoutResource(box) checked out <SampleContainer object>, version 1 >>> transaction.commit() >>> version_id = repository.getVersionInfo(box).version_id >>> box.aList.append(4) >>> box.bob_list.append(0) >>> repository.checkinResource(box) checked in <SampleContainer object>, version 2 >>> transaction.commit() >>> box.aList [1, 2, 3, 4] >>> box.bob_list [3, 2, 1, 0] >>> repository.updateResource(box, version_id) updated <SampleContainer object> from version 2 to 1 >>> box.aList [1, 2, 3] >>> box.bob_list [3, 2, 1, 0] The remaining `listNonVersionedObjects()` method of the `INonVersionedData` interface is a little different, but remains very tightly tied to the details of the object's state. It should return a sequence of all the objects that should not be copied as part of the object's state. The difference between this method and `getNonVersionedData()` may seem simple, but is significant in practice. The `listNonVersionedObjects()` method allows the version control framework to identify data that should not be included in state copies, without saying anything else about the data. The `getNonVersionedData()` method allows the INonVersionedData implementation to communicate with itself (by providing data to be restored by the `restoreNonVersionedData()` method) without exposing any information about how it communicates with itself (it could store all the relevant data into an external file and use the value returned to locate the state file again, if that was needed for some reason). Copying old version data ------------------------ Sometimes, you'd like to copy old version data. You can do so with `copyVersion`: >>> ob = Sample() >>> ob.__name__ = 'samp' >>> root["samp"] = ob >>> transaction.commit() >>> ob.x = 1 >>> repository.applyVersionControl(ob) applied version control to <Sample object> >>> repository.checkoutResource(ob) checked out <Sample object>, version 1 >>> ob.x = 2 >>> repository.checkinResource(ob) checked in <Sample object>, version 2 >>> repository.copyVersion(ob, '1') Traceback (most recent call last): ... VersionControlError: The selected resource is not checked out. >>> repository.checkoutResource(ob) checked out <Sample object>, version 2 >>> ob.x = 3 >>> transaction.commit() >>> repository.copyVersion(ob, '1') >>> ob.x 1 >>> transaction.commit() >>> repository.isResourceChanged(ob) True >>> repository.checkinResource(ob) checked in <Sample object>, version 3
zope.app.versioncontrol
/zope.app.versioncontrol-0.1.tar.gz/zope.app.versioncontrol-0.1/src/zope/app/versioncontrol/README.txt
README.txt
import time from cStringIO import StringIO from cPickle import Pickler import persistent from ZODB.serialize import referencesf from ZODB.TimeStamp import TimeStamp import zope.location import zope.security.management import zope.app.versioncontrol.interfaces def isAVersionableResource(obj): """ True if an object is versionable. To qualify, the object must be persistent (have its own db record), and must not have an true attribute named '__non_versionable__'. """ return zope.app.versioncontrol.interfaces.IVersionable.providedBy(obj) class VersionInfo(persistent.Persistent): """Container for bookkeeping information. The bookkeeping information can be read (but not changed) by restricted code. """ def __init__(self, history_id, version_id, status): self.history_id = history_id self.version_id = version_id self.status = status self.touch() sticky = None def branchName(self): if self.sticky is not None and self.sticky[0] == 'B': return self.sticky[1] return 'mainline' def touch(self): self.user_id = _findUserId() self.timestamp = time.time() def _findUserId(): interaction = zope.security.management.getInteraction() return interaction.participations[0].principal.id def _findModificationTime(object): """Find the last modification time for a version-controlled object. The modification time reflects the latest modification time of the object or any of its persistent subobjects that are not themselves version-controlled objects. Note that this will return None if the object has no modification time.""" serial = [object._p_serial] def persistent_id(ob): s = getattr(ob, '_p_serial', None) if not isinstance(s, str): return None # TODO obviously no test for this if (zope.location.ILocation.providedBy(ob) and not zope.location.inside(ob, object)): return '1' # go away # The location check above should wake the object ## if getattr(ob, '_p_changed', 0) is None: ## ob._p_changed = 0 serial[0] = max(serial[0], s) return None stream = StringIO() p = Pickler(stream, 1) p.persistent_id = persistent_id p.dump(object) return serial[0]
zope.app.versioncontrol
/zope.app.versioncontrol-0.1.tar.gz/zope.app.versioncontrol-0.1/src/zope/app/versioncontrol/utility.py
utility.py
import tempfile import time from cStringIO import StringIO from cPickle import Pickler, Unpickler import persistent from BTrees.OOBTree import OOBTree import zope.location from zope.app.versioncontrol.interfaces import VersionControlError from zope.app.versioncontrol.interfaces import INonVersionedData def cloneByPickle(obj, ignore_list=()): """Makes a copy of a ZODB object, loading ghosts as needed. Ignores specified objects along the way, replacing them with None in the copy. """ ignore_dict = {} for o in ignore_list: ignore_dict[id(o)] = o ids = {"ignored": object()} def persistent_id(ob): if ignore_dict.has_key(id(ob)): return 'ignored' if (zope.location.ILocation.providedBy(ob) and not zope.location.inside(ob, obj)): myid = id(ob) ids[myid] = ob return myid # The location check above should wake the object ## if getattr(ob, '_p_changed', 0) is None: ## ob._p_changed = 0 return None stream = StringIO() p = Pickler(stream, 1) p.persistent_id = persistent_id p.dump(obj) stream.seek(0) u = Unpickler(stream) u.persistent_load = ids.get return u.load() class Version(persistent.Persistent, zope.location.Location): """A Version is a resource that contains a copy of a particular state (content and dead properties) of a version-controlled resource. A version is created by checking in a checked-out resource. The state of a version of a version-controlled resource never changes.""" def __init__(self, version_id): self.__name__ = version_id self.date_created = time.time() self._data = None # These attributes are set by the createVersion method of the version # history at the time the version is created. The branch is the name # of the branch on which the version was created. The prev attribute # is the version id of the predecessor to this version. The next attr # is a sequence of version ids of the successors to this version. branch = 'mainline' prev = None next = () def saveState(self, obj): """Save the state of `obj` as the state for this version of a version-controlled resource.""" self._data = self.stateCopy(obj) def copyState(self): """Return an independent deep copy of the state of the version.""" return self.stateCopy(self._data) def stateCopy(self, obj): """Get a deep copy of the state of an object. Breaks any database identity references. """ ignore = INonVersionedData(obj).listNonVersionedObjects() res = cloneByPickle(obj, ignore) INonVersionedData(res).removeNonVersionedData() return res
zope.app.versioncontrol
/zope.app.versioncontrol-0.1.tar.gz/zope.app.versioncontrol-0.1/src/zope/app/versioncontrol/version.py
version.py
from persistent import Persistent from persistent.dict import PersistentDict import zope.component from zope.interface import implements, classProvides from zope.schema.interfaces import IVocabularyTokenized from zope.schema.interfaces import ITokenizedTerm, IVocabularyFactory from zope.container.contained import Contained, setitem, uncontained from zope.app.workflow.interfaces import IProcessDefinitionElementContainer from zope.app.workflow.interfaces import IProcessDefinition class ProcessDefinition(Persistent, Contained): """Abstract Process Definition class. Must be inherited by a particular implementation. """ implements(IProcessDefinition) name = None def createProcessInstance(self, definition_name): """See zope.app.workflow.interfaces.IProcessDefinition""" return None class ProcessDefinitionElementContainer(Persistent, Contained): """See IProcessDefinitionElementContainer""" implements(IProcessDefinitionElementContainer) def __init__(self): super(ProcessDefinitionElementContainer, self).__init__() self.__data = PersistentDict() def keys(self): """See IProcessDefinitionElementContainer""" return self.__data.keys() def __iter__(self): return iter(self.__data.keys()) def __getitem__(self, name): """See IProcessDefinitionElementContainer""" return self.__data[name] def get(self, name, default=None): """See IProcessDefinitionElementContainer""" return self.__data.get(name, default) def values(self): """See IProcessDefinitionElementContainer""" return self.__data.values() def __len__(self): """See IProcessDefinitionElementContainer""" return len(self.__data) def items(self): """See IProcessDefinitionElementContainer""" return self.__data.items() def __contains__(self, name): """See IProcessDefinitionElementContainer""" return name in self.__data has_key = __contains__ def __setitem__(self, name, object): """See IProcessDefinitionElementContainer""" setitem(self, self.__data.__setitem__, name, object) def __delitem__(self, name): """See IProcessDefinitionElementContainer""" uncontained(self.__data[name], self, name) del self.__data[name] def getProcessDefinition(self): return self.__parent__ class ProcessDefinitionTerm(object): """A term representing the name of a process definition.""" implements(ITokenizedTerm) def __init__(self, name): self.value = self.token = name class ProcessDefinitionVocabulary(object): """Vocabulary providing available process definition names.""" implements(IVocabularyTokenized) classProvides(IVocabularyFactory) def __init__(self, context): self.sm = zope.component.getSiteManager(context) def __names(self): return [name for name, util in self.sm.getUtilitiesFor(IProcessDefinition)] def __contains__(self, value): """See zope.schema.interfaces.IVocabulary""" return value in self.__names() def __iter__(self): """See zope.schema.interfaces.IVocabulary""" terms = [ProcessDefinitionTerm(name) for name in self.__names()] return iter(terms) def __len__(self): """See zope.schema.interfaces.IVocabulary""" return len(self.__names()) def getTerm(self, value): """See zope.schema.interfaces.IVocabulary""" return ProcessDefinitionTerm(value) def getTermByToken(self, token): """See zope.schema.interfaces.IVocabularyTokenized""" return self.getTerm(token)
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/definition.py
definition.py
from types import StringTypes from persistent.dict import PersistentDict import zope.component from zope.proxy import removeAllProxies from zope.annotation.interfaces import IAnnotatable, IAnnotations from zope.interface import implements from zope.container.interfaces import IContained from zope.container.contained import Contained, setitem, uncontained from zope.app.workflow.interfaces import IProcessInstance, IProcessDefinition from zope.app.workflow.interfaces import IProcessInstanceContainer class ProcessInstance(Contained): """Process Instance implementation. Process instances are always added to a process instance container. This container lives in an annotation of the object and is commonly stored in the ZODB. Therefore a process instance should be persistent. """ implements(IProcessInstance) def __init__(self, pd_name): self._pd_name = pd_name self._status = None processDefinitionName = property(lambda self: self._pd_name) status = property(lambda self: self._status) ## should probably have a method "getProcessDefinition" def createProcessInstance(context, name): """Helper function to create a process instance from a process definition name.""" sm = zope.component.getSiteManager(context) pd = sm.queryUtility(IProcessDefinition, name) return pd.createProcessInstance(name) _marker = object() WFKey = "zope.app.worfklow.ProcessInstanceContainer" class ProcessInstanceContainerAdapter(object): implements(IProcessInstanceContainer) __used_for__ = IAnnotatable def __init__(self, context): self.context = context annotations = IAnnotations(context) wfdata = annotations.get(WFKey) if not wfdata: wfdata = PersistentDict() annotations[WFKey] = wfdata self.wfdata = wfdata def __getitem__(self, key): "See IProcessInstanceContainer" value = self.wfdata[key] return value def get(self, key, default=None): "See IProcessInstanceContainer" value = self.wfdata.get(key, _marker) if value is not _marker: return value else: return default def __contains__(self, key): "See IProcessInstanceContainer" return key in self.wfdata def values(self): "See IProcessInstanceContainer" return self.wfdata.values() def keys(self): "See IProcessInstanceContainer" return self.wfdata.keys() def __len__(self): "See IProcessInstanceContainer" return len(self.wfdata) def items(self): "See IProcessInstanceContainer" return self.wfdata.items() def __setitem__(self, key, object): "See IProcessInstanceContainer" # We cannot make the message the parent right away, since it is not # added to any message board yet; setitem(self, self.wfdata.__setitem__, key, object) # Set the final parent to be the message. if IContained.providedBy(object): object.__parent__ = self.context def __delitem__(self, key): "See IZopeWriteContainer" container = self.wfdata # publish event ? uncontained(container[key], self, key) del container[key] def __iter__(self): '''See interface IReadContainer''' return iter(self.wfdata)
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/instance.py
instance.py
from zope.interface import Interface, Attribute from zope.app.workflow.interfaces import IProcessDefinition from zope.app.workflow.interfaces import IProcessInstance from zope.container.interfaces import IContainer # TODO: # - Specify all attributes as schema fields where possible # - Define necessary methods for interfaces class IWfMCProcessDefinition(IProcessDefinition): """WfMC Workflow process definition. """ # will we have packages ?? # package = Attribute("ref to package") processDefinitionHeader = Attribute("ref to pd header") redefinableHeader = Attribute("ref to refinable header") formalParameters = Attribute("parameters that are interchanged e.g. " "subflow") relevantData = Attribute("wfr data definition") participants = Attribute("colletion of participants") applications = Attribute("collection of applictations") startActivity = Attribute("ref to start activity") endActivity = Attribute("ref to end activity") activities = Attribute("list activities contained by PD") transitions = Attribute("list transitions contained by PD") class IWfMCProcessDefinitionHeader(Interface): """WfMC Workflow process definition header. """ created = Attribute("date of creation") description = Attribute("description of package") validFrom = Attribute("date the PD is valid from") validTo = Attribute("date the PD is valid to") limit = Attribute("limit for timemanagement in units of DurationUnit") priority = Attribute("priority of PD") durationUnit = Attribute("Duration Unit") workingTime = Attribute("amount of time, performer of activity needs " "to perform task") waitingTime = Attribute("amount of time, needed to prepare performance " "of task") duration = Attribute("duration in units") timeEstimation = Attribute("estimated time for the process") class IWfMCProcessDefinitionElement(Interface): """WfMC process definition Element.""" # components usually don't know their id within a container # id = Attribute("id of ProcessDefinitionElement") # we have to decide how to handle the Extended Attributes extendedAttributes = Attribute("list of extended Attributes") ## FormalParameter Declaration class IWfMCFormalParameter(IContainer): """WfMC Formal Parameters Container. """ class IWfMCFormalParameter(IWfMCProcessDefinitionElement): """WfMC Formal Parameter. """ mode = Attribute("mode: in/out/inout") index = Attribute("index of par") dataType = Attribute("data type of Parameter") description = Attribute("the Parameter Description") ## RelevantData Declaration class IWfMCRelevantDataContainer(IContainer): """WfMC Relevant Data Container. """ class IWfMCRelevantData(IWfMCProcessDefinitionElement): """WfMC Relevant Data. """ name = Attribute("name of DataField") isArray = Attribute("is array ?") dataType = Attribute("type of data") initialValue = Attribute("initial Value") description = Attribute("description of WFRD") ## Application Declaration class IWfMCApplicationContainer(IContainer): """WfMC Application Definition Container. """ class IWfMCApplication(IWfMCProcessDefinitionElement): """WfMC Application Definition. """ name = Attribute("Name of Application.") description = Attribute("Description of Application.") formalParameterList = Attribute("Sequence of Formal Parameters.") ## Participant Declaration class IWfMCParticipantContainer(IContainer): """WfMC Participant Definition Container. """ class IWfMCParticipant(IWfMCProcessDefinitionElement): """WfMC Participant Definition. """ name = Attribute("Name of Participant.") type = Attribute("""Type of Participant: RESOURCE_SET/RESOURCE/ROLE/ ORGANIZATIONAL_UNIT/HUMAN/SYSTEM""") description = Attribute("Description of Participant.") ## Activity class IWfMCActivityContainer(IContainer): """WfMC Activity Container. """ class IWfMCActivity(IWfMCProcessDefinitionElement): """WfMC Activity. """ # we get get this via acquisition # processDefinition = Attribute("ref to PD the activity belongs to") name = Attribute("a Activity Name") description = Attribute("a description") isRoute = Attribute("is this a route Activity") startMode = Attribute("how Activity is started (0-Manual/1-Automatic)") finishMode = Attribute("how Activity is finished (0-Manual/1-Automatic)") performer = Attribute("link to workflow participant (may be expression)") implementation = Attribute("if not Route-Activity: mandatory " "(no/tool+/subflow/loop)") instantiation = Attribute("capability: once/multiple times") priority = Attribute("priority of Activity") cost = Attribute("average cost") workingTime = Attribute("amount of time, performer of activity needs " "to perform task") waitingTime = Attribute("amount of time, needed to prepare performance " "of task") duration = Attribute("duration of activity") limit = Attribute("limit in costUnits") icon = Attribute("icon of activity") documentation = Attribute("documentation") splitMode = Attribute("split Mode (and/xor)") joinMode = Attribute("join Mode (and/xor)") inlineBlock = Attribute("inline Block definition") class IWfMCImplementation(IWfMCProcessDefinitionElement): """WfMC Implementation Definition. is referenced by Activity Attribute: implementation. """ type = Attribute("Type of Implementation: NO/SUBFLOW/TOOL") class IWfMCSubflow(IWfMCImplementation): """WfMC Implementation Subflow. """ name = Attribute("Name of Subflow to start.") execution = Attribute("Type of Execution: Asynchr/synchr.") actualParameterList = Attribute("Sequence of ActualParameters with those " "the new Instance is initialized and " "whose are returned.") class IWfMCTool(IWfMCImplementation): """WfMC Implementation Subflow. """ name = Attribute("Name of Application/Procedure to invoke " "(Application Declaration).") type = Attribute("Type of Tool: APPLICATION/PROCEDURE.") description = Attribute("Description of Tool.") actualParameterList = Attribute("Sequence of ActualParameters with those " "the new Instance is initialized and " "whose are returned.") ## Transition class IWfMCCondition(Interface): """WfMC Condition. """ type = Attribute("Type of Condition: CONDITION/OTHERWISE") expression = Attribute("Expression to evaluate.") class IWfMCTransitionContainer(IContainer): """WfMC Transition Container. """ class IWfMCTransition(IWfMCProcessDefinitionElement): """WfMC Transition. """ name = Attribute("Name of Transition.") condition = Attribute("ref to Condition.") fromActivityId = Attribute("Id of FromActivity.") toActivityId = Attribute("Id of ToActivity.") class IWfMCProcessInstanceData(Interface): """WfMC ProcessInstance Data. This is a base interfaces that gets extended dynamically when creating a ProcessInstance from the relevantData Spec. """ class IWfMCProcessInstance(IProcessInstance): """WfMC Workflow process instance. """ processDefinitionId = Attribute("Id of ProcessDefinition.") name = Attribute("Name of ProcessInstance.") creationTime = Attribute("Creation Time of ProcessInstance.") activityInstances = Attribute("ref to ActivityInstanceContainer.") data = Attribute("WorkflowRelevant Data (instance, not definition.)") # We might need an actual Participantlist for the implementation. class IWfMCActivityInstanceContainer(IContainer): """WfMC ActivityInstance Container. """ class IWfMCActivityInstance(Interface): """WfMC Workflow activity instance. """ activityId = Attribute("Id of Activity.") name = Attribute("Name of ActivityInstance.") creationTime = Attribute("Creation Time of ActivityInstance.") status = Attribute("Status of ActivityInstance.") priority = Attribute("Priority of ActivityInstance (initialized from " "Activity).") workitems = Attribute("ref to WorkitemContainer.") # participants = Attribute("Sequence of assigned Participants.") class IWfMCWorkitemContainer(IContainer): """WfMC Workitem Container. """ class IWfMCWorkitem(Interface): """WfMC Workflow instance. """ status = Attribute("Status of Workitem.") priority = Attribute("Priority of Workitem.") participant = Attribute("Participant that is assigned to do this item " "of Work.")
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/interfaces/wfmc.py
wfmc.py
from zope.interface import Interface, Attribute from zope.i18nmessageid import ZopeMessageFactory as _ from zope.container.interfaces import IContainer class IWorkflowEvent(Interface): """This event describes a generic event that is triggered by the workflow mechanism.""" class IProcessDefinition(Interface): """Interface for workflow process definition.""" name = Attribute("""The name of the ProcessDefinition""") def createProcessInstance(definition_name): """Create a new process instance for this process definition. Returns an IProcessInstance.""" class IProcessDefinitionElementContainer(IContainer): """Abstract Interface for ProcessDefinitionElementContainers.""" def getProcessDefinition(): """Return the ProcessDefinition Object.""" class IProcessInstance(Interface): """Workflow process instance. Represents the instance of a process defined by a ProcessDefinition.""" status = Attribute("The status in which the workitem is.") processDefinitionName = Attribute("The process definition Name.") class IProcessInstanceContainer(IContainer): """Workflow process instance container.""" class IProcessInstanceContainerAdaptable(Interface): """Marker interface for components that can be adapted to a process instance container.""" class IProcessInstanceControl(Interface): """Interface to interact with a process instance.""" def start(): """Start a process instance.""" def finish(): """Finish a process instance.""" class IWorklistHandler(Interface): """Base interface for Workflow Worklist Handler.""" def getWorkitems(): """Return a sequence of workitem.""" class IProcessDefinitionImportHandler(Interface): """Handler for Import of ProcessDefinitions.""" def canImport(data): """Check if handler can import a processdefinition based on the data given.""" def doImport(data): """Create a ProcessDefinition from the data given. Returns a ProcessDefinition Instance.""" class IProcessDefinitionExportHandler(Interface): """Handler for Export of ProcessDefinitions.""" def doExport(): """Export a ProcessDefinition into a specific format. Returns the serialized value of the given ProcessDefintion."""
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/interfaces/__init__.py
__init__.py
import urllib from zope.schema import getFieldNames from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile from zope.app.workflow.interfaces import IProcessInstanceContainerAdaptable from zope.app.workflow.interfaces import IProcessInstanceContainer from zope.app.workflow.stateful.interfaces import IStatefulProcessInstance class InstanceContainerView(object): __used_for__ = IProcessInstanceContainerAdaptable def _extractContentInfo(self, item): id, obj = item info = {} info['id'] = id info['object'] = obj info['url'] = "processinstance.html?pi_name=%s" %urllib.quote_plus(id) return info def removeObjects(self, ids): """Remove objects specified in a list of object ids""" container = IProcessInstanceContainer(self.context) for id in ids: container.__delitem__(id) self.request.response.redirect('@@processinstances.html') def listContentInfo(self): return map(self._extractContentInfo, IProcessInstanceContainer(self.context).items()) contents = ViewPageTemplateFile('instancecontainer_main.pt') contentsMacros = contents _index = ViewPageTemplateFile('instancecontainer_index.pt') def index(self): if 'index.html' in self.context: self.request.response.redirect('index.html') return '' return self._index() # ProcessInstance Details # TODO: # This is temporary till we find a better name to use # objects that are stored in annotations # Steve suggested a ++annotations++<key> Namespace for that. # we really want to traverse to the instance and display a view def _getProcessInstanceData(self, data): names = [] for interface in providedBy(data): names.append(getFieldNames(interface)) return dict([(name, getattr(data, name, None),) for name in names]) def getProcessInstanceInfo(self, pi_name): info = {} pi = IProcessInstanceContainer(self.context)[pi_name] info['status'] = pi.status # temporary if IStatefulProcessInstance.providedBy(pi): info['outgoing_transitions'] = pi.getOutgoingTransitions() if pi.data is not None: info['data'] = self._getProcessInstanceData(pi.data) else: info['data'] = None return info def _fireTransition(self, pi_name, id): pi = IProcessInstanceContainer(self.context)[pi_name] pi.fireTransition(id) _instanceindex = ViewPageTemplateFile('instance_index.pt') def instanceindex(self): """ProcessInstance detail view.""" request = self.request pi_name = request.get('pi_name') if pi_name is None: request.response.redirect('index.html') return '' if request.has_key('fire_transition'): self._fireTransition(pi_name, request['fire_transition']) return self._instanceindex()
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/browser/instance.py
instance.py
from persistent import Persistent from persistent.dict import PersistentDict from zope.interface import implements, classProvides from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm from zope.schema.interfaces import IVocabularyFactory from zope.security.checker import CheckerPublic from zope.event import notify from zope.component.interfaces import ObjectEvent from zope.lifecycleevent import modified from zope.traversing.api import getParents from zope.container.interfaces import IReadContainer from zope.container.contained import Contained, containedEvent from zope.app.workflow.definition import ProcessDefinition from zope.app.workflow.definition import ProcessDefinitionElementContainer from zope.app.workflow.stateful.interfaces import IStatefulProcessDefinition from zope.app.workflow.stateful.interfaces import IState, ITransition, INITIAL from zope.app.workflow.stateful.interfaces import IStatefulStatesContainer from zope.app.workflow.stateful.interfaces import IStatefulTransitionsContainer from zope.app.workflow.stateful.interfaces import MANUAL from zope.app.workflow.stateful.instance import StatefulProcessInstance class State(Persistent, Contained): """State.""" implements(IState) class StatesContainer(ProcessDefinitionElementContainer): """Container that stores States.""" implements(IStatefulStatesContainer) class NoLocalProcessDefinition(Exception): """No local process definition found""" class StateNamesVocabulary(SimpleVocabulary): """Vocabulary providing the names of states in a local process definition. """ classProvides(IVocabularyFactory) def __init__(self, context): terms = [SimpleTerm(name) for name in self._getStateNames(context)] super(StateNamesVocabulary, self).__init__(terms) def _getStateNames(self, context): if hasattr(context, 'getProcessDefinition'): return context.getProcessDefinition().getStateNames() else: for obj in getParents(context): if IStatefulProcessDefinition.providedBy(obj): return obj.getStateNames() raise NoLocalProcessDefinition('No local process definition found.') class Transition(Persistent, Contained): """Transition from one state to another.""" implements(ITransition) # See ITransition sourceState = None destinationState = None condition = None script = None permission = CheckerPublic triggerMode = MANUAL def __init__(self, sourceState=None, destinationState=None, condition=None, script=None, permission=CheckerPublic, triggerMode=None): super(Transition, self).__init__() self.sourceState = sourceState self.destinationState = destinationState self.condition = condition or None self.script = script or None self.permission = permission or None self.triggerMode = triggerMode def getProcessDefinition(self): return self.__parent__.getProcessDefinition() class TransitionsContainer(ProcessDefinitionElementContainer): """Container that stores Transitions.""" implements(IStatefulTransitionsContainer) class StatefulProcessDefinition(ProcessDefinition): """Stateful workflow process definition.""" implements(IStatefulProcessDefinition, IReadContainer) classProvides(IVocabularyFactory) def __init__(self): super(StatefulProcessDefinition, self).__init__() self.__states = StatesContainer() initial = State() self.__states[self.getInitialStateName()] = initial self.__transitions = TransitionsContainer() self.__schema = None self._publishModified('transitions', self.__transitions) self._publishModified('states', self.__states) # See workflow.stateful.IStatefulProcessDefinition self.schemaPermissions = PersistentDict() _clear = clear = __init__ def _publishModified(self, name, object): object, event = containedEvent(object, self, name) if event: notify(event) modified(self) def getRelevantDataSchema(self): return self.__schema def setRelevantDataSchema(self, schema): self.__schema = schema # See workflow.stateful.IStatefulProcessDefinition relevantDataSchema = property(getRelevantDataSchema, setRelevantDataSchema, None, "Schema for RelevantData.") # See workflow.stateful.IStatefulProcessDefinition states = property(lambda self: self.__states) # See workflow.stateful.IStatefulProcessDefinition transitions = property(lambda self: self.__transitions) def addState(self, name, state): """See workflow.stateful.IStatefulProcessDefinition""" if name in self.states: raise KeyError(name) self.states[name] = state def getState(self, name): """See workflow.stateful.IStatefulProcessDefinition""" return self.states[name] def removeState(self, name): """See workflow.stateful.IStatefulProcessDefinition""" del self.states[name] def getStateNames(self): """See workflow.stateful.IStatefulProcessDefinition""" return self.states.keys() def getInitialStateName(self): """See workflow.stateful.IStatefulProcessDefinition""" return INITIAL def addTransition(self, name, transition): """See workflow.stateful.IStatefulProcessDefinition""" if name in self.transitions: raise KeyError(name) self.transitions[name] = transition def getTransition(self, name): """See workflow.stateful.IStatefulProcessDefinition""" return self.transitions[name] def removeTransition(self, name): """See workflow.stateful.IStatefulProcessDefinition""" del self.transitions[name] def getTransitionNames(self): """See workflow.stateful.IStatefulProcessDefinition""" return self.transitions.keys() def createProcessInstance(self, definition_name): """See workflow.IProcessDefinition""" pi_obj = StatefulProcessInstance(definition_name) # TODO: # Process instances need to have a place, so they can look things # up. It's not clear to me (Jim) what place they should have. # The parent of the process instance should be the object it is # created for!!! This will cause all sorts of head-aches, but at this # stage we do not have the object around; it would need some API # changes to do that. (SR) pi_obj.__parent__ = self pi_obj.initialize() return pi_obj def __getitem__(self, key): "See Interface.Common.Mapping.IReadMapping" result = self.get(key) if result is None: raise KeyError(key) return result def get(self, key, default=None): "See Interface.Common.Mapping.IReadMapping" if key == 'states': return self.states if key == 'transitions': return self.transitions return default def __contains__(self, key): "See Interface.Common.Mapping.IReadMapping" return self.get(key) is not None def __iter__(self): """See zope.container.interfaces.IReadContainer""" return iter(self.keys()) def keys(self): """See zope.container.interfaces.IReadContainer""" return ['states', 'transitions'] def values(self): """See zope.container.interfaces.IReadContainer""" return map(self.get, self.keys()) def items(self): """See zope.container.interfaces.IReadContainer""" return [(key, self.get(key)) for key in self.keys()] def __len__(self): """See zope.container.interfaces.IReadContainer""" return 2
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/stateful/definition.py
definition.py
import zope.schema from zope.security.checker import CheckerPublic from zope.interface import Interface, Attribute from zope.i18nmessageid import ZopeMessageFactory as _ from zope.app.workflow.interfaces import IWorkflowEvent from zope.app.workflow.interfaces import IProcessDefinition from zope.app.workflow.interfaces import IProcessInstance from zope.app.workflow.interfaces import IProcessDefinitionElementContainer AUTOMATIC = u'Automatic' MANUAL = u'Manual' INITIAL = u'INITIAL' class ITransitionEvent(IWorkflowEvent): """An event that signalizes a transition from one state to another.""" object = Attribute("""The content object whose status will be changed.""") process = Attribute("""The process instance that is doing the transition. Note that this object really represents the workflow.""") transition = Attribute("""The transition that is being fired/executed. It contains all the specific information, such as source and destination state.""") class IBeforeTransitionEvent(ITransitionEvent): """This event is published before a the specified transition occurs. This allows other objects to veto the transition.""" class IAfterTransitionEvent(ITransitionEvent): """This event is published after the transition. This is important for objects that might change permissions when changing the status.""" class IRelevantDataChangeEvent(IWorkflowEvent): """This event is fired, when the object's data changes and the data is considered 'relevant' to the workflow. The attributes of interest are usually defined by a so called Relevant Data Schema.""" process = Attribute("""The process instance that is doing the transition. Note that this object really represents the workflow.""") schema = Attribute("""The schema that defines the relevant data attributes.""") attributeName = Attribute("""Name of the attribute that is changed.""") oldValue = Attribute("""The old value of the attribute.""") newValue = Attribute("""The new value of the attribute.""") class IBeforeRelevantDataChangeEvent(IRelevantDataChangeEvent): """This event is triggered before some of the workflow-relevant data is being changed.""" class IAfterRelevantDataChangeEvent(IRelevantDataChangeEvent): """This event is triggered after some of the workflow-relevant data has been changed.""" class IState(Interface): """Interface for state of a stateful workflow process definition.""" # TODO: Should at least have a title, if not a value as well class IStatefulStatesContainer(IProcessDefinitionElementContainer): """Container that stores States.""" class ITransition(Interface): """Stateful workflow transition.""" sourceState = zope.schema.Choice( title=_(u"Source State"), description=_(u"Name of the source state."), vocabulary=u"Workflow State Names", required=True) destinationState = zope.schema.Choice( title=_(u"Destination State"), description=_(u"Name of the destination state."), vocabulary=u"Workflow State Names", required=True) condition = zope.schema.TextLine( title=_(u"Condition"), description=_(u"""The condition that is evaluated to decide if the transition can be fired or not."""), required=False) script = zope.schema.TextLine( title=_(u"Script"), description=_(u"""The script that is evaluated to decide if the transition can be fired or not."""), required=False) permission = zope.schema.Choice( title=_(u"The permission needed to fire the Transition."), vocabulary="Permission Ids", default=CheckerPublic, required=True) triggerMode = zope.schema.Choice( title=_(u"Trigger Mode"), description=_(u"How the Transition is triggered (Automatic/Manual)"), default=MANUAL, values=[MANUAL, AUTOMATIC]) def getProcessDefinition(): """Return the ProcessDefinition Object.""" class IStatefulTransitionsContainer(IProcessDefinitionElementContainer): """Container that stores Transitions.""" class IStatefulProcessDefinition(IProcessDefinition): """Interface for stateful workflow process definition.""" relevantDataSchema = zope.schema.Choice( title=_(u"Workflow-Relevant Data Schema"), description=_(u"Specifies the schema that characterizes the workflow " u"relevant data of a process instance, found in pd.data."), vocabulary="Interfaces", default=None, required=False) schemaPermissions = Attribute(u"A dictionary that maps set/get permissions" u"on the schema's fields. Entries looks as" u"follows: {fieldname:(set_perm, get_perm)}") states = Attribute("State objects container.") transitions = Attribute("Transition objects container.") def addState(name, state): """Add a IState to the process definition.""" def getState(name): """Get the named state.""" def removeState(name): """Remove a state from the process definition Raises ValueError exception if trying to delete the initial state. """ def getStateNames(): """Get the state names.""" def getInitialStateName(): """Get the name of the initial state.""" def addTransition(name, transition): """Add a ITransition to the process definition.""" def getTransition(name): """Get the named transition.""" def removeTransition(name): """Remove a transition from the process definition.""" def getTransitionNames(): """Get the transition names.""" def clear(): """Clear the whole ProcessDefinition.""" class IStatefulProcessInstance(IProcessInstance): """Workflow process instance. Represents the instance of a process defined by a StatefulProcessDefinition. """ data = Attribute("Relevant Data object.") def initialize(): """Initialize the ProcessInstance. set Initial State and create relevant Data. """ def getOutgoingTransitions(): """Get the outgoing transitions.""" def fireTransition(id): """Fire a outgoing transitions.""" def getProcessDefinition(): """Get the process definition for this instance.""" class IContentProcessRegistry(Interface): """Content Type <-> Process Definitions Registry This is a registry for mapping content types (interface) to workflow process definitions (by name). """ def register(iface, name): """Register a new process definition (name) for the interface iface.""" def unregister(iface, name): """Unregister a process (name) for a particular interface.""" def getProcessNamesForInterface(iface): """Return a list of process defintion names for the particular interface.""" def getInterfacesForProcessName(name): """Return a list of interfaces for the particular process name.""" class IContentWorkflowsManager(IContentProcessRegistry): """A Content Workflows Manager. It associates content objects with some workflow process definitions. """ def getProcessDefinitionNamesForObject(object): """Get the process definition names for a particular object. This method reads in all the interfaces this object implements and finds then the corresponding process names using the IContentProcessRegistry."""
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/stateful/interfaces.py
interfaces.py
from xml.sax import parseString from xml.sax.handler import ContentHandler import zope.component from zope.configuration.name import resolve from zope.interface import implements from zope.proxy import removeAllProxies from zope.security.checker import CheckerPublic from zope.security.proxy import removeSecurityProxy from zope.dublincore.interfaces import IZopeDublinCore from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile from zope.app.security.interfaces import IPermission from zope.app.workflow.interfaces import IProcessDefinitionImportHandler from zope.app.workflow.interfaces import IProcessDefinitionExportHandler from zope.app.workflow.stateful.definition import State, Transition from zope.app.workflow.stateful.interfaces import IStatefulProcessDefinition # basic implementation for a format-checker class XMLFormatChecker(ContentHandler): def __init__(self): self.__valid = False def startElement(self, name, attrs): if name == 'workflow' and attrs.get('type',None) == 'StatefulWorkflow': self.__valid = True def endElement(self, name): pass def isValid(self): return self.__valid class XMLStatefulImporter(ContentHandler): def __init__(self, context, encoding='latin-1'): self.context = context self.encoding = encoding def startElement(self, name, attrs): handler = getattr(self, 'start' + name.title().replace('-', ''), None) if not handler: raise ValueError('Unknown element %s' % name) handler(attrs) def endElement(self, name): handler = getattr(self, 'end' + name.title().replace('-', ''), None) if handler: handler() def noop(*args): pass startStates = noop startTransitions = noop startPermissions = noop def startWorkflow(self, attrs): dc = IZopeDublinCore(self.context) dc.title = attrs.get('title', u'') def startSchema(self, attrs): name = attrs['name'].encode(self.encoding).strip() if name: self.context.relevantDataSchema = resolve(name) def startPermission(self, attrs): perms = removeSecurityProxy(self.context.schemaPermissions) fieldName = attrs.get('for') type = attrs.get('type') perm_id = attrs.get('id') if perm_id == 'zope.Public': perm = CheckerPublic elif perm_id == '': perm = None else: perm = zope.component.getUtility(IPermission, perm_id) if not fieldName in perms.keys(): perms[fieldName] = (CheckerPublic, CheckerPublic) if type == u'get': perms[fieldName] = (perm, perms[fieldName][1]) if type == u'set': perms[fieldName] = (perms[fieldName][0], perm) def startState(self, attrs): name = attrs['name'] if name == 'INITIAL': state = self.context.getState('INITIAL') dc = IZopeDublinCore(state) dc.title = attrs.get('title', u'') else: state = State() dc = IZopeDublinCore(state) dc.title = attrs.get('title', u'') self.context.addState(name, state) def startTransition(self, attrs): name = attrs['name'] permission = attrs.get('permission', u'zope.Public') if permission == u'zope.Public': permission = CheckerPublic trans = Transition( sourceState = attrs['sourceState'], destinationState = attrs['destinationState'], condition = attrs.get('condition', None), script = attrs.get('script', None), permission = permission, triggerMode = attrs['triggerMode'] ) dc = IZopeDublinCore(trans) dc.title = attrs.get('title', u'') self.context.addTransition(name, trans) class XMLImportHandler(object): implements(IProcessDefinitionImportHandler) def __init__(self, context): self.context = context def canImport(self, data): # TODO: Implementation needs more work !! # check if xml-data can be imported and represents a StatefulPD checker = XMLFormatChecker() parseString(data, checker) return (bool(IStatefulProcessDefinition.providedBy(self.context)) and checker.isValid()) def doImport(self, data): # Clear the process definition self.context.clear() parseString(data, XMLStatefulImporter(self.context)) class XMLExportHandler(object): implements(IProcessDefinitionExportHandler) template = ViewPageTemplateFile('xmlexport_template.pt') def __init__(self, context): self.context = context def doExport(self): # Unfortunately, the template expects its parent to have an attribute # called request. from zope.publisher.browser import TestRequest self.request = TestRequest() return self.template() def getDublinCore(self, obj): return IZopeDublinCore(obj) def getPermissionId(self, permission): if isinstance(permission, str) or isinstance(permission, unicode): return permission if permission is CheckerPublic: return 'zope.Public' if permission is None: return '' permission = removeAllProxies(permission) return permission.id def getSchemaPermissions(self): info = [] perms = self.context.schemaPermissions for field, (getPerm, setPerm) in perms.items(): info.append({'fieldName': field, 'type': 'get', 'id': self.getPermissionId(getPerm)}) info.append({'fieldName': field, 'type': 'set', 'id': self.getPermissionId(setPerm)}) return info def relevantDataSchema(self): schema = removeAllProxies(self.context.relevantDataSchema) if schema is None: return 'None' return schema.__module__ + '.' + schema.getName()
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/stateful/xmlimportexport.py
xmlimportexport.py
from persistent import Persistent from persistent.dict import PersistentDict from zope.component import getUtilitiesFor from zope.interface import implements, providedBy from zope.lifecycleevent.interfaces import IObjectCreatedEvent from zope.app.workflow.interfaces import IProcessInstanceContainer from zope.app.workflow.interfaces import IProcessInstanceContainerAdaptable from zope.app.workflow.stateful.interfaces import IContentWorkflowsManager from zope.app.workflow.instance import createProcessInstance from zope.container.contained import Contained def NewObjectProcessInstanceCreator(obj, event): # used for: IProcessInstanceContainerAdaptable, IObjectCreatedEvent pi_container = IProcessInstanceContainer(obj) for (ignored, cwf) in getUtilitiesFor(IContentWorkflowsManager): # here we will lookup the configured processdefinitions # for the newly created compoent. For every pd_name # returned we will create a processinstance. # Note that we use getUtilitiesFor rather than getAllUtilitiesFor # so that we don't use overridden content-workflow managers. for pd_name in cwf.getProcessDefinitionNamesForObject(obj): if pd_name in pi_container.keys(): continue try: pi = createProcessInstance(cwf, pd_name) except KeyError: # No registered PD with that name.. continue pi_container[pd_name] = pi class ContentWorkflowsManager(Persistent, Contained): implements(IContentWorkflowsManager) def __init__(self): super(ContentWorkflowsManager, self).__init__() self._registry = PersistentDict() def getProcessDefinitionNamesForObject(self, object): """See interfaces.workflows.stateful.IContentWorkflowsManager""" names = () for iface in providedBy(object): names += self.getProcessNamesForInterface(iface) return names def getProcessNamesForInterface(self, iface): """See zope.app.workflow.interfacess.stateful.IContentProcessRegistry""" return self._registry.get(iface, ()) def getInterfacesForProcessName(self, name): ifaces = [] for iface, names in self._registry.items(): if name in names: ifaces.append(iface) return tuple(ifaces) def register(self, iface, name): """See zope.app.workflow.interfacess.stateful.IContentProcessRegistry""" if iface not in self._registry.keys(): self._registry[iface] = () self._registry[iface] += (name,) def unregister(self, iface, name): """See zope.app.workflow.interfacess.stateful.IContentProcessRegistry""" names = list(self._registry[iface]) names = filter(lambda n: n != name, names) if not names: del self._registry[iface] else: self._registry[iface] = tuple(names)
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/stateful/contentworkflow.py
contentworkflow.py
from persistent import Persistent from persistent.dict import PersistentDict from zope.app.workflow.interfaces import IProcessDefinition from zope.app.workflow.stateful.interfaces import AUTOMATIC from zope.app.workflow.stateful.interfaces import IAfterTransitionEvent from zope.app.workflow.stateful.interfaces import IBeforeTransitionEvent from zope.app.workflow.stateful.interfaces import IRelevantDataChangeEvent from zope.app.workflow.stateful.interfaces import IStatefulProcessInstance from zope.app.workflow.stateful.interfaces import ITransitionEvent from zope.app.workflow.stateful.interfaces import IBeforeRelevantDataChangeEvent from zope.app.workflow.stateful.interfaces import IAfterRelevantDataChangeEvent from zope.app.workflow.instance import ProcessInstance from zope.container.contained import Contained from zope.component import getUtility, getSiteManager from zope.event import notify from zope.traversing.api import getParent from zope.security.interfaces import Unauthorized from zope.interface import directlyProvides, implements from zope.proxy import removeAllProxies from zope.schema import getFields from zope.security.management import queryInteraction from zope.security.checker import CheckerPublic, Checker from zope.security.proxy import Proxy from zope.security import checkPermission from zope.tales.engine import Engine class TransitionEvent(object): """A simple implementation of the transition event.""" implements(ITransitionEvent) def __init__(self, object, process, transition): self.object = object self.process = process self.transition = transition class BeforeTransitionEvent(TransitionEvent): implements(IBeforeTransitionEvent) class AfterTransitionEvent(TransitionEvent): implements(IAfterTransitionEvent) class RelevantDataChangeEvent(object): """A simple implementation of the transition event.""" implements(IRelevantDataChangeEvent) def __init__(self, process, schema, attributeName, oldValue, newValue): self.process = process self.schema = schema self.attributeName = attributeName self.oldValue = oldValue self.newValue = newValue class BeforeRelevantDataChangeEvent(RelevantDataChangeEvent): implements(IBeforeRelevantDataChangeEvent) class AfterRelevantDataChangeEvent(RelevantDataChangeEvent): implements(IAfterRelevantDataChangeEvent) class RelevantData(Persistent, Contained): """The relevant data object can store data that is important to the workflow and fires events when this data is changed. If you don't understand this code, don't worry, it is heavy lifting. """ def __init__(self, schema=None, schemaPermissions=None): super(RelevantData, self).__init__() self.__schema = None # Add the new attributes, if there was a schema passed in if schema is not None: for name, field in getFields(schema).items(): setattr(self, name, field.default) self.__schema = schema directlyProvides(self, schema) # Build up a Checker rules and store it for later self.__checker_getattr = {} self.__checker_setattr = {} for name in getFields(schema): get_perm, set_perm = schemaPermissions.get(name, (None, None)) self.__checker_getattr[name] = get_perm or CheckerPublic self.__checker_setattr[name] = set_perm or CheckerPublic # Always permit our class's two public methods self.__checker_getattr['getChecker'] = CheckerPublic self.__checker_getattr['getSchema'] = CheckerPublic def __setattr__(self, key, value): # The '__schema' attribute has a sepcial function if key in ('_RelevantData__schema', '_RelevantData__checker_getattr', '_RelevantData__checker_setattr', 'getChecker', 'getSchema') or \ key.startswith('_p_'): return super(RelevantData, self).__setattr__(key, value) is_schema_field = (self.__schema is not None and key in getFields(self.__schema).keys()) if is_schema_field: process = self.__parent__ # Send an Event before RelevantData changes oldvalue = getattr(self, key, None) notify(BeforeRelevantDataChangeEvent( process, self.__schema, key, oldvalue, value)) super(RelevantData, self).__setattr__(key, value) if is_schema_field: # Send an Event after RelevantData has changed notify(AfterRelevantDataChangeEvent( process, self.__schema, key, oldvalue, value)) def getChecker(self): return Checker(self.__checker_getattr, self.__checker_setattr) def getSchema(self): return self.__schema class StateChangeInfo(object): """Immutable StateChangeInfo.""" def __init__(self, transition): self.__old_state = transition.sourceState self.__new_state = transition.destinationState old_state = property(lambda self: self.__old_state) new_state = property(lambda self: self.__new_state) class StatefulProcessInstance(ProcessInstance, Persistent): """Stateful Workflow ProcessInstance.""" implements(IStatefulProcessInstance) def getData(self): if self._data is None: return None # Always give out the data attribute as proxied object. return Proxy(self._data, self._data.getChecker()) data = property(getData) def initialize(self): """See zope.app.workflow.interfaces.IStatefulProcessInstance""" pd = self.getProcessDefinition() clean_pd = removeAllProxies(pd) self._status = clean_pd.getInitialStateName() # resolve schema class # This should really always return a schema schema = clean_pd.getRelevantDataSchema() if schema: # create relevant-data self._data = RelevantData(schema, clean_pd.schemaPermissions) else: self._data = None # setup permission on data # check for Automatic Transitions self._checkAndFireAuto(clean_pd) def getOutgoingTransitions(self): """See zope.app.workflow.interfaces.IStatefulProcessInstance""" pd = self.getProcessDefinition() clean_pd = removeAllProxies(pd) return self._outgoingTransitions(clean_pd) def fireTransition(self, id): """See zope.app.workflow.interfaces.IStatefulProcessInstance""" pd = self.getProcessDefinition() clean_pd = removeAllProxies(pd) if not id in self._outgoingTransitions(clean_pd): raise KeyError('Invalid Transition Id: %s' % id) transition = clean_pd.transitions[id] # Get the object whose status is being changed. obj = getParent(self) # Send an event before the transition occurs. notify(BeforeTransitionEvent(obj, self, transition)) # change status self._status = transition.destinationState # Send an event after the transition occurred. notify(AfterTransitionEvent(obj, self, transition)) # check for automatic transitions and fire them if necessary self._checkAndFireAuto(clean_pd) def getProcessDefinition(self): """Get the ProcessDefinition object from Workflow Utility.""" return getUtility(IProcessDefinition, self.processDefinitionName) def _getContext(self): ctx = {} # data should be readonly for condition-evaluation ctx['data'] = self.data ctx['principal'] = None interaction = queryInteraction() if interaction is not None: principals = [p.principal for p in interaction.participations] if principals: # There can be more than one principal assert len(principals) == 1 ctx['principal'] = principals[0] # TODO This needs to be discussed: # how can we know if this ProcessInstance is annotated # to a Content-Object and provide secure ***READONLY*** # Access to it for evaluating Transition Conditions ??? #content = self.__parent__ # TODO: How can i make sure that nobody modifies content # while the condition scripts/conditions are evaluated ???? # this hack only prevents from directly setting an attribute # using a setter-method directly is not protected :(( #try: # checker = getChecker(content) # checker.set_permissions = {} #except TypeError: # # got object without Security Proxy # checker = selectChecker(content) # checker.set_permissions = {} # content = Proxy(content, checker) #ctx['content'] = content return ctx def _extendContext(self, transition, ctx={}): ctx['state_change'] = StateChangeInfo(transition) return ctx def _evaluateCondition(self, transition, contexts): """Evaluate a condition in context of relevant-data.""" if not transition.condition: return True expr = Engine.compile(transition.condition) return expr(Engine.getContext(contexts=contexts)) def _evaluateScript(self, transition, contexts): """Evaluate a script in context of relevant-data.""" script = transition.script if not script: return True if isinstance(script, (str, unicode)): sm = getSiteManager(self) script = sm.resolve(script) return script(contexts) def _outgoingTransitions(self, clean_pd): ret = [] contexts = self._getContext() for name, trans in clean_pd.transitions.items(): if self.status == trans.sourceState: # check permissions permission = trans.permission if not checkPermission(permission, self): continue ctx = self._extendContext(trans, contexts) # evaluate conditions if trans.condition is not None: try: include = self._evaluateCondition(trans, ctx) except Unauthorized: include = 0 if not include: continue if trans.script is not None: try: include = self._evaluateScript(trans, ctx) except Unauthorized: include = 0 if not include: continue # append transition name ret.append(name) return ret def _checkAndFireAuto(self, clean_pd): outgoing_transitions = self.getOutgoingTransitions() for name in outgoing_transitions: trans = clean_pd.transitions[name] if trans.triggerMode == AUTOMATIC: self.fireTransition(name) return
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/stateful/instance.py
instance.py
import zope.component from zope.proxy import removeAllProxies from zope.schema import getFields, Choice from zope.publisher.browser import BrowserView from zope.security.checker import CheckerPublic from zope.security.proxy import removeSecurityProxy from zope.i18nmessageid import ZopeMessageFactory as _ from zope.app.container.browser.adding import Adding from zope.app.form.browser.submit import Update from zope.app.form.browser.editview import EditView from zope.app.form.interfaces import IInputWidget from zope.app.workflow.stateful.definition import State, Transition from zope.app.security.interfaces import IPermission from zope.app.form.utility import setUpWidget class StatesContainerAdding(Adding): """Custom adding view for StatesContainer objects.""" menu_id = "add_stateful_states" class TransitionsContainerAdding(Adding): """Custom adding view for TransitionsContainer objects.""" menu_id = "add_stateful_transitions" def getProcessDefinition(self): return self.context.getProcessDefinition() # TODO: Temporary ... class StateAddFormHelper(object): # Hack to prevent from displaying an empty addform def __call__(self, template_usage=u'', *args, **kw): if not len(self.fieldNames): self.request.form[Update] = 'submitted' return self.update() return super(StateAddFormHelper, self).__call__(template_usage, *args, **kw) class StatefulProcessDefinitionView(BrowserView): def getName(self): return """I'm a stateful ProcessInstance""" class RelevantDataSchemaEdit(EditView): def __init__(self, context, request): super(RelevantDataSchemaEdit, self).__init__(context, request) self.buildPermissionWidgets() def buildPermissionWidgets(self): schema = self.context.relevantDataSchema if schema is not None: for name, field in getFields(schema).items(): if self.context.schemaPermissions.has_key(name): get_perm, set_perm = self.context.schemaPermissions[name] try: get_perm_id = get_perm.id except: get_perm_id = None try: set_perm_id = set_perm.id except: set_perm_id = None else: get_perm_id, set_perm_id = None, None # Create the Accessor Permission Widget for this field permField = Choice( __name__=name + '_get_perm', title=_("Accessor Permission"), vocabulary="Permission Ids", default=CheckerPublic, required=False) setUpWidget(self, name + '_get_perm', permField, IInputWidget, value=get_perm_id) # Create the Mutator Permission Widget for this field permField = Choice( __name__=name + '_set_perm', title=_("Mutator Permission"), default=CheckerPublic, vocabulary="Permission Ids", required=False) setUpWidget(self, name + '_set_perm', permField, IInputWidget, value=set_perm_id) def update(self): status = '' if Update in self.request: status = super(RelevantDataSchemaEdit, self).update() self.buildPermissionWidgets() elif 'CHANGE' in self.request: schema = self.context.relevantDataSchema perms = removeSecurityProxy(self.context.schemaPermissions) for name, field in getFields(schema).items(): getPermWidget = getattr(self, name + '_get_perm_widget') setPermWidget = getattr(self, name + '_set_perm_widget') # get the selected permission id from the from request get_perm_id = getPermWidget.getInputValue() set_perm_id = setPermWidget.getInputValue() # get the right permission from the given id get_perm = zope.component.getUtility(IPermission, get_perm_id) set_perm = zope.component.getUtility(IPermission, set_perm_id) # set the permission back to the instance perms[name] = (get_perm, set_perm) # update widget ohterwise we see the old value getPermWidget.setRenderedValue(get_perm_id) setPermWidget.setRenderedValue(set_perm_id) status = _('Fields permissions mapping updated.') return status def getPermissionWidgets(self): schema = self.context.relevantDataSchema if schema is None: return None info = [] for name, field in getFields(schema).items(): field = removeSecurityProxy(field) info.append( {'fieldName': name, 'fieldTitle': field.title, 'getter': getattr(self, name + '_get_perm_widget'), 'setter': getattr(self, name + '_set_perm_widget')} ) return info class AddState(BrowserView): def action(self, id): state = State() self.context[id] = state return self.request.response.redirect(self.request.URL[-2]) class AddTransition(BrowserView): # TODO: This could and should be handled by a Vocabulary Field/Widget def getStateNames(self): pd = self.context.getProcessDefinition() states = removeAllProxies(pd.getStateNames()) states.sort() return states def action(self, id, source, destination, condition=None, permission=None): condition = condition or None permission = permission or None transition = Transition(source, destination, condition, permission) self.context[id] = transition return self.request.response.redirect(self.request.URL[-2])
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/stateful/browser/definition.py
definition.py
from zope.component import getUtilitiesFor from zope.component.interface import nameToInterface, interfaceToName from zope.interface import Interface from zope.publisher.browser import BrowserView from zope.schema import Choice, List from zope.security.proxy import removeSecurityProxy from zope.i18nmessageid import ZopeMessageFactory as _ from zope.app.form.utility import setUpWidgets from zope.app.form.interfaces import IInputWidget from zope.app.workflow.interfaces import IProcessDefinition class IContentProcessMapping(Interface): iface = List( title = _("Content Type Interface"), description = _("Specifies the interfaces that characterizes " "a particular content type. Feel free to select several at once."), required = True, value_type = Choice(vocabulary = "Content Types") ) name = List( title = _("Process Definition Name"), description = _("The name of the process that will be available for " "this content type. Feel free to select several at once."), required = True, value_type = Choice(vocabulary = "ProcessDefinitions") ) class ManageContentProcessRegistry(BrowserView): def __init__(self, *args): super(ManageContentProcessRegistry, self).__init__(*args) setUpWidgets(self, IContentProcessMapping, IInputWidget) self.process_based = int(self.request.get('process_based', '1')) def getProcessInterfacesMapping(self): mapping = [] for name in [name for name, util in getUtilitiesFor( IProcessDefinition, self.context, )]: ifaces = self.context.getInterfacesForProcessName(name) ifaces = map(lambda i: interfaceToName(self.context, i), ifaces) if ifaces: mapping.append({'name': name, 'ifaces': ifaces}) return mapping def getInterfaceProcessesMapping(self): mapping = [] # Nothing bad here; we just read the registry data registry = removeSecurityProxy(self.context)._registry for iface, names in registry.items(): mapping.append({'iface': interfaceToName(self.context, iface), 'names': names}) return mapping def update(self): status = '' if 'ADD' in self.request: for name in self.name_widget.getInputValue(): for iface in self.iface_widget.getInputValue(): self.context.register(iface, name) status = _('Mapping(s) added.') elif 'REMOVE' in self.request: mappings = self.request.get('mappings', []) for entry in mappings: split = entry.rfind(':') name = entry[:split] iface = nameToInterface(self.context, entry[split+1:]) self.context.unregister(iface, name) status = _('Mapping(s) removed.') elif 'SWITCH' in self.request: self.request.response.setCookie('process_based', self.request.get('other_view')) self.process_based = int(self.request.get('other_view')) return status
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/stateful/browser/contentworkflow.py
contentworkflow.py
from zope.component import getUtility from zope.proxy import removeAllProxies from zope.security.proxy import removeSecurityProxy from zope.schema import getFields from zope.publisher.browser import BrowserView from zope.dublincore.interfaces import IZopeDublinCore from zope.app.form.browser.submit import Update from zope.app.form.utility import setUpWidget, applyWidgetsChanges from zope.app.form.interfaces import IInputWidget from zope.i18nmessageid import ZopeMessageFactory as _ from zope.app.workflow.interfaces import IProcessDefinition from zope.app.workflow.interfaces import IProcessInstanceContainer from zope.app.workflow.interfaces import IProcessInstanceContainerAdaptable class ManagementView(BrowserView): __used_for__ = IProcessInstanceContainerAdaptable def __init__(self, context, request): super(ManagementView, self).__init__(context, request) workflow = self._getSelWorkflow() # Workflow might be None if workflow is None or workflow.data is None: return schema = workflow.data.getSchema() for name, field in getFields(schema).items(): # setUpWidget() does not mutate the field, so it is ok. field = removeSecurityProxy(field) setUpWidget(self, name, field, IInputWidget, value=getattr(workflow.data, name)) def _extractContentInfo(self, item): id, processInstance = item info = {} info['id'] = id info['name'] = self._getTitle( self._getProcessDefinition(processInstance)) return info def listContentInfo(self): return map(self._extractContentInfo, IProcessInstanceContainer(self.context).items()) def getWorkflowTitle(self): pi = self._getSelWorkflow() if pi is None: return None return self._getTitle(self._getProcessDefinition(pi)) def getTransitions(self): info = {} pi = self._getSelWorkflow() if pi is None: return info pd = self._getProcessDefinition(pi) clean_pd = removeAllProxies(pd) current_state = clean_pd.getState(pi.status) adapter = IZopeDublinCore(current_state) info['status'] = adapter.title or pi.status transition_names = pi.getOutgoingTransitions() trans_info = [] for name in transition_names: transition = clean_pd.getTransition(name) adapter = IZopeDublinCore(transition) trans_info.append({'name':name, 'title': adapter.title or name}) info['transitions'] = trans_info return info def fireTransition(self): pi = self._getSelWorkflow() if pi is None: return trans = self.request.get('selTransition', None) self.request.response.redirect('@@workflows.html?workflow=%s' % pi.processDefinitionName) if pi and trans: pi.fireTransition(trans) def _getTitle(self, obj): return (IZopeDublinCore(obj).title or obj.__name___) def _getSelWorkflow(self): reqWorkflow = self.request.get('workflow', u'') pi_container = IProcessInstanceContainer(self.context) if reqWorkflow is u'': available_instances = pi_container.keys() if len(available_instances) > 0: pi = pi_container[available_instances[0]] else: pi = None else: pi = pi_container[reqWorkflow] return pi def _getProcessDefinition(self, processInstance): return getUtility(IProcessDefinition, processInstance.processDefinitionName) def widgets(self): workflow = self._getSelWorkflow() # Workflow might be None if workflow is None or workflow.data is None: return [] schema = self._getSelWorkflow().data.getSchema() return [getattr(self, name+'_widget') for name in getFields(schema).keys()] def update(self): status = '' workflow = self._getSelWorkflow() # Workflow might be None if Update in self.request and (workflow is not None and workflow.data is not None): schema = removeSecurityProxy(workflow.data.getSchema()) changed = applyWidgetsChanges(self, schema, target=workflow.data, names=getFields(schema).keys()) if changed: status = _('Updated Workflow Data.') return status
zope.app.workflow
/zope.app.workflow-3.5.0.tar.gz/zope.app.workflow-3.5.0/src/zope/app/workflow/stateful/browser/instance.py
instance.py
===================== Zope WSGI Application ===================== This package contains an interpretation of the WSGI specification (PEP-0333) for the Zope application server by providing a WSGI application object. The first step is to initialize the WSGI-compliant Zope application that is called from the server. To do that, we first have to create and open a ZODB connection: >>> from ZODB.MappingStorage import MappingStorage >>> from ZODB.DB import DB >>> storage = MappingStorage('test.db') >>> db = DB(storage, cache_size=4000) We can now initialize the application: >>> from zope.app import wsgi >>> app = wsgi.WSGIPublisherApplication(db) The callable ``app`` object accepts two positional arguments, the environment and the function that initializes the response and returns a function with which the output data can be written. Even though this is commonly done by the server, we now have to create an appropriate environment for the request. >>> import io >>> environ = { ... 'PATH_INFO': '/', ... 'wsgi.input': io.BytesIO(b'')} Next we create a WSGI-compliant ``start_response()`` method that accepts the status of the response to the HTTP request and the headers that are part of the response stream. The headers are expected to be a list of 2-tuples. The ``start_response()`` method must also return a ``write()`` function that directly writes the output to the server. However, the Zope 3 implementation will not utilize this function, since it is strongly discouraged by PEP-0333. The second method of getting data to the server is by returning an iteratable from the application call. Sp we simply ignore all the arguments and return ``None`` as the write method. >>> def start_response(status, headers): ... return None Now we can send the fabricated HTTP request to the application for processing: >>> print(b''.join(app(environ, start_response)).decode('utf-8')) <html><head><title>SystemError</title></head> <body><h2>SystemError</h2> A server error occurred. </body></html> <BLANKLINE> We can see that application really crashed and did not know what to do. This is okay, since we have not setup anything. Getting a request successfully processed would require us to bring up a lot of Zope 3's system, which would be just a little bit too much for this demonstration. Now that we have seen the manual way of initializing and using the publisher application, here is the way it is done using all of Zope 3's setup machinery:: from zope.app.server.main import setup, load_options from zope.app.wsgi import PublisherApp # Read all configuration files and bring up the component architecture args = ["-C/path/to/zope.conf"] db = setup(load_options(args)) # Initialize the WSGI-compliant publisher application with the database wsgiApplication = PublisherApp(db) # Here is an example on how the application could be registered with a # WSGI-compliant server. Note that the ``setApplication()`` method is not # part of the PEP 333 specification. wsgiServer.setApplication(wsgiApplication) The code above assumes, that Zope is available on the ``PYTHONPATH``. Note that you may have to edit ``zope.conf`` to provide an absolute path for ``site.zcml``. Unfortunately we do not have enough information about the directory structure to make this code a doctest. In summary, to use Zope as a WSGI application, the following steps must be taken: * configure and setup Zope * an instance of ``zope.app.wsgi.PublisherApp`` must be created with a refernce to the opened database * this application instance must be somehow communicated to the WSGI server, i.e. by calling a method on the server that sets the application. Access logging -------------- But let's test at least the user info logging feature. We can check the environ after being sent to the app and also see that a key has been set to store user names for use in access logs. This logging information is provided by an adapter registered for `ILoggingInfo`. Out-of-the-box, `zope.publisher` registers a base adapter that returns the principal id as value:: >>> from pprint import pprint >>> pprint(environ) {'PATH_INFO': '/', 'REMOTE_USER': '...fallback_unauthenticated_principal', 'wsgi.input': <...BytesIO object at ...>, 'wsgi.logging_info': '...fallback_unauthenticated_principal'} .. edge case If remote user is already set, don't update it: >>> environ = { ... 'PATH_INFO': '/', ... 'REMOTE_USER': 'someoneelse', ... 'wsgi.input': io.BytesIO(b'')} >>> _ = list(app(environ, start_response)) >>> pprint(environ) {'PATH_INFO': '/', 'REMOTE_USER': 'someoneelse', 'wsgi.input': <...BytesIO object at ...>, 'wsgi.logging_info': '...fallback_unauthenticated_principal'} Creating A WSGI Application --------------------------- We do not always want Zope to control the startup process. People want to be able to start their favorite server and then register Zope simply as a WSGI application. For those cases we provide a very high-level function called ``getWSGIApplication()`` that only requires the configuration file to set up the Zope 3 application server and returns a WSGI application. Here is a simple example: # We have to create our own site definition file -- which will simply be # empty -- to provide a minimal test. >>> import os, tempfile >>> temp_dir = tempfile.mkdtemp() >>> sitezcml = os.path.join(temp_dir, 'site.zcml') >>> with open(sitezcml, 'w') as f: ... _ = f.write('<configure />') >>> configFile = io.StringIO(u''' ... site-definition %s ... ... <zodb> ... <mappingstorage /> ... </zodb> ... ... <eventlog> ... <logfile> ... path STDOUT ... </logfile> ... </eventlog> ... ... <product-config sample> ... key1 val1 ... </product-config> ... ''' %sitezcml) Create an handler for the event. >>> import zope.component >>> from zope.app.wsgi.interfaces import IWSGIPublisherApplicationCreatedEvent >>> called = [] >>> @zope.component.adapter(IWSGIPublisherApplicationCreatedEvent) ... def handler(event): ... called.append(event) >>> zope.component.provideHandler(handler) Create an WSGI application. >>> app = wsgi.getWSGIApplication(configFile) >>> app <zope.app.wsgi.WSGIPublisherApplication object at ...> >>> called[0].application is app True The product configs were parsed: >>> import zope.app.appsetup.product as zapp >>> print(zapp.getProductConfiguration('sample')) {'key1': 'val1'} >>> import shutil >>> shutil.rmtree(temp_dir) About WSGI ---------- WSGI is the Python Web Server Gateway Interface, a PEP to standardize the interface between web servers and python applications to promote portability. For more information, refer to the WSGI specification: http://www.python.org/peps/pep-0333.html
zope.app.wsgi
/zope.app.wsgi-5.0-py3-none-any.whl/zope/app/wsgi/README.txt
README.txt
"""IResult adapters for files.""" import io import tempfile import zope.publisher.http import zope.publisher.interfaces.http from zope.publisher.interfaces.http import IResult from zope.security.proxy import removeSecurityProxy from zope import component from zope import interface @interface.implementer(IResult) class FallbackWrapper: def __init__(self, f): self.close = f.close self._file = f def __iter__(self): f = self._file while True: v = f.read(32768) if v: yield v else: break @component.adapter(io._io._IOBase, zope.publisher.interfaces.http.IHTTPRequest) @interface.implementer(zope.publisher.http.IResult) def FileResult(f, request): f = removeSecurityProxy(f) if request.response.getHeader('content-length') is None: f.seek(0, 2) size = f.tell() f.seek(0) request.response.setHeader('Content-Length', str(size)) wrapper = request.environment.get('wsgi.file_wrapper') if wrapper is not None: f = wrapper(f) else: f = FallbackWrapper(f) return f # We need to provide an adapter for temporary files *if* they are different # than regular files. Whether they are is system dependent. Sigh. # If temporary files are the same type, we'll create a fake type just # to make the registration work. _tfile = tempfile.TemporaryFile() _tfile.close() _tfile = _tfile.__class__ if issubclass(_tfile, io._io._IOBase): # need a fake one. Sigh class _tfile: pass @component.adapter(_tfile, zope.publisher.interfaces.http.IHTTPRequest) @interface.implementer(zope.publisher.http.IResult) def TemporaryFileResult(f, request): return FileResult(f, request) @component.adapter(io.BufferedReader, zope.publisher.interfaces.http.IHTTPRequest) @interface.implementer(zope.publisher.http.IResult) def BufferedReaderFileResult(f, request): return FileResult(f, request) @component.adapter(io.TextIOWrapper, zope.publisher.interfaces.http.IHTTPRequest) @interface.implementer(zope.publisher.http.IResult) def TextIOWrapperFileResult(f, request): return FileResult(f, request) @component.adapter(io.BufferedRandom, zope.publisher.interfaces.http.IHTTPRequest) @interface.implementer(zope.publisher.http.IResult) def BufferedRandomFileResult(f, request): return FileResult(f, request)
zope.app.wsgi
/zope.app.wsgi-5.0-py3-none-any.whl/zope/app/wsgi/fileresult.py
fileresult.py
import logging import os import sys import ZConfig import zope.app.appsetup.product import zope.processlifetime from zope.app.appsetup import appsetup from zope.app.publication.httpfactory import HTTPPublicationRequestFactory from zope.event import notify from zope.interface import implementer from zope.publisher.interfaces.logginginfo import ILoggingInfo from zope.publisher.publish import publish from zope.app.wsgi import interfaces @implementer(interfaces.IWSGIApplication) class WSGIPublisherApplication: """A WSGI application implementation for the zope publisher Instances of this class can be used as a WSGI application object. The class relies on a properly initialized request factory. """ def __init__(self, db=None, factory=HTTPPublicationRequestFactory, handle_errors=True): self.requestFactory = None self.handleErrors = handle_errors if db is None: db = object() self.requestFactory = factory(db) def __call__(self, environ, start_response): """See zope.app.wsgi.interfaces.IWSGIApplication""" request = self.requestFactory(environ['wsgi.input'], environ) # Let's support post-mortem debugging handle_errors = environ.get('wsgi.handleErrors', self.handleErrors) request = publish(request, handle_errors=handle_errors) response = request.response # Get logging info from principal for log use logging_info = ILoggingInfo(request.principal, None) if logging_info is None: message = b'-' else: message = logging_info.getLogMessage() message = message.decode('latin1') environ['wsgi.logging_info'] = message if 'REMOTE_USER' not in environ: environ['REMOTE_USER'] = message # Start the WSGI server response start_response(response.getStatusString(), response.getHeaders()) # Return the result body iterable. return response.consumeBodyIter() class PMDBWSGIPublisherApplication(WSGIPublisherApplication): def __init__(self, db=None, factory=HTTPPublicationRequestFactory, handle_errors=False): super().__init__(db, factory, handle_errors) def __call__(self, environ, start_response): environ['wsgi.handleErrors'] = self.handleErrors # Call the application to handle the request and write a response try: app = super() return app.__call__(environ, start_response) except Exception: import pdb import sys print("%s:" % sys.exc_info()[0]) print(sys.exc_info()[1]) try: pdb.post_mortem(sys.exc_info()[2]) raise finally: pass def config(configfile, schemafile=None, features=()): # Load the configuration schema if schemafile is None: schemafile = os.path.join( os.path.dirname(appsetup.__file__), 'schema', 'schema.xml') # Let's support both, an opened file and path if isinstance(schemafile, (str, bytes)): schema = ZConfig.loadSchema(schemafile) else: schema = ZConfig.loadSchemaFile(schemafile) # Load the configuration file # Let's support both, an opened file and path try: if isinstance(configfile, (str, bytes)): options, handlers = ZConfig.loadConfig(schema, configfile) else: options, handlers = ZConfig.loadConfigFile(schema, configfile) except ZConfig.ConfigurationError as msg: sys.stderr.write("Error: %s\n" % str(msg)) sys.exit(2) # Insert all specified Python paths if options.path: sys.path[:0] = [os.path.abspath(p) for p in options.path] # Parse product configs zope.app.appsetup.product.setProductConfigurations( options.product_config) # Setup the event log options.eventlog() # Setup other defined loggers for logger in options.loggers: logger() # Insert the devmode feature, if turned on if options.devmode: features += ('devmode',) logging.warning( "Developer mode is enabled: this is a security risk " "and should NOT be enabled on production servers. Developer mode " "can usually be turned off by setting the `devmode` option to " "`off` or by removing it from the instance configuration file " "completely.") # Execute the ZCML configuration. appsetup.config(options.site_definition, features=features) # Connect to and open the database, notify subscribers. db = appsetup.multi_database(options.databases)[0][0] notify(zope.processlifetime.DatabaseOpened(db)) return db def getWSGIApplication(configfile, schemafile=None, features=(), requestFactory=HTTPPublicationRequestFactory, handle_errors=True): db = config(configfile, schemafile, features) application = WSGIPublisherApplication(db, requestFactory, handle_errors) # Create the application, notify subscribers. notify(interfaces.WSGIPublisherApplicationCreated(application)) return application
zope.app.wsgi
/zope.app.wsgi-5.0-py3-none-any.whl/zope/app/wsgi/__init__.py
__init__.py
__docformat__ = 'restructuredtext' import types import inspect from zope.interface import providedBy from zope.publisher.interfaces.xmlrpc import IXMLRPCRequest from zope.component import getGlobalSiteManager def getViews(ifaces): """Get all view registrations for methods""" gsm = getGlobalSiteManager() for reg in gsm.registeredAdapters(): if (len(reg.required) > 0 and reg.required[-1] is not None and reg.required[-1].isOrExtends(IXMLRPCRequest)): for required_iface in reg.required[:-1]: if required_iface is not None: for iface in ifaces: if iface.isOrExtends(required_iface): yield reg def xmlrpccallable(return_type, *parameters_types): def wrapper(func): # adding info on the function object func.return_type = return_type func.parameters_types = parameters_types return func return wrapper class XMLRPCIntrospection(object): def listMethods(self): """ lists all methods available """ return self._getXMLRPCMethods() def methodSignature(self, method_name): """ returns the method signature """ return self._getXMLRPCMethodSignature(method_name) def methodHelp(self, method_name): """ returns the docstring of the method """ return self._getXMLRPCMethodHelp(method_name) def __call__(self, *args, **kw): return self.listMethods() # # Introspection APIS # _reserved_method_names = (u'', u'listMethods', u'methodHelp', u'methodSignature') def _filterXMLRPCRequestRegistrations(self, registrations): # TODO might be outsourced to some utility for registration in registrations: for required_iface in registration.required: if (required_iface is IXMLRPCRequest and registration.name.strip() not in self._reserved_method_names): yield registration def _getRegistrationAdapters(self, interfaces): # TODO might be outsourced to some utility registrations = list(getViews(interfaces)) filtered_adapters = list( self._filterXMLRPCRequestRegistrations(registrations)) return filtered_adapters def _getFunctionArgumentSize(self, func): args, varargs, varkw, defaults = inspect.getargspec(func) num_params = len(args) - 1 if varargs is not None: num_params += len(varargs) if varkw is not None: num_params += len(varkw) return num_params def _getFunctionSignature(self, func): """Return the signature of a function or method.""" if not isinstance(func, (types.FunctionType, types.MethodType)): raise TypeError("func must be a function or method") # see if the function has been decorated if hasattr(func, 'return_type') and hasattr(func, 'parameters_types'): signature = [func.return_type] + list(func.parameters_types) # we want to return the type name as string # to avoid marshall problems str_signature = [] for element in signature: if element is None or not hasattr(element, '__name__'): str_signature.append('undef') else: str_signature.append(element.__name__) return [str_signature] # no decorator, let's just return Nones # TODO if defaults are given, render their type return [['undef'] * (self._getFunctionArgumentSize(func) + 1)] def _getFunctionHelp(self, func): if hasattr(func, '__doc__') and func.__doc__ is not None: if func.__doc__.strip() != '': return func.__doc__ return 'undef' # # Lookup APIS # def _getXMLRPCMethods(self): adapter_registrations = [] interfaces = list(providedBy(self.context)) for result in self._getRegistrationAdapters(interfaces): if result.name not in adapter_registrations: adapter_registrations.append(result.name) adapter_registrations.sort() return adapter_registrations def _getXMLRPCMethodSignature(self, method_name): """ The signature of a method is an array of signatures (if the method returns multiple signatures) and each array contains the return type then the parameters types: [[return type, param1 type, param2 type, ...], [...], ...] """ interfaces = list(providedBy(self.context)) for result in self._getRegistrationAdapters(interfaces): if result.name == method_name: method = getattr(result.factory, method_name) return self._getFunctionSignature(method) return 'undef' def _getXMLRPCMethodHelp(self, method_name): """ The help of a method is just the doctstring, if given """ interfaces = list(providedBy(self.context)) for result in self._getRegistrationAdapters(interfaces): if result.name == method_name: method = getattr(result.factory, method_name) return self._getFunctionHelp(method) return 'undef'
zope.app.xmlrpcintrospection
/zope.app.xmlrpcintrospection-3.5.1.tar.gz/zope.app.xmlrpcintrospection-3.5.1/src/zope/app/xmlrpcintrospection/xmlrpcintrospection.py
xmlrpcintrospection.py
==================== XMLRPC Introspection ==================== What's introspection now ? -------------------------- This Zope 3 package provides an xmlrpcintrospection mechanism, as defined here: http://xmlrpc-c.sourceforge.net/xmlrpc-howto/xmlrpc-howto-api-introspection.html It registers three new xmlrpc methods: - `listMethods()`: Lists all xmlrpc methods (ie views) registered for the current object - `methodHelp(method_name)`: Returns the method documentation of the given method. - `methodSignature(method_name)`: Returns the method documentation of the given method. How do I use it ? ----------------- Basically, if you want to add introspection into your XMLRPCView, you just have to add a decorator for each method of the view, that specifies the return type of the method and the argument types. The decorator is called `xmlrpccallable` >>> from zope.app.xmlrpcintrospection.xmlrpcintrospection import xmlrpccallable >>> from zope.app.publisher.xmlrpc import XMLRPCView >>> class MySuperXMLRPCView(XMLRPCView): ... @xmlrpccallable(str, str, str, str) ... def myMethod(self, a, b, c): ... """ my help """ ... return '%s %s, %s, lalalala, you and me, lalalala' % (a, b, c) `myMethod()` will then be introspectable. (find a full examples below, grep for (*)) How does it works ? ------------------- It is based on introspection mechanisms provided by the apidoc package. ***** ripped form xmlrpc doctests ***** Let's write a view that returns a folder listing: >>> class FolderListing: ... def contents(self): ... return list(self.context.keys()) Now we'll register it as a view: >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... ... <xmlrpc:view ... for="zope.site.interfaces.IFolder" ... methods="contents" ... class="zope.app.xmlrpcintrospection.README.FolderListing" ... permission="zope.ManageContent" ... /> ... </configure> ... """) Now, we'll add some items to the root folder: >>> print http(r""" ... POST /@@contents.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 73 ... Content-Type: application/x-www-form-urlencoded ... ... type_name=BrowserAdd__zope.site.folder.Folder&new_value=f1""") HTTP/1.1 303 See Other ... >>> print http(r""" ... POST /@@contents.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 73 ... Content-Type: application/x-www-form-urlencoded ... ... type_name=BrowserAdd__zope.site.folder.Folder&new_value=f2""") HTTP/1.1 303 See Other ... And call our xmlrpc method: >>> print http(r""" ... POST / HTTP/1.0 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 102 ... Content-Type: text/xml ... ... <?xml version='1.0'?> ... <methodCall> ... <methodName>contents</methodName> ... <params> ... </params> ... </methodCall> ... """) HTTP/1.0 200 OK ... <?xml version='1.0'?> <methodResponse> <params> <param> <value><array><data> <value><string>f1</string></value> <value><string>f2</string></value> </data></array></value> </param> </params> </methodResponse> <BLANKLINE> ***** end of ripped form xmlrpc doctests ***** Now we want to provide to that view introspection. Let's add three new xmlrcp methods, that published the introspection api. >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... <xmlrpc:view ... for="zope.interface.Interface" ... methods="listMethods methodHelp methodSignature" ... class="zope.app.xmlrpcintrospection.xmlrpcintrospection.XMLRPCIntrospection" ... permission="zope.Public" ... /> ... </configure> ... """) They are linked to XMLRPCIntrospection class, that actually knows how to lookup to all interfaces And call our xmlrpc method, that should list the content method: >>> print http(r""" ... POST / HTTP/1.0 ... Content-Type: text/xml ... ... <?xml version='1.0'?> ... <methodCall> ... <methodName>listMethods</methodName> ... <params> ... </params> ... </methodCall> ... """, handle_errors=False) HTTP/1.0 200 OK ... <?xml version='1.0'?> <methodResponse> ... <value><string>contents</string></value> ... </methodResponse> <BLANKLINE> Let's try to add another method, to se if it gets listed... >>> class FolderListing2: ... def contents2(self): ... return list(self.context.keys()) >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... ... <xmlrpc:view ... for="zope.site.interfaces.IFolder" ... methods="contents2" ... class="zope.app.xmlrpcintrospection.README.FolderListing2" ... permission="zope.ManageContent" ... /> ... </configure> ... """) >>> print http(r""" ... POST / HTTP/1.0 ... Content-Type: text/xml ... ... <?xml version='1.0'?> ... <methodCall> ... <methodName>listMethods</methodName> ... <params> ... </params> ... </methodCall> ... """, handle_errors=False) HTTP/1.0 200 OK ... <?xml version='1.0'?> <methodResponse> ... <value><string>contents</string></value> <value><string>contents2</string></value> ... </methodResponse> <BLANKLINE> No we want to test methodHelp and methodSignature, to check that it returns, - The method doc - The list of attributes In RPC, the list of attributes has to be return in an array of type: [return type, param1 type, param2 type] Since in Python we cannot have a static type for the method return type, we introduce here a new mechanism based on a decorator, that let the xmlrpcview developer add his own signature. If the signature is not given, a defaut list is returned: [None, None, None...] The decorator append to the function objet two new parameters, to get back the signature. >>> from zope.app.xmlrpcintrospection.xmlrpcintrospection import xmlrpccallable >>> class JacksonFiveRPC: ... @xmlrpccallable(str, str, str, str) ... def says(self, a, b, c): ... return '%s %s, %s, lalalala, you and me, lalalala' % (a, b, c) Let's try to get back the signature: >>> JacksonFiveRPC().says.return_type <type 'str'> >>> JacksonFiveRPC().says.parameters_types (<type 'str'>, <type 'str'>, <type 'str'>) The method is still callable as needed: >>> JacksonFiveRPC().says('a', 'b', 'c') 'a b, c, lalalala, you and me, lalalala' Let's try out decorated and not decorated methods signatures (*): >>> class JacksonFiveRPC: ... @xmlrpccallable(str, str, str, str) ... def says(self, a, b, c): ... return '%s %s, %s, lalalala, you and me, lalalala' % (a, b, c) ... def says_not_decorated(self, a, b, c): ... return '%s %s, %s, lalalala, you and me, lalalala' % (a, b, c) >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... ... <xmlrpc:view ... for="zope.site.folder.IFolder" ... methods="says says_not_decorated" ... class="zope.app.xmlrpcintrospection.README.JacksonFiveRPC" ... permission="zope.ManageContent" ... /> ... </configure> ... """) Now let's try to get the signature for `says()`: >>> print http(r""" ... POST / HTTP/1.0 ... Content-Type: text/xml ... ... <?xml version='1.0'?> ... <methodCall> ... <methodName>methodSignature</methodName> ... <params> ... <param> ... <value>says</value> ... </param> ... </params> ... </methodCall> ... """, handle_errors=False) HTTP/1.0 200 OK ... <?xml version='1.0'?> <methodResponse> <params> <param> <value><array><data> <value><array><data> <value><string>str</string></value> <value><string>str</string></value> <value><string>str</string></value> <value><string>str</string></value> </data></array></value> </data></array></value> </param> </params> </methodResponse> <BLANKLINE> Now let's try to get the signature for says_not_decorated()`: >>> print http(r""" ... POST / HTTP/1.0 ... Content-Type: text/xml ... ... <?xml version='1.0'?> ... <methodCall> ... <methodName>methodSignature</methodName> ... <params> ... <param> ... <value>says_not_decorated</value> ... </param> ... </params> ... </methodCall> ... """, handle_errors=False) HTTP/1.0 200 OK ... <?xml version='1.0'?> <methodResponse> <params> <param> <value><array><data> <value><array><data> <value><string>undef</string></value> <value><string>undef</string></value> <value><string>undef</string></value> <value><string>undef</string></value> </data></array></value> </data></array></value> </param> </params> </methodResponse> <BLANKLINE> Last, but not least, the method help: >>> class JacksonFiveRPCDocumented: ... @xmlrpccallable(str, str, str, str) ... def says(self, a, b, c): ... """ this is the help for ... says() ... """ ... return '%s %s, %s, lalalala, you and me, lalalala' % (a, b, c) ... def says_not_documented(self, a, b, c): ... return '%s %s, %s, lalalala, you and me, lalalala' % (a, b, c) >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... ... <xmlrpc:view ... for="zope.site.folder.IFolder" ... methods="says says_not_documented" ... class="zope.app.xmlrpcintrospection.README.JacksonFiveRPCDocumented" ... permission="zope.ManageContent" ... /> ... </configure> ... """) >>> print http(r""" ... POST / HTTP/1.0 ... Content-Type: text/xml ... ... <?xml version='1.0'?> ... <methodCall> ... <methodName>methodHelp</methodName> ... <params> ... <param> ... <value>says</value> ... </param> ... </params> ... </methodCall> ... """, handle_errors=False) HTTP/1.0 200 OK ... <?xml version='1.0'?> <methodResponse> <params> <param> <value><string> this is the help for says() </string></value> </param> </params> </methodResponse> <BLANKLINE> >>> print http(r""" ... POST / HTTP/1.0 ... Content-Type: text/xml ... ... <?xml version='1.0'?> ... <methodCall> ... <methodName>methodHelp</methodName> ... <params> ... <param> ... <value>says_not_documented</value> ... </param> ... </params> ... </methodCall> ... """, handle_errors=False) HTTP/1.0 200 OK ... <?xml version='1.0'?> <methodResponse> <params> <param> <value><string>undef</string></value> </param> </params> </methodResponse> <BLANKLINE>
zope.app.xmlrpcintrospection
/zope.app.xmlrpcintrospection-3.5.1.tar.gz/zope.app.xmlrpcintrospection-3.5.1/src/zope/app/xmlrpcintrospection/README.txt
README.txt
Zope Application Programming Interface ====================================== This package provides a collection of commonly used APIs to make imports simpler. Mostly, the APIs provided here are imported from elsewhere. A few are provided here. principals() ------------ The principals method returns the authentication service. If no service is defined, a ComponentLookupError is raised: >>> from zope.app import zapi >>> zapi.principals() #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ComponentLookupError: (<InterfaceClass zope.authentication.interfaces.IAuthentication>, '') But if we provide an authentication service: >>> import zope.interface >>> from zope.authentication.interfaces import IAuthentication >>> class FakeAuthenticationUtility: ... zope.interface.implements(IAuthentication) >>> fake = FakeAuthenticationUtility() >>> from zope.app.testing import ztapi >>> ztapi.provideUtility(IAuthentication, fake) Then we should be able to get the service back when we ask for the principals: >>> zapi.principals() is fake True
zope.app.zapi
/zope.app.zapi-3.5.0.tar.gz/zope.app.zapi-3.5.0/src/zope/app/zapi/README.txt
README.txt
Change History ============== 5.0 (2023-07-10) ---------------- - Add support for Python 3.11. - Drop support for Python 2.7, 3.5, 3.6. 4.1.0 (2022-08-23) ------------------ - Add support for Python 3.7, 3.8, 3.9, 3.10. - Drop support for Python 3.4. 4.0.0 (2017-05-29) ------------------ - Add support for Python 3.4, 3.5, 3.6 and PyPy. Update minimum dependency versions appropriately. 3.8.0 (2013-08-27) ------------------ - Remove include of ``zope.app.zopeappgenerations`` that is not useful unless upgrading a database older than Zope 3.4. This cuts the last dependency on ``zope.app.authentication`` from the ZTK. 3.7.1 (2011-07-26) ------------------ - Move include of ``zope.dublincore.browser`` here from ``zope.dublincore`` (LP: #590668). 3.7.0 (2009-12-28) ------------------ - Use new ``zope.app.locales`` which has its own `configure.zcml`. - No longer using ``zope.testing.doctestunit`` as it is deprecated now. Using python's ``doctest`` module. 3.6.1 (2009-12-16) ------------------ - Removed reference to no longer existing configure.zcml from ``zope.app.pagetemplate.tests``. 3.6.0 (2009-07-11) ------------------ - No longer depends on deprecated ``zope.app.interface`` but on ``zope.componentvocabulary``. 3.5.5 (2009-05-23) ------------------ - Added missing dependencies, including ``zope.app.http`` and ``zope.app.applicationcontrol``. 3.5.4 (2009-05-18) ------------------ - Added missing ``zope.app.exception`` dependency, as we include its ZCML. - Added missing ``zope.app.testing`` test dependency to make tests pass. 3.5.3 (2009-02-04) ------------------ - Added ``zope.app.broken`` dependency (we include its ZCML). 3.5.2 (2009-01-31) ------------------ - We depended on ``zope.formlib`` but didn't include its configuration. Now it's included in ``configure.zcml``. - We include ZCML of ``zope.app.error`` but didn't mention it as a dependency. 3.5.1 (2008-12-28) ------------------ - Add include of ``zope.app.schema:configure.zcml``. Because component-based vocabularies are used everywhere and we need to import zope.app.schema somehow to make it work. This is needed because of removal of the include of zope.app.schema's meta.zcml in the previous release. 3.5.0 (2008-12-16) ------------------ - Remove deprecated include of ``zope.app.component.browser:meta.zcml``. - Remove deprecated include of ``zope.app.schema:meta.zcml``. - Remove use of zope.modulealias. 3.4.3 (2007-11-01) ------------------ - Fix test failure due to missing ``zope.app.container.browser.ftests`` directory. Now it is moved to ``zope.app.container.browser.tests``. 3.4.2 (2007-10-30) ------------------ - Fix test failure due to missing ``zope.app.form.browser.ftests`` directory. Now it is moved to ``zope.app.form.browser.tests``. 3.4.1 (2007-10-23) ------------------ - Added missing dependency. 3.4.0 (2007-10-03) ------------------ - Initial public release as an individual package.
zope.app.zcmlfiles
/zope.app.zcmlfiles-5.0.tar.gz/zope.app.zcmlfiles-5.0/CHANGES.rst
CHANGES.rst
__docformat__ = "reStructuredText" import zope.app.authentication.interfaces from zope.app.authentication import groupfolder from zope.app.component.interfaces import ISite from zope.component import getUtilitiesFor from zope.copypastemove.interfaces import IObjectMover from zope.generations.utility import findObjectsProviding, getRootFolder generation = 3 def evolve(context): """Evolve existing PAUs and group folders. - Group folders should no longer be registered. - PAUs that use group folders should use their contents name, not their (formerly) registered name. Group folders used by multiple PAUs were not supported, and are not supported with this evolution. """ root = getRootFolder(context) for site in findObjectsProviding(root, ISite): sm = site.getSiteManager() for pau in findObjectsProviding( sm, zope.app.authentication.interfaces.IPluggableAuthentication): for nm, util in getUtilitiesFor( zope.app.authentication.interfaces.IAuthenticatorPlugin, context=pau): if groupfolder.IGroupFolder.providedBy(util): if util.__parent__ is not pau: raise RuntimeError( "I don't know how to migrate your database: " "each group folder should only be within the " "Pluggable Authentication utility that uses it") # we need to remove this registration regs = [r for r in sm.registeredUtilities() if r.component == util] if len(regs) != 1: raise RuntimeError( "I don't know how to migrate your database: " "you should only have registered your group " "folder as an IAuthenticatorPlugin, but it looks " "like it's registered for something additional " "that I don't expect") r = regs[0] sm.unregisterUtility( util, zope.app.authentication.interfaces.IAuthenticatorPlugin, nm) if r.name in pau.authenticatorPlugins: if util.__name__ != r.name: # else no-op plugins = list(pau.authenticatorPlugins) if util.__name__ in pau.authenticatorPlugins: # argh! another active plugin's name is # the same as this group folder's # __name__. That means we need to choose # a new name that is also not in # authenticatorPlugins and not in # pau.keys()... ct = 0 nm = '%s_%d' % (util.__name__, ct) while (nm in pau.authenticatorPlugins or nm in pau): ct += 1 nm = '%s_%d' % (util.__name__, ct) IObjectMover(util).moveTo(pau, nm) plugins[plugins.index(r.name)] = util.__name__ pau.authenticatorPlugins = tuple(plugins) for k, r in pau.registrationManager.items(): if groupfolder.IGroupFolder.providedBy(r.component): del pau.registrationManager[k]
zope.app.zopeappgenerations
/zope.app.zopeappgenerations-3.6.1.tar.gz/zope.app.zopeappgenerations-3.6.1/src/zope/app/zopeappgenerations/evolve3.py
evolve3.py
from persistent import Persistent from zope.security.proxy import ProxyFactory from zope.interface import implements from zope.pagetemplate.pagetemplate import PageTemplate from zope.size.interfaces import ISized from zope.publisher.browser import BrowserView from zope.traversing.api import getPath from zope.filerepresentation.interfaces import IReadFile, IWriteFile from zope.filerepresentation.interfaces import IFileFactory from zope.pagetemplate.engine import AppPT from zope.app.zptpage.i18n import ZopeMessageFactory as _ from zope.container.contained import Contained from zope.app.publication.interfaces import IFileContent from zope.app.zptpage.interfaces import IZPTPage, IRenderZPTPage class ZPTPage(AppPT, PageTemplate, Persistent, Contained): implements(IZPTPage, IRenderZPTPage, IFileContent) # See zope.app.zptpage.interfaces.IZPTPage expand = False # See zope.app.zptpage.interfaces.IZPTPage evaluateInlineCode = False def getSource(self, request=None): """See zope.app.zptpage.interfaces.IZPTPage""" return self.read(request) def setSource(self, text, content_type='text/html'): """See zope.app.zptpage.interfaces.IZPTPage""" if not isinstance(text, unicode): raise TypeError("source text must be Unicode" , text) self.pt_edit(text, content_type) # See zope.app.zptpage.interfaces.IZPTPage source = property(getSource, setSource, None, """Source of the Page Template.""") def pt_getEngineContext(self, namespace): context = self.pt_getEngine().getContext(namespace) context.evaluateInlineCode = self.evaluateInlineCode return context def pt_getContext(self, instance, request, **_kw): # instance is a View component namespace = super(ZPTPage, self).pt_getContext(**_kw) namespace['template'] = self namespace['request'] = request namespace['container'] = namespace['context'] = instance return namespace def pt_source_file(self): try: return getPath(self) except TypeError: return None def render(self, request, *args, **keywords): instance = self.__parent__ debug_flags = request.debug request = ProxyFactory(request) instance = ProxyFactory(instance) if args: args = ProxyFactory(args) kw = ProxyFactory(keywords) namespace = self.pt_getContext(instance, request, args=args, options=kw) return self.pt_render(namespace, showtal=debug_flags.showTAL, sourceAnnotations=debug_flags.sourceAnnotations) class Sized(object): implements(ISized) def __init__(self, page): self.num_lines = len(page.getSource().splitlines()) def sizeForSorting(self): 'See ISized' return ('line', self.num_lines) def sizeForDisplay(self): 'See ISized' if self.num_lines == 1: return _('1 line') return _('${lines} lines', mapping={'lines': str(self.num_lines)}) # File-system access adapters class ZPTReadFile(object): implements(IReadFile) def __init__(self, context): self.context = context def read(self): return self.context.getSource() def size(self): return len(self.read()) class ZPTWriteFile(object): implements(IWriteFile) def __init__(self, context): self.context = context def write(self, data): # We cannot communicate an encoding via FTP. Zope's default is UTF-8, # so use it. self.context.setSource(data.decode('UTF-8'), None) class ZPTFactory(object): implements(IFileFactory) def __init__(self, context): self.context = context def __call__(self, name, content_type, data): page = ZPTPage() # We cannot communicate an encoding via FTP. Zope's default is UTF-8, # so use it. page.setSource(data.decode('UTF-8'), content_type or 'text/html') return page class ZPTSourceView(BrowserView): def __str__(self): return self.context.getSource() __call__ = __str__
zope.app.zptpage
/zope.app.zptpage-3.5.1.tar.gz/zope.app.zptpage-3.5.1/src/zope/app/zptpage/zptpage.py
zptpage.py
========= Changes ========= 5.0 (2023-07-06) ================ - Add support for Python 3.11. - Drop support for Python 2.7, 3.5, 3.6. 4.3 (2022-06-24) ================ - Drop support for Python 3.4. - Add support for Python 3.8, 3.9, 3.10. 4.2.0 (2018-10-19) ================== - Drop support for ``setup.py test``. - Drop support for Python 3.3. - Add support for Python 3.7. 4.1.0 (2017-05-03) ================== - Add support for Python 3.5 and 3.6. - Drop support for Python 3.2 and 2.6. 4.0.1 (2015-06-05) ================== - Add support for Python 3.2 and PyPy3. 4.0.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. 4.0.0a1 (2013-02-22) ==================== - Add support for Python 3.3. - Replace deprecated ``zope.interface.implements`` usage with equivalent ``zope.interface.implementer`` decorator. - Drop support for Python 2.4 and 2.5. 3.5.5 (2010-01-09) ================== - Initial release, extracted from ``zope.app.applicationcontrol``.
zope.applicationcontrol
/zope.applicationcontrol-5.0.tar.gz/zope.applicationcontrol-5.0/CHANGES.rst
CHANGES.rst
""" Runtime Information """ __docformat__ = 'restructuredtext' import os import sys import time try: import locale except ImportError: # pragma: no cover locale = None import platform from zope.component import ComponentLookupError from zope.component import adapter from zope.component import getUtility from zope.interface import implementer from zope.applicationcontrol.interfaces import IApplicationControl from zope.applicationcontrol.interfaces import IRuntimeInfo from zope.applicationcontrol.interfaces import IZopeVersion try: from zope.app.appsetup import appsetup except ImportError: appsetup = None @implementer(IRuntimeInfo) @adapter(IApplicationControl) class RuntimeInfo: """Runtime information.""" def __init__(self, context): self.context = context def getDeveloperMode(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" if appsetup is None: return 'undefined' cc = appsetup.getConfigContext() if cc is None: # make the test run return 'undefined' if cc.hasFeature('devmode'): return 'On' return 'Off' def getPreferredEncoding(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" try: result = locale.getpreferredencoding() except (locale.Error, AttributeError): # pragma: no cover result = '' # Under some systems, getpreferredencoding() can return '' # (e.g., Python 2.7/MacOSX/LANG=en_us.UTF-8). This then blows # up with 'unknown encoding' return result or sys.getdefaultencoding() def getFileSystemEncoding(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" enc = sys.getfilesystemencoding() return enc if enc is not None else self.getPreferredEncoding() def getZopeVersion(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" try: version_utility = getUtility(IZopeVersion) except ComponentLookupError: return "Unavailable" return version_utility.getZopeVersion() def getPythonVersion(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" return sys.version def getPythonPath(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" return tuple(path for path in sys.path) def getSystemPlatform(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" info = [] enc = self.getPreferredEncoding() for item in platform.uname(): try: t = item if isinstance(item, str) else item.decode(enc) except UnicodeError: continue info.append(t) return ' '.join(info) def getCommandLine(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" return " ".join(sys.argv) def getProcessId(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" return os.getpid() def getUptime(self): """See zope.app.applicationcontrol.interfaces.IRuntimeInfo""" return time.time() - self.context.getStartTime()
zope.applicationcontrol
/zope.applicationcontrol-5.0.tar.gz/zope.applicationcontrol-5.0/src/zope/applicationcontrol/runtimeinfo.py
runtimeinfo.py
========= Changes ========= 5.0 (2023-01-06) ================ - Add support for Python 3.10, 3.11. - Drop support for Python 2.7, 3.5, 3.6. 4.5.0 (2021-03-19) ================== - Add support for Python 3.8 and 3.9. - Drop support for Python 3.4. - Fix deprecated test imports from zope.component to use the correct imports from zope.interface. 4.4.0 (2018-08-24) ================== - Host documentation at https://zopeauthentication.readthedocs.io - Add support for Python 3.7. - Drop support for Python 3.3. - Drop support for ``python setup.py test``. 4.3.0 (2017-05-11) ================== - Add support for Python 3.5 and 3.6. - Drop support for Python 2.6 and 3.2. 4.2.1 (2015-06-05) ================== - Add support for PyPy3 and Python 3.2. 4.2.0 (2014-12-26) ================== - Add support for PyPy. PyPy3 support is blocked on a release of a fix for: https://bitbucket.org/pypy/pypy/issue/1946 - Add support for Python 3.4. - Add support for testing on Travis. 4.1.0 (2013-02-21) ================== - Add support for Python 3.3. - Add ``tox.ini`` and ``MANIFEST.in``. 4.0.0 (2012-07-04) ================== - Break inappropriate testing dependency on ``zope.component.nextutility``. (Forward-compatibility with ``zope.component`` 4.0.0). - 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. 3.7.1 (2010-04-30) ================== - Remove undeclared testing dependency on ``zope.testing``. 3.7.0 (2009-03-14) ================== Initial release. This package was split off from ``zope.app.security`` to provide a separate common interface definition for authentication utilities without extra dependencies.
zope.authentication
/zope.authentication-5.0.tar.gz/zope.authentication-5.0/CHANGES.rst
CHANGES.rst
===================== zope.authentication ===================== .. image:: https://img.shields.io/pypi/v/zope.authentication.svg :target: https://pypi.org/project/zope.authentication/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.authentication.svg :target: https://pypi.org/project/zope.authentication/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.authentication/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.authentication/actions/workflows/tests.yml .. image:: https://coveralls.io/repos/github/zopefoundation/zope.authentication/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.authentication?branch=master .. image:: https://readthedocs.org/projects/zopeauthentication/badge/?version=latest :target: https://zopeauthentication.readthedocs.io/en/latest/ :alt: Documentation Status This package provides a definition of authentication concepts for use in Zope Framework. This includes: - ``IAuthentication`` - ``IUnauthenticatedPrincipal`` - ``ILogout`` Documentation is hosted at https://zopeauthentication.readthedocs.io/en/latest/
zope.authentication
/zope.authentication-5.0.tar.gz/zope.authentication-5.0/README.rst
README.rst
"""Authentication interfaces """ from zope.interface import Interface from zope.schema.interfaces import ISource from zope.security.interfaces import IGroup from zope.security.interfaces import IPrincipal class PrincipalLookupError(LookupError): """No principal for given principal id""" class IUnauthenticatedPrincipal(IPrincipal): """A principal that hasn't been authenticated. Authenticated principals are preferable to UnauthenticatedPrincipals. """ class IFallbackUnauthenticatedPrincipal(IUnauthenticatedPrincipal): """Marker interface for the fallback unauthenticated principal. This principal can be used by publications to set on a request if no principal, not even an unauthenticated principal, was returned by any authentication utility to fulfil the contract of IApplicationRequest. """ class IUnauthenticatedGroup(IGroup): """A group containing unauthenticated users""" class IAuthenticatedGroup(IGroup): """A group containing authenticated users""" class IEveryoneGroup(IGroup): """A group containing all users""" class IAuthentication(Interface): """Provide support for establishing principals for requests. This is implemented by performing protocol-specific actions, such as issuing challenges or providing login interfaces. :class:`IAuthentication` objects are used to implement authentication utilities. Because they implement utilities, they are expected to collaborate with utilities in other contexts. Client code doesn't search a context and call multiple utilities. Instead, client code will call the most specific utility in a place and rely on the utility to delegate to other utilities as necessary. The interface doesn't include methods for data management. Utilities may use external data and not allow management in Zope. Simularly, the data to be managed may vary with different implementations of a utility. """ def authenticate(request): """Identify a principal for a request. If a principal can be identified, then return the principal. Otherwise, return None. The request object is fairly opaque. We may decide that it implements some generic request interface. .. note:: Implementation note: It is likely that the component will dispatch to another component based on the actual request interface. This will allow different kinds of requests to be handled correctly. For example, a component that authenticates based on user names and passwords might request an adapter for the request as in:: getpw = getAdapter(request, context=self) The ``context`` keyword argument is used to control where the :class:`ILoginPassword` component is searched for. This is necessary because requests are placeless. """ def unauthenticatedPrincipal(): """Return the unauthenticated principal, if one is defined. Return None if no unauthenticated principal is defined. The unauthenticated principal must provide :class:`IUnauthenticatedPrincipal`. """ def unauthorized(id, request): """Signal an authorization failure. This method is called when an auhorization problem occurs. It can perform a variety of actions, such as issuing an HTTP authentication challenge or displaying a login interface. Note that the authentication utility nearest to the requested resource is called. It is up to authentication utility implementations to collaborate with utilities higher in the object hierarchy. If no principal has been identified, id will be None. """ def getPrincipal(id): """Get principal meta-data. Returns an object of type :class:`~.IPrincipal` for the given principal id. A :class:`PrincipalLookupError` is raised if the principal cannot be found. Note that the authentication utility nearest to the requested resource is called. It is up to authentication utility implementations to collaborate with utilities higher in the object hierarchy. """ class ILoginPassword(Interface): """A password based login. An :class:`IAuthentication` utility may use this (adapting a request), to discover the login/password passed from the user, or to indicate that a login is required. """ def getLogin(): """Return login name, or None if no login name found.""" def getPassword(): """Return password, or None if no login name found. If there's a login but no password, return empty string. """ def needLogin(realm): """Indicate that a login is needed. The realm argument is the name of the principal registry. """ class IPrincipalSource(ISource): """A Source of Principal Ids""" class ILogout(Interface): """Provides support for logging out.""" def logout(request): """Perform a logout.""" class ILogoutSupported(Interface): """A marker indicating that the security configuration supports logout. Provide an adapter to this interface to signal that the security system supports logout. """
zope.authentication
/zope.authentication-5.0.tar.gz/zope.authentication-5.0/src/zope/authentication/interfaces.py
interfaces.py
"""Principal source and helper function """ import base64 from zope.browser.interfaces import ITerms from zope.component import adapter from zope.component import getUtility from zope.component import queryNextUtility from zope.interface import Interface from zope.interface import implementer from zope.schema.interfaces import ISourceQueriables from zope.authentication.interfaces import IAuthentication from zope.authentication.interfaces import IPrincipalSource from zope.authentication.interfaces import PrincipalLookupError def checkPrincipal(context, principal_id): """Utility function to check if there's a principal for given principal id. Raises :exc:`ValueError` when principal doesn't exists for given context and principal id. To test it, let's create and register a dummy authentication utility. >>> from zope.authentication.interfaces import IAuthentication >>> from zope.authentication.interfaces import PrincipalLookupError >>> from zope.interface import implementer >>> @implementer(IAuthentication) ... class DummyUtility(object): ... ... def getPrincipal(self, id): ... if id == 'bob': ... return id ... raise PrincipalLookupError(id) >>> from zope.component import provideUtility >>> provideUtility(DummyUtility()) Now, let's check the behaviour of this function. >>> from zope.authentication.principal import checkPrincipal >>> checkPrincipal(None, 'bob') >>> checkPrincipal(None, 'dan') Traceback (most recent call last): ... ValueError: ('Undefined principal id', 'dan') """ auth = getUtility(IAuthentication, context=context) try: if auth.getPrincipal(principal_id): return except PrincipalLookupError: pass raise ValueError("Undefined principal id", principal_id) @implementer(IPrincipalSource, ISourceQueriables) class PrincipalSource: """Generic Principal Source Implements :class:`zope.authentication.interfaces.IPrincipalSource` and :class:`zope.schema.interfaces.ISourceQueriables`. """ def __contains__(self, id): """Test for the existence of a user. We want to check whether the system knows about a particular principal, which is referenced via its id. The source will go through the most local authentication utility to look for the principal. Whether the utility consults other utilities to give an answer is up to the utility itself. First we need to create a dummy utility that will return a user, if the id is 'bob'. >>> from zope.authentication.interfaces import IAuthentication >>> from zope.interface import implementer >>> @implementer(IAuthentication) ... class DummyUtility(object): ... def getPrincipal(self, id): ... if id == 'bob': ... return id ... raise PrincipalLookupError(id) Let's register our dummy auth utility. >>> from zope.component import provideUtility >>> provideUtility(DummyUtility()) Now initialize the principal source and test the method >>> from zope.authentication.principal import PrincipalSource >>> source = PrincipalSource() >>> 'jim' in source False >>> 'bob' in source True """ auth = getUtility(IAuthentication) try: auth.getPrincipal(id) except PrincipalLookupError: return False else: return True def getQueriables(self): """Returns an iteratable of queriables. Queriables are responsible for providing interfaces to search for principals by a set of given parameters (can be different for the various queriables). This method will walk up through all of the authentication utilities to look for queriables. >>> from zope.schema.interfaces import ISourceQueriables >>> @implementer(IAuthentication) ... class DummyUtility1(object): ... __parent__ = None ... def __repr__(self): return 'dummy1' >>> dummy1 = DummyUtility1() >>> @implementer(ISourceQueriables, IAuthentication) ... class DummyUtility2(object): ... __parent__ = None ... def getQueriables(self): ... return ('1', 1), ('2', 2), ('3', 3) >>> dummy2 = DummyUtility2() >>> @implementer(IAuthentication) ... class DummyUtility3(DummyUtility2): ... def getQueriables(self): ... return ('4', 4), >>> dummy3 = DummyUtility3() >>> from zope.authentication.tests.utils import testingNextUtility >>> testingNextUtility(dummy1, dummy2, IAuthentication) >>> testingNextUtility(dummy2, dummy3, IAuthentication) >>> from zope.component import provideUtility >>> provideUtility(dummy1) >>> from zope.authentication.principal import PrincipalSource >>> source = PrincipalSource() >>> list(source.getQueriables()) [('0', dummy1), ('1.1', 1), ('1.2', 2), ('1.3', 3), ('2.4', 4)] """ i = 0 auth = getUtility(IAuthentication) yielded = [] while True: queriables = ISourceQueriables(auth, None) if queriables is None: yield str(i), auth else: for qid, queriable in queriables.getQueriables(): # ensure that we dont return same yielded utility more # then once if queriable not in yielded: yield f'{i}.{qid}', queriable yielded.append(queriable) auth = queryNextUtility(auth, IAuthentication) if auth is None: break i += 1 @implementer(ITerms) @adapter(IPrincipalSource, Interface) class PrincipalTerms: """ Implementation of :class:`zope.browser.interfaces.ITerms` given a :class:`zope.authentication.interfaces.IPrincipalSource` and request object. """ def __init__(self, context, request): self.context = context def _encode(self, id): # principal_id is always str: id = id.encode('utf-8') res = base64.b64encode(id).strip().replace(b'=', b'_') return res.decode() def _decode(self, token): return base64.b64decode( token.replace('_', '=').encode()).decode('utf-8') def getTerm(self, principal_id): """Return a :class:`PrincipalTerm` for the given ID. If no such principal can be found, raises :exc:`LooupError`. """ if principal_id not in self.context: raise LookupError(principal_id) auth = getUtility(IAuthentication) principal = auth.getPrincipal(principal_id) if principal is None: # TODO: is this a possible case? raise LookupError(principal_id) return PrincipalTerm(self._encode(principal_id), principal.title) def getValue(self, token): """Return the principal ID given its token.""" return self._decode(token) class PrincipalTerm: """ A principal term. We have a ``token`` based on the encoded principal ID, and a ``title``. """ def __init__(self, token, title): self.token = token self.title = title
zope.authentication
/zope.authentication-5.0.tar.gz/zope.authentication-5.0/src/zope/authentication/principal.py
principal.py
Logout Support ============== .. testsetup:: from zope.component.testing import setUp setUp() Logout support is defined by a simple interface :class:`zope.authentication.interfaces.ILogout`: .. doctest:: >>> from zope.authentication.interfaces import ILogout that has a single 'logout' method. The current use of ILogout is to adapt an :class:`zope.authentication.interfaces.IAuthentication` instance to :class:`~.ILogout`. To illustrate, we'll create a simple logout implementation that adapts :class:`~.IAuthentication`: .. doctest:: >>> from zope.component import adapter, provideAdapter >>> from zope.interface import implementer >>> from zope.authentication.interfaces import IAuthentication >>> @adapter(IAuthentication) ... @implementer(ILogout) ... class SimpleLogout(object): ... ... def __init__(self, auth): ... pass ... ... def logout(self, request): ... print('User has logged out') >>> provideAdapter(SimpleLogout) and something to represent an authentication utility: .. doctest:: >>> @implementer(IAuthentication) ... class Authentication(object): ... pass >>> auth = Authentication() To perform a logout, we adapt auth to ``ILogout`` and call 'logout': .. doctest:: >>> logout = ILogout(auth) >>> request = object() >>> logout.logout(request) User has logged out The 'NoLogout' Adapter ---------------------- The :class:`zope.authentication.logout.NoLogout` class can be registered as a fallback provider of ``ILogout`` for ``IAuthentication`` components that are not otherwise adaptable to ``ILogout``. ``NoLogout``'s logout method is a no-op. .. doctest:: >>> from zope.authentication.logout import NoLogout >>> NoLogout(auth).logout(request) Logout User Interface --------------------- Because some authentication protocols do not formally support logout, it may not be possible for a user to logout once he or she has logged in. In such cases, it would be inappropriate to present a user interface for logging out. Because logout support is site-configurable, Zope provides an adapter that, when registered, indicates that the site is configured for logout. This class merely serves as a flag as it implements ILogoutSupported: .. doctest:: >>> from zope.authentication.logout import LogoutSupported >>> from zope.authentication.interfaces import ILogoutSupported >>> ILogoutSupported.implementedBy(LogoutSupported) True >>> ILogoutSupported.providedBy(LogoutSupported(request)) True .. testcleanup:: from zope.component.testing import tearDown tearDown()
zope.authentication
/zope.authentication-5.0.tar.gz/zope.authentication-5.0/docs/logout.rst
logout.rst
Principal Terms =============== .. testsetup:: from zope.component.testing import setUp setUp() Principal Terms are used to support browser interfaces for searching principal sources. They provide access to tokens and titles for values. The principal terms view uses an authentication utility to get principal titles. Let's create an authentication utility to demonstrate how this works: .. doctest:: >>> class Principal(object): ... def __init__(self, id, title): ... self.id, self.title = id, title >>> from zope.interface import implementer >>> from zope.authentication.interfaces import IAuthentication >>> from zope.authentication.interfaces import PrincipalLookupError >>> @implementer(IAuthentication) ... class AuthUtility: ... data = {'jim': 'Jim Fulton', 'stephan': 'Stephan Richter'} ... ... def getPrincipal(self, id): ... title = self.data.get(id) ... if title is not None: ... return Principal(id, title) ... raise PrincipalLookupError Now we need to install the authentication utility: .. doctest:: >>> from zope.component import provideUtility >>> provideUtility(AuthUtility(), IAuthentication) We need a principal source so that we can create a view from it. .. doctest:: >>> from zope.component import getUtility >>> class PrincipalSource(object): ... def __contains__(self, id): ... auth = getUtility(IAuthentication) ... try: ... auth.getPrincipal(id) ... except PrincipalLookupError: ... return False ... else: ... return True Now we can create an terms view and ask the terms view for terms: .. doctest:: >>> from zope.authentication.principal import PrincipalTerms >>> terms = PrincipalTerms(PrincipalSource(), None) >>> term = terms.getTerm('stephan') >>> term.title 'Stephan Richter' >>> term.token u'c3RlcGhhbg__' If we ask for a term that does not exist, we get a lookup error: .. doctest:: >>> terms.getTerm('bob') Traceback (most recent call last): ... LookupError: bob If we have a token, we can get the principal id for it. .. doctest:: >>> terms.getValue('c3RlcGhhbg__') u'stephan' .. testcleanup:: from zope.component.testing import tearDown
zope.authentication
/zope.authentication-5.0.tar.gz/zope.authentication-5.0/docs/principalterms.rst
principalterms.rst
try: from pytz import UTC, _UTC # we import _UTC so that pickles made by the # fallback code below can still be reinstantiated if pytz is added in. except ImportError: import datetime class UTC(datetime.tzinfo): """UTC Identical to the reference UTC implementation given in Python docs except that it unpickles using the single module global instance defined beneath this class declaration. Also contains extra attributes and methods to match other pytz tzinfo instances. """ zone = "UTC" def utcoffset(self, dt): return ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return ZERO def __reduce__(self): return _UTC, () def localize(self, dt, is_dst=False): '''Convert naive time to local time''' if dt.tzinfo is not None: raise ValueError, 'Not naive datetime (tzinfo is already set)' return dt.replace(tzinfo=self) def normalize(self, dt, is_dst=False): '''Correct the timezone information on the given datetime''' if dt.tzinfo is None: raise ValueError, 'Naive time - no tzinfo set' return dt.replace(tzinfo=self) def __repr__(self): return "<UTC>" def __str__(self): return "UTC" UTC = utc = UTC() # UTC is a singleton def _UTC(): """Factory function for utc unpickling. Makes sure that unpickling a utc instance always returns the same module global. These examples belong in the UTC class above, but it is obscured; or in the README.txt, but we are not depending on Python 2.4 so integrating the README.txt examples with the unit tests is not trivial. >>> import datetime, pickle >>> dt = datetime.datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc) >>> naive = dt.replace(tzinfo=None) >>> p = pickle.dumps(dt, 1) >>> naive_p = pickle.dumps(naive, 1) >>> len(p), len(naive_p), len(p) - len(naive_p) (60, 43, 17) >>> new = pickle.loads(p) >>> new == dt True >>> new is dt False >>> new.tzinfo is dt.tzinfo True >>> utc is UTC is timezone('UTC') True >>> utc is timezone('GMT') False """ return utc _UTC.__safe_for_unpickling__ = True
zope.bforest
/zope.bforest-1.2.tar.gz/zope.bforest-1.2/src/zope/bforest/utils.py
utils.py
import datetime import BTrees import zope.bforest.bforest import zope.bforest.utils def mutating(name): def mutate(self, *args, **kwargs): if (datetime.datetime.now(zope.bforest.utils.UTC) - self.last_rotation) >= self._inner_period: self.rotateBucket() return getattr(super(Abstract, self), name)(*args, **kwargs) return mutate class Abstract(zope.bforest.bforest.AbstractBForest): def __init__(self, period, d=None, count=2): super(Abstract, self).__init__(d, count) self.period = period self.last_rotation = datetime.datetime.now(zope.bforest.utils.UTC) _inner_period = _period = None def period(self, value): self._period = value self._inner_period = self._period / (len(self.buckets) - 1) period = property( lambda self: self._period, period) def copy(self): # this makes an exact copy, including the individual state of each # bucket. If you want a dict, cast it to a dict, or if you want # another one of these but with all of the keys in the first bucket, # call obj.__class__(obj) copy = self.__class__(self.period, count=len(self.buckets)) for i in range(len(self.buckets)): copy.buckets[i].update(self.buckets[i]) return copy def rotateBucket(self): super(Abstract, self).rotateBucket() self.last_rotation = datetime.datetime.now(zope.bforest.utils.UTC) __setitem__ = mutating('__setitem__') __delitem__ = mutating('__delitem__') pop = mutating('pop') popitem = mutating('popitem') update = mutating('update') class IOBForest(Abstract): _treemodule = BTrees.family32.IO class OIBForest(Abstract): _treemodule = BTrees.family32.OI class IIBForest(Abstract): _treemodule = BTrees.family32.II class LOBForest(Abstract): _treemodule = BTrees.family64.IO class OLBForest(Abstract): _treemodule = BTrees.family64.OI class LLBForest(Abstract): _treemodule = BTrees.family64.II class OOBForest(Abstract): _treemodule = BTrees.family32.OO
zope.bforest
/zope.bforest-1.2.tar.gz/zope.bforest-1.2/src/zope/bforest/periodic.py
periodic.py
import persistent import persistent.list import BTrees class AbstractBForest(persistent.Persistent): _treemodule = None # override _marker = object() def __init__(self, d=None, count=2): if count < 0: raise ValueError("count must be 0 or greater") if count == 0: if d is not None: raise ValueError( "cannot set initial values without a bucket") l = persistent.list.PersistentList() else: Tree = self._treemodule.BTree if d is not None: first = Tree(d) else: first = Tree() l = [Tree() for i in range(count - 1)] l.insert(0, first) l = persistent.list.PersistentList(l) self.buckets = l def __getitem__(self, key): m = self._marker res = self.get(key, m) if res is m: raise KeyError(key) return res def __setitem__(self, key, value): self.buckets[0][key] = value def get(self, key, default=None): m = self._marker for b in self.buckets: res = b.get(key, m) if res is not m: return res return default def __delitem__(self, key): found = False for b in self.buckets: # we delete all, in case one bucket is masking an old value try: del b[key] except KeyError: pass else: found = True if not found: raise KeyError(key) def update(self, d): self.buckets[0].update(d) def keys(self): buckets = self.buckets if len(buckets) == 1: res = buckets[0].keys() elif getattr(self._treemodule, 'multiunion', None) is not None: return self._treemodule.multiunion(buckets) else: union = self._treemodule.union res = union(buckets[0], buckets[1]) for b in buckets[2:]: res = union(res, b) return res def tree(self): # convert to a tree; do as much in C as possible. buckets = self.buckets res = self._treemodule.BTree(buckets[-1]) for b in buckets[-2::-1]: res.update(b) return res def items(self): return self.tree().items() def values(self): return self.tree().values() def maxKey(self, key=None): res = m = self._marker if key is None: args = () else: args = (key,) for b in self.buckets: try: v = b.maxKey(*args) except ValueError: pass else: if res is m or v > res: res = v if res is m: raise ValueError('no key') return res def minKey(self, key=None): res = m = self._marker if key is None: args = () else: args = (key,) for b in self.buckets: try: v = b.minKey(*args) except ValueError: pass else: if res is m or v < res: res = v if res is m: raise ValueError('no key') return res def iteritems(self, min=None, max=None, excludemin=False, excludemax=False): # this approach might be slower than simply iterating over self.keys(), # but it has a chance of waking up fewer objects in the ZODB, if the # iteration stops early. sources = [] for b in self.buckets: i = iter(b.items(min, max, excludemin, excludemax)) try: first = i.next() except StopIteration: pass else: sources.append([first, i]) scratch = self._treemodule.Bucket() while sources: for ((k, v), i) in sources: scratch.setdefault(k, v) k = scratch.minKey() yield k, scratch[k] for i in range(len(sources)-1, -1, -1): source = sources[i] if source[0][0] == k: try: source[0] = source[1].next() except StopIteration: del sources[i] scratch.clear() def iterkeys(self, min=None, max=None, excludemin=False, excludemax=False): return (k for k, v in self.iteritems(min, max, excludemin, excludemax)) __iter__ = iterkeys def itervalues(self, min=None, max=None, excludemin=False, excludemax=False): return (v for k, v in self.iteritems(min, max, excludemin, excludemax)) def __eq__(self, other): # we will declare contents and its ordering to define equality. More # restrictive definitions can be wrapped around this one. if getattr(other, 'iteritems', None) is None: return False si = self.iteritems() so = other.iteritems() while 1: try: k, v = si.next() except StopIteration: try: so.next() except StopIteration: return True return False try: ok, ov = so.next() except StopIteration: return False else: if ok != k or ov != v: return False def __ne__(self, other): return not self.__eq__(other) def __gt__(self, other): # TODO blech, change this if not isinstance(other, dict): try: other = dict(other) except TypeError: return id(self) > id(other) return dict(self) > other def __lt__(self, other): # TODO blech, change this if not isinstance(other, dict): try: other = dict(other) except TypeError: return id(self) < id(other) return dict(self) < other def __ge__(self, other): # TODO blech, change this if not isinstance(other, dict): try: other = dict(other) except TypeError: return id(self) >= id(other) return dict(self) >= other def __le__(self, other): # TODO blech, change this if not isinstance(other, dict): try: other = dict(other) except TypeError: return id(self) <= id(other) return dict(self) <= other def __len__(self): # keeping track of a separate length is currently considered to be # somewhat expensive per write and not necessarily always valuable # (that is, we don't always care what the length is). Therefore, we # have this quite expensive default approach. If you need a len often # and cheaply then you'll need to wrap the BForest and keep track of it # yourself. This is expensive both because it wakes up every BTree and # bucket in the BForest, which might be quite a few objects; and # because of the merge necessary to create the composite tree (which # eliminates duplicates from the count). return len(self.tree()) def setdefault(self, key, failobj=None): try: res = self[key] except KeyError: res = self[key] = failobj return res def pop(self, key, d=_marker): try: res = self[key] except KeyError: if d is self._marker: raise KeyError(key) else: return d else: del self[key] return res def popitem(self): key = self.minKey() val = self.pop(key) return key, val def __contains__(self, key): for b in self.buckets: if b.has_key(key): return True return False has_key = __contains__ def copy(self): # this makes an exact copy, including the individual state of each # bucket. If you want a dict, cast it to a dict, or if you want # another one of these but with all of the keys in the first bucket, # call obj.__class__(obj) copy = self.__class__(count=len(self.buckets)) for i in range(len(self.buckets)): copy.buckets[i].update(self.buckets[i]) return copy def clear(self): for b in self.buckets: b.clear() def __nonzero__(self): for b in self.buckets: if bool(b): return True return False def rotateBucket(self): buckets = self.buckets b = buckets.pop() b.clear() buckets.insert(0, b) class IOBForest(AbstractBForest): _treemodule = BTrees.family32.IO class OIBForest(AbstractBForest): _treemodule = BTrees.family32.OI class IIBForest(AbstractBForest): _treemodule = BTrees.family32.II class LOBForest(AbstractBForest): _treemodule = BTrees.family64.IO class OLBForest(AbstractBForest): _treemodule = BTrees.family64.OI class LLBForest(AbstractBForest): _treemodule = BTrees.family64.II class OOBForest(AbstractBForest): _treemodule = BTrees.family32.OO
zope.bforest
/zope.bforest-1.2.tar.gz/zope.bforest-1.2/src/zope/bforest/bforest.py
bforest.py
=========== Changelog =========== 3.0 (2023-03-27) ================ - Add support for Python 3.11. - Drop support for Python 2.7, 3.5, 3.6. 2.4 (2022-04-06) ================ - Add support for Python 3.8, 3.9, 3.10. - Drop support for Python 3.4. 2.3 (2018-10-05) ================ - Add support for Python 3.7. 2.2.0 (2017-08-10) ================== - Add support for Python 3.5 and 3.6. - Drop support for Python 2.6, 3.2 and 3.3. - Host documentation at https://zopebrowser.readthedocs.io 2.1.0 (2014-12-26) ================== - Add support for Python 3.4. - Add support for testing on Travis. 2.0.2 (2013-03-08) ================== - Add Trove classifiers indicating CPython, 3.2 and PyPy support. 2.0.1 (2013-02-11) ================== - Add support for testing with tox. 2.0.0 (2013-02-11) ================== - Test coverage of 100% verified. - Add support for Python 3.3 and PyPy. - Drop support for Python 2.4 and 2.5. 1.3 (2010-04-30) ================ - Remove ``test`` extra and ``zope.testing`` dependency. 1.2 (2009-05-18) ================ - Move ``ISystemErrorView`` interface here from ``zope.app.exception`` to break undesirable dependencies. - Fix home page and author's e-mail address. - Add doctests to ``long_description``. 1.1 (2009-05-13) ================ - Move ``IAdding`` interface here from ``zope.app.container.interfaces`` to break undesirable dependencies. 1.0 (2009-05-13) ================ - Move ``IView`` and ``IBrowserView`` interfaces here from ``zope.publisher.interfaces`` to break undesirable dependencies. 0.5.0 (2008-12-11) ================== - Move ``ITerms`` interface here from ``zope.app.form.browser.interfaces`` to break undesirable dependencies.
zope.browser
/zope.browser-3.0.tar.gz/zope.browser-3.0/CHANGES.rst
CHANGES.rst
============== zope.browser ============== .. image:: https://img.shields.io/pypi/v/zope.browser.svg :target: https://pypi.python.org/pypi/zope.browser/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.browser.svg :target: https://pypi.org/project/zope.browser/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.browser/workflows/tests/badge.svg :target: https://github.com/zopefoundation/zope.browser/actions?query=workflow%3A%22tests%22 .. image:: https://coveralls.io/repos/github/zopefoundation/zope.browser/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.browser?branch=master .. image:: https://readthedocs.org/projects/zopebrowser/badge/?version=latest :target: https://zopebrowser.readthedocs.io/en/latest/ :alt: Documentation Status This package provides shared browser components for the Zope Toolkit. These components consist of a set of interfaces defining common concepts, including: - ``IView`` - ``IBrowserView`` - ``IAdding`` - ``ITerms`` - ``ISystemErrorView`` Documentation is hosted at https://zopebrowser.readthedocs.io
zope.browser
/zope.browser-3.0.tar.gz/zope.browser-3.0/README.rst
README.rst
============ Interfaces ============ This package defines several basic interfaces. .. currentmodule:: zope.browser.interfaces IView ===== Views adapt both a context and a request. There is not much we can test except that ``IView`` is importable and an interface: >>> from zope.interface import Interface >>> from zope.browser.interfaces import IView >>> Interface.providedBy(IView) True .. autointerface:: IView IBrowserView ============ Browser views are views specialized for requests from a browser (e.g., as distinct from WebDAV, FTP, XML-RPC, etc.). There is not much we can test except that ``IBrowserView`` is importable and an interface derived from :class:`IView`: >>> from zope.interface import Interface >>> from zope.browser.interfaces import IBrowserView >>> Interface.providedBy(IBrowserView) True >>> IBrowserView.extends(IView) True .. autointerface:: IBrowserView IAdding ======= Adding views manage how newly-created items get added to containers. There is not much we can test except that ``IAdding`` is importable and an interface derived from :class:`IBrowserView`: >>> from zope.interface import Interface >>> from zope.browser.interfaces import IAdding >>> Interface.providedBy(IBrowserView) True >>> IAdding.extends(IBrowserView) True .. autointerface:: IAdding ITerms ====== The ``ITerms`` interface is used as a base for ``ISource`` widget implementations. This interfaces get used by ``zope.app.form`` and was initially defined in ``zope.app.form.browser.interfaces``, which made it impossible to use for other packages like ``z3c.form`` wihtout depending on ``zope.app.form``. Moving such base components / interfaces to ``zope.browser`` makes it possible to share them without undesirable dependencies. There is not much we can test except that ITerms is importable and an interface: >>> from zope.interface import Interface >>> from zope.browser.interfaces import ITerms >>> Interface.providedBy(ITerms) True .. autointerface:: ITerms ISystemErrorView ================ Views providing this interface can classify their contexts as system errors. These errors can be handled in a special way (e. g. more detailed logging). There is not much we can test except that ``ISystemErrorView`` is importable and an interface: >>> from zope.interface import Interface >>> from zope.browser.interfaces import ISystemErrorView >>> Interface.providedBy(ISystemErrorView) True .. autointerface:: ISystemErrorView
zope.browser
/zope.browser-3.0.tar.gz/zope.browser-3.0/src/zope/browser/README.rst
README.rst
"""Shared dependency less Zope3 brwoser components. """ from zope.interface import Attribute from zope.interface import Interface class IView(Interface): """ Views are multi-adapters for context and request objects. """ context = Attribute("The context object the view renders") request = Attribute("The request object driving the view") class IBrowserView(IView): """ Views which are specialized for requests from a browser Such views are distinct from those geerated via WebDAV, FTP, XML-RPC, etc. """ class IAdding(IBrowserView): """ Multi-adapter interface for views which add items to containers. The 'context' of the view must implement :obj:`zope.container.interfaces.IContainer`. """ def add(content): """Add content object to context. Add using the name in ``contentName``. Return the added object in the context of its container. If ``contentName`` is already used in container, raise :class:`zope.container.interfaces.DuplicateIDError`. """ contentName = Attribute( """The content name, usually set by the Adder traverser. If the content name hasn't been defined yet, returns ``None``. Some creation views might use this to optionally display the name on forms. """ ) def nextURL(): """Return the URL that the creation view should redirect to. This is called by the creation view after calling add. It is the adder's responsibility, not the creation view's to decide what page to display after content is added. """ def nameAllowed(): """Return whether names can be input by the user.""" def addingInfo(): """Return add menu data as a sequence of mappings. Each mapping contains 'action', 'title', and possibly other keys. The result is sorted by title. """ def isSingleMenuItem(): """Return whether there is single menu item or not.""" def hasCustomAddView(): """This should be called only if there is ``singleMenuItem`` else return 0. """ class ITerms(Interface): """ Adapter providing lookups for vocabulary terms. """ def getTerm(value): """Return an ITitledTokenizedTerm object for the given value LookupError is raised if the value isn't in the source. The return value should have the ``token`` and ``title`` attributes. """ def getValue(token): """Return a value for a given identifier token LookupError is raised if there isn't a value in the source. """ class ISystemErrorView(Interface): """Error views that can classify their contexts as system errors """ def isSystemError(): """Return a boolean indicating whether the error is a system error."""
zope.browser
/zope.browser-3.0.tar.gz/zope.browser-3.0/src/zope/browser/interfaces.py
interfaces.py
========= Changes ========= 5.0 (2023-02-08) ================ - Drop support for Python 2.7, 3.4, 3.5, 3.6. - Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11. 4.4 (2018-10-05) ================ - Add support for Python 3.7. 4.3.0 (2017-08-03) ================== - Drop support for Python 3.3. - Add support for PyPy3 3.5. - Fix test compatibility with zope.component 4.4.0. 4.2.0 (2017-05-28) ================== - Add support for Python 3.5 and 3.6. - Drop support for Python 2.6 and 3.2. - Drop support for 'setup.py test'. 4.1.1 (2015-06-05) ================== - Add support for PyPy3 and Python 3.2. 4.1.0 (2014-12-24) ================== - Add support for PyPy. PyPy3 support is pending a release of fix for https://bitbucket.org/pypy/pypy/issue/1946). - Add support for Python 3.4. - Add support for testing on Travis. 4.1.0a1 (2013-02-22) ==================== - Add support for Python 3.3. 4.0.0 (2012-07-04) ================== - Strip noise from context actions in doctests. Make output is now more meaningful, and hides irrelevant details. (forward-compatibility with ``zope.component`` 4.0.0). - Replace deprecated ``zope.interface.implements`` usage with equivalent ``zope.interface.implementer`` decorator. - Drop support for Python 2.4 and 2.5. 3.9.1 (2010-04-30) ================== - Remove use of ``zope.testing.doctestunit`` in favor of stdlib's ``doctest``. 3.9.0 (2009-08-27) ================== Initial release. This package was splitted off zope.app.publisher.
zope.browsermenu
/zope.browsermenu-5.0.tar.gz/zope.browsermenu-5.0/CHANGES.rst
CHANGES.rst
====================== ``zope.browsermenu`` ====================== .. image:: https://img.shields.io/pypi/v/zope.browsermenu.svg :target: https://pypi.python.org/pypi/zope.browsermenu/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.browsermenu.svg :target: https://pypi.org/project/zope.browsermenu/ :alt: Supported Python versions .. image:: https://travis-ci.com/zopefoundation/zope.browsermenu.svg?branch=master :target: https://travis-ci.com/zopefoundation/zope.browsermenu .. image:: https://coveralls.io/repos/github/zopefoundation/zope.browsermenu/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.browsermenu?branch=master .. note:: This package is at present not reusable without depending on a large chunk of the Zope Toolkit and its assumptions. It is maintained by the `Zope Toolkit project <http://docs.zope.org/zopetoolkit/>`_. This package provides an implementation of browser menus and ZCML directives for configuring them.
zope.browsermenu
/zope.browsermenu-5.0.tar.gz/zope.browsermenu-5.0/README.rst
README.rst
"""Menu field """ from zope.component import queryUtility from zope.configuration.exceptions import ConfigurationError from zope.configuration.fields import GlobalObject from zope.schema import ValidationError from zope.browsermenu.interfaces import IMenuItemType class MenuField(GlobalObject): r"""This fields represents a menu (item type). Besides being able to look up the menu by importing it, we also try to look up the name in the site manager. >>> from zope.interface import directlyProvides >>> from zope.interface.interface import InterfaceClass >>> menu1 = InterfaceClass('menu1', (), ... __doc__='Menu Item Type: menu1', ... __module__='zope.app.menus') >>> directlyProvides(menu1, IMenuItemType) >>> menus = None >>> class Resolver(object): ... def resolve(self, path): ... if path.startswith('zope.app.menus') and \ ... hasattr(menus, 'menu1') or \ ... path == 'zope.browsermenu.menus.menu1': ... return menu1 ... raise ConfigurationError('menu1') >>> field = MenuField() >>> field = field.bind(Resolver()) Test 1: Import the menu ----------------------- >>> field.fromUnicode('zope.browsermenu.menus.menu1') is menu1 True Test 2: We have a shortcut name. Import the menu from `zope.app.menus1`. ------------------------------------------------------------------------ >>> from types import ModuleType as module >>> import sys >>> menus = module('menus') >>> old = sys.modules.get('zope.app.menus', None) >>> sys.modules['zope.app.menus'] = menus >>> setattr(menus, 'menu1', menu1) >>> field.fromUnicode('menu1') is menu1 True >>> if old is not None: ... sys.modules['zope.app.menus'] = old Test 3: Get the menu from the Site Manager ------------------------------------------ >>> from zope.component import provideUtility >>> provideUtility(menu1, IMenuItemType, 'menu1') >>> field.fromUnicode('menu1') is menu1 True """ def fromUnicode(self, u): name = str(u.strip()) # queryUtility can never raise ComponentLookupError value = queryUtility(IMenuItemType, name) if value is not None: self.validate(value) return value try: value = self.context.resolve('zope.app.menus.' + name) except ConfigurationError: try: value = self.context.resolve(name) except ConfigurationError as v: raise ValidationError(v) self.validate(value) return value
zope.browsermenu
/zope.browsermenu-5.0.tar.gz/zope.browsermenu-5.0/src/zope/browsermenu/field.py
field.py
"""Menu-specific interfaces """ from zope.i18nmessageid import ZopeMessageFactory as _ from zope.interface import Interface from zope.interface import directlyProvides from zope.interface.interfaces import IInterface from zope.schema import URI from zope.schema import Int from zope.schema import Text from zope.schema import TextLine class IMenuItemType(IInterface): """Menu item type Menu item types are interfaces that define classes of menu items. """ class AddMenu(Interface): """Special menu for providing a list of addable objects.""" directlyProvides(AddMenu, IMenuItemType) class IBrowserMenu(Interface): """Menu Menus are objects that can return a list of menu items they contain. How they generate this list is up to them. Commonly, however, they will look up adapters that provide the ``IBrowserMenuItem`` interface. """ id = TextLine( title=_("Menu Id"), description=_("The id uniquely identifies this menu."), required=True ) title = TextLine( title=_("Menu title"), description=_("The title provides the basic label for the menu."), required=False ) description = Text( title=_("Menu description"), description=_("A description of the menu. This might be shown " "on menu pages or in pop-up help for menus."), required=False ) def getMenuItems(object, request): """Return a TAL-friendly list of menu items. The object (acts like the context) and request can be used to select the items that are available. """ class IBrowserMenuItem(Interface): """Menu type An interface that defines a menu. """ title = TextLine( title=_("Menu item title"), description=_("The title provides the basic label for the menu item."), required=True ) description = Text( title=_("Menu item description"), description=_("A description of the menu item. This might be shown " "on menu pages or in pop-up help for menu items."), required=False ) action = TextLine( title=_("The URL to display if the item is selected"), description=_("When a user selects a browser menu item, the URL" "given in the action is displayed. The action is " "usually given as a relative URL, relative to the " "object the menu item is for."), required=True ) order = Int( title=_("Menu item ordering hint"), description=_("This attribute provides a hint for menu item ordering." "Menu items will generally be sorted by the `for_`" "attribute and then by the order.") ) filter_string = TextLine( title=_("A condition for displaying the menu item"), description=_("The condition is given as a TALES expression. The " "expression has access to the variables:\n" "\n" "context -- The object the menu is being displayed " "for\n" "\n" "request -- The browser request\n" "\n" "nothing -- None\n" "\n" "The menu item will not be displayed if there is a \n" "filter and the filter evaluates to a false value."), required=False) icon = URI( title=_("Icon URI"), description=_("URI of the icon representing this menu item")) def available(): """Test whether the menu item should be displayed A menu item might not be available for an object, for example due to security limitations or constraints. """ class IBrowserSubMenuItem(IBrowserMenuItem): """A menu item that points to a sub-menu.""" submenuId = TextLine( title=_("Sub-Menu Id"), description=_("The menu id of the menu that describes the " "sub-menu below this item."), required=True) action = TextLine( title=_("The URL to display if the item is selected"), description=_("When a user selects a browser menu item, the URL " "given in the action is displayed. The action is " "usually given as a relative URL, relative to the " "object the menu item is for."), required=False ) class IMenuAccessView(Interface): """View that provides access to menus""" def __getitem__(menu_id): """Get menu information Return a sequence of dictionaries with labels and actions, where actions are relative URLs. """
zope.browsermenu
/zope.browsermenu-5.0.tar.gz/zope.browsermenu-5.0/src/zope/browsermenu/interfaces.py
interfaces.py
============= Browser Menus ============= Browser menus are used to categorize browser actions, such as the views of a content component or the addable components of a container. In essence they provide the same functionality as menu bars in desktop application. >>> from zope.browsermenu import menu, metaconfigure Menus are simple components that have an id, title and description. They also must provide a method called ``getMenuItems(object, request)`` that returns a TAL-friendly list of information dictionaries. We will see this in detail later. The default menu implementation, however, makes the menu be very transparent by identifying the menu through an interface. So let's define and register a simple edit menu: >>> import zope.interface >>> class EditMenu(zope.interface.Interface): ... """This is an edit menu.""" >>> from zope.browsermenu.interfaces import IMenuItemType >>> zope.interface.directlyProvides(EditMenu, IMenuItemType) >>> from zope.component import provideUtility >>> provideUtility(EditMenu, IMenuItemType, 'edit') Now we have to create and register the menu itself: >>> from zope.browsermenu.interfaces import IBrowserMenu >>> provideUtility( ... menu.BrowserMenu('edit', 'Edit', 'Edit Menu'), IBrowserMenu, 'edit') Note that these steps seem like a lot of boilerplate, but all this work is commonly done for you via ZCML. An item in a menu is simply an adapter that provides. In the following section we will have a closer look at the browser menu item: ``BrowserMenuItem`` class ------------------------- The browser menu item represents an entry in the menu. Essentially, the menu item is a browser view of a content component. Thus we have to create a content component first: >>> class IContent(zope.interface.Interface): ... pass >>> from zope.publisher.interfaces.browser import IBrowserPublisher >>> from zope.security.interfaces import Unauthorized, Forbidden >>> @zope.interface.implementer(IContent, IBrowserPublisher) ... class Content(object): ... ... def foo(self): ... pass ... ... def browserDefault(self, r): ... return self, () ... ... def publishTraverse(self, request, name): ... if name.startswith('fb'): ... raise Forbidden(name) ... if name.startswith('ua'): ... raise Unauthorized(name) ... if name.startswith('le'): ... raise LookupError(name) ... return self.foo We also implemented the ``IBrowserPublisher`` interface, because we want to make the object traversable, so that we can make availability checks later. Since the ``BrowserMenuItem`` is just a view, we can initiate it with an object and a request. >>> from zope.publisher.browser import TestRequest >>> item = menu.BrowserMenuItem(Content(), TestRequest()) Note that the menu item knows *nothing* about the menu itself. It purely depends on the adapter registration to determine in which menu it will appear. The advantage is that a menu item can be reused in several menus. Now we add a title, description, order and icon and see whether we can then access the value. Note that these assignments are always automatically done by the framework. >>> item.title = 'Item 1' >>> item.title 'Item 1' >>> item.description = 'This is Item 1.' >>> item.description 'This is Item 1.' >>> item.order 0 >>> item.order = 1 >>> item.order 1 >>> item.icon is None True >>> item.icon = '/@@/icon.png' >>> item.icon '/@@/icon.png' Since there is no permission or view specified yet, the menu item should be available and not selected. >>> item.available() True >>> item.selected() False There are two ways to deny availability of a menu item: (1) the current user does not have the correct permission to access the action or the menu item itself, or (2) the filter returns ``False``, in which case the menu item should also not be shown. >>> from zope.security.interfaces import IPermission >>> from zope.security.permission import Permission >>> perm = Permission('perm', 'Permission') >>> provideUtility(perm, IPermission, 'perm') >>> class ParticipationStub(object): ... principal = 'principal' ... interaction = None In the first case, the permission of the menu item was explicitly specified. Make sure that the user needs this permission to make the menu item available. >>> item.permission = perm Now, we are not setting any user. This means that the menu item should be available. >>> from zope.security.management import newInteraction, endInteraction >>> endInteraction() >>> newInteraction() >>> item.available() True Now we specify a principal that does not have the specified permission. >>> endInteraction() >>> newInteraction(ParticipationStub()) >>> item.available() False In the second case, the permission is not explicitly defined and the availability is determined by the permission required to access the action. >>> item.permission = None All views starting with 'fb' are forbidden, the ones with 'ua' are unauthorized and all others are allowed. >>> item.action = 'fb' >>> item.available() False >>> item.action = 'ua' >>> item.available() False >>> item.action = 'a' >>> item.available() True Also, sometimes a menu item might be registered for a view that does not exist. In those cases the traversal mechanism raises a ``TraversalError``, which is a special type of ``LookupError``. All actions starting with 'le' should raise this error: >>> item.action = 'le' >>> item.available() False Now let's test filtering. If the filter is specified, it is assumed to be a TALES object. >>> from zope.pagetemplate.engine import Engine >>> item.action = 'a' >>> item.filter = Engine.compile('not:context') >>> item.available() False >>> item.filter = Engine.compile('context') >>> item.available() True Finally, make sure that the menu item can be selected. >>> item.request = TestRequest(SERVER_URL='http://127.0.0.1/@@view.html', ... PATH_INFO='/@@view.html') >>> item.selected() False >>> item.action = 'view.html' >>> item.selected() True >>> item.action = '@@view.html' >>> item.selected() True >>> item.request = TestRequest( ... SERVER_URL='http://127.0.0.1/++view++view.html', ... PATH_INFO='/++view++view.html') >>> item.selected() True >>> item.action = 'otherview.html' >>> item.selected() False ``BrowserSubMenuItem`` class ---------------------------- The menu framework also allows for submenus. Submenus can be inserted by creating a special menu item that simply points to another menu to be inserted: >>> item = menu.BrowserSubMenuItem(Content(), TestRequest()) The framework will always set the sub-menu automatically (we do it manually here): >>> class SaveOptions(zope.interface.Interface): ... "A sub-menu that describes available save options for the content." >>> zope.interface.directlyProvides(SaveOptions, IMenuItemType) >>> provideUtility(SaveOptions, IMenuItemType, 'save') >>> provideUtility(menu.BrowserMenu('save', 'Save', 'Save Menu'), ... IBrowserMenu, 'save') Now we can assign the sub-menu id to the menu item: >>> item.submenuId = 'save' Also, the ``action`` attribute for the browser sub-menu item is optional, because you often do not want the item itself to represent something. The rest of the class is identical to the ``BrowserMenuItem`` class. Getting a Menu -------------- Now that we know how the single menu item works, let's have a look at how menu items get put together to a menu. But let's first create some menu items and register them as adapters with the component architecture. Register the edit menu entries first. We use the menu item factory to create the items: >>> from zope.component import provideAdapter >>> from zope.publisher.interfaces.browser import IBrowserRequest >>> undo = metaconfigure.MenuItemFactory(menu.BrowserMenuItem, title="Undo", ... action="undo.html") >>> provideAdapter(undo, (IContent, IBrowserRequest), EditMenu, 'undo') >>> redo = metaconfigure.MenuItemFactory(menu.BrowserMenuItem, title="Redo", ... action="redo.html", icon="/@@/redo.png") >>> provideAdapter(redo, (IContent, IBrowserRequest), EditMenu, 'redo') >>> save = metaconfigure.MenuItemFactory(menu.BrowserSubMenuItem, title="Save", ... submenuId='save', order=2) >>> provideAdapter(save, (IContent, IBrowserRequest), EditMenu, 'save') And now the save options: >>> saveas = metaconfigure.MenuItemFactory(menu.BrowserMenuItem, title="Save as", ... action="saveas.html") >>> provideAdapter(saveas, (IContent, IBrowserRequest), ... SaveOptions, 'saveas') >>> saveall = metaconfigure.MenuItemFactory(menu.BrowserMenuItem, title="Save all", ... action="saveall.html") >>> provideAdapter(saveall, (IContent, IBrowserRequest), ... SaveOptions, 'saveall') Note that we can also register menu items for classes: >>> new = metaconfigure.MenuItemFactory(menu.BrowserMenuItem, title="New", ... action="new.html", _for=Content) >>> provideAdapter(new, (Content, IBrowserRequest), EditMenu, 'new') The utility that is used to generate the menu into a TAL-friendly data-structure is ``getMenu()``:: getMenu(menuId, object, request) where ``menuId`` is the id originally specified for the menu. Let's look up the menu now: >>> pprint(menu.getMenu('edit', Content(), TestRequest())) [{'action': 'new.html', 'description': '', 'extra': None, 'icon': None, 'selected': '', 'submenu': None, 'title': 'New'}, {'action': 'redo.html', 'description': '', 'extra': None, 'icon': '/@@/redo.png', 'selected': '', 'submenu': None, 'title': 'Redo'}, {'action': 'undo.html', 'description': '', 'extra': None, 'icon': None, 'selected': '', 'submenu': None, 'title': 'Undo'}, {'action': '', 'description': '', 'extra': None, 'icon': None, 'selected': '', 'submenu': [{'action': 'saveall.html', 'description': '', 'extra': None, 'icon': None, 'selected': '', 'submenu': None, 'title': 'Save all'}, {'action': 'saveas.html', 'description': '', 'extra': None, 'icon': None, 'selected': '', 'submenu': None, 'title': 'Save as'}], 'title': 'Save'}] Custom ``IBrowserMenu`` Implementations --------------------------------------- Until now we have only seen how to use the default menu implementation. Much of the above boilerplate was necessary just to support custom menus. But what could custom menus do? Sometimes menu items are dynamically generated based on a certain state of the object the menu is for. For example, you might want to show all items in a folder-like component. So first let's create this folder-like component: >>> class Folderish(Content): ... names = ['README.txt', 'logo.png', 'script.py'] Now we create a menu using the names to create a menu: >>> from zope.browsermenu.interfaces import IBrowserMenu >>> @zope.interface.implementer(IBrowserMenu) ... class Items(object): ... ... def __init__(self, id, title='', description=''): ... self.id = id ... self.title = title ... self.description = description ... ... def getMenuItems(self, object, request): ... return [{'title': name, ... 'description': None, ... 'action': name + '/manage', ... 'selected': '', ... 'icon': None, ... 'extra': {}, ... 'submenu': None} ... for name in object.names] and register it: >>> provideUtility(Items('items', 'Items', 'Items Men'), ... IBrowserMenu, 'items') We can now get the menu items using the previously introduced API: >>> pprint(menu.getMenu('items', Folderish(), TestRequest())) [{'action': 'README.txt/manage', 'description': None, 'extra': {}, 'icon': None, 'selected': '', 'submenu': None, 'title': 'README.txt'}, {'action': 'logo.png/manage', 'description': None, 'extra': {}, 'icon': None, 'selected': '', 'submenu': None, 'title': 'logo.png'}, {'action': 'script.py/manage', 'description': None, 'extra': {}, 'icon': None, 'selected': '', 'submenu': None, 'title': 'script.py'}] ``MenuItemFactory`` class ------------------------- As you have seen above already, we have used the menu item factory to generate adapter factories for menu items. The factory needs a particular ``IBrowserMenuItem`` class to instantiate. Here is an example using a dummy menu item class: >>> class DummyBrowserMenuItem(object): ... "a dummy factory for menu items" ... def __init__(self, context, request): ... self.context = context ... self.request = request To instantiate this class, pass the factory and the other arguments as keyword arguments (every key in the arguments should map to an attribute of the menu item class). We use dummy values for this example. >>> factory = metaconfigure.MenuItemFactory( ... DummyBrowserMenuItem, title='Title', description='Description', ... icon='Icon', action='Action', filter='Filter', ... permission='zope.Public', extra='Extra', order='Order', _for='For') >>> factory.factory is DummyBrowserMenuItem True The "zope.Public" permission needs to be translated to ``CheckerPublic``. >>> from zope.security.checker import CheckerPublic >>> factory.kwargs['permission'] is CheckerPublic True Call the factory with context and request to return the instance. We continue to use dummy values. >>> item = factory('Context', 'Request') The returned value should be an instance of the ``DummyBrowserMenuItem``, and have all of the values we initially set on the factory. >>> isinstance(item, DummyBrowserMenuItem) True >>> item.context 'Context' >>> item.request 'Request' >>> item.title 'Title' >>> item.description 'Description' >>> item.icon 'Icon' >>> item.action 'Action' >>> item.filter 'Filter' >>> item.permission is CheckerPublic True >>> item.extra 'Extra' >>> item.order 'Order' >>> item._for 'For' If you pass a permission other than ``zope.Public`` to the ``MenuItemFactory``, it should pass through unmodified. >>> factory = metaconfigure.MenuItemFactory( ... DummyBrowserMenuItem, title='Title', description='Description', ... icon='Icon', action='Action', filter='Filter', ... permission='another.Permission', extra='Extra', order='Order', ... _for='For_') >>> factory.kwargs['permission'] 'another.Permission' Directive Handlers ------------------ ``menu`` Directive Handler ~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides a new menu (item type). >>> class Context(object): ... info = 'doc' ... def __init__(self): ... self.actions = [] ... ... def action(self, **kw): ... self.actions.append(kw) Possibility 1: The Old Way ++++++++++++++++++++++++++ >>> context = Context() >>> metaconfigure.menuDirective(context, 'menu1', title='Menu 1') >>> iface = context.actions[0]['args'][1] >>> iface.getName() 'menu1' >>> import sys >>> hasattr(sys.modules['zope.app.menus'], 'menu1') True >>> del sys.modules['zope.app.menus'].menu1 Possibility 2: Just specify an interface ++++++++++++++++++++++++++++++++++++++++ >>> class menu1(zope.interface.Interface): ... pass >>> context = Context() >>> metaconfigure.menuDirective(context, interface=menu1) >>> context.actions[0]['args'][1] is menu1 True Possibility 3: Specify an interface and an id +++++++++++++++++++++++++++++++++++++++++++++ >>> context = Context() >>> metaconfigure.menuDirective(context, id='menu1', interface=menu1) >>> pprint([action['discriminator'] for action in context.actions]) [('browser', 'MenuItemType', 'builtins.menu1'), ('interface', 'builtins.menu1'), ('browser', 'MenuItemType', 'menu1'), ('utility', <InterfaceClass zope.browsermenu.interfaces.IBrowserMenu>, 'menu1'), None] Here are some disallowed configurations. >>> context = Context() >>> metaconfigure.menuDirective(context) Traceback (most recent call last): ... zope.configuration.exceptions.ConfigurationError: You must specify the 'id' or 'interface' attribute. >>> metaconfigure.menuDirective(context, title='Menu 1') Traceback (most recent call last): ... zope.configuration.exceptions.ConfigurationError: You must specify the 'id' or 'interface' attribute. ``menuItems`` Directive Handler ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Register several menu items for a particular menu. >>> class TestMenuItemType(zope.interface.Interface): ... pass >>> class ITest(zope.interface.Interface): ... pass >>> context = Context() >>> items = metaconfigure.menuItemsDirective(context, TestMenuItemType, ITest) >>> context.actions [] >>> items.menuItem(context, 'view.html', 'View') >>> items.subMenuItem(context, SaveOptions, 'Save') >>> disc = sorted([action['discriminator'] for action in context.actions ... if action['discriminator'] is not None]) >>> pprint(disc[-2:]) [('adapter', (<InterfaceClass builtins.ITest>, <InterfaceClass zope.publisher.interfaces.browser.IDefaultBrowserLayer>), <InterfaceClass builtins.TestMenuItemType>, 'Save'), ('adapter', (<InterfaceClass builtins.ITest>, <InterfaceClass zope.publisher.interfaces.browser.IDefaultBrowserLayer>), <InterfaceClass builtins.TestMenuItemType>, 'View')] Custom menu item classes ~~~~~~~~~~~~~~~~~~~~~~~~ We can register menu items and sub menu items with custom classes instead of ones used by default. For that, we need to create an implementation of ``IBrowserMenuItem`` or ``IBrowserSubMenuItem``. >>> context = Context() >>> items = metaconfigure.menuItemsDirective(context, TestMenuItemType, ITest) >>> context.actions [] Let's create a custom menu item class that inherits standard ``BrowserMenuItem``: >>> class MyMenuItem(menu.BrowserMenuItem): ... pass >>> items.menuItem(context, 'view.html', 'View', item_class=MyMenuItem) Also create a custom sub menu item class inheriting standard ``BrowserSubMenuItem``: >>> class MySubMenuItem(menu.BrowserSubMenuItem): ... pass >>> items.subMenuItem(context, SaveOptions, 'Save', item_class=MySubMenuItem) >>> actions = sorted(context.actions, key=lambda a:a['discriminator'] or ()) >>> factories = [action['args'][1] for action in actions][-2:] >>> factories[0].factory is MySubMenuItem True >>> factories[1].factory is MyMenuItem True These directive will fail if you provide an item_class that does not implement ``IBrowserMenuItem``/``IBrowserSubMenuItem``: >>> items.menuItem(context, 'fail', 'Failed', item_class=object) Traceback (most recent call last): ... ValueError: Item class (<class 'object'>) must implement IBrowserMenuItem >>> items.subMenuItem(context, SaveOptions, 'Failed', item_class=object) Traceback (most recent call last): ... ValueError: Item class (<class 'object'>) must implement IBrowserSubMenuItem
zope.browsermenu
/zope.browsermenu-5.0.tar.gz/zope.browsermenu-5.0/src/zope/browsermenu/README.txt
README.txt
"""Menu implementation code """ import sys from zope.component import getAdapters from zope.component import getUtility from zope.interface import Interface from zope.interface import implementer from zope.interface import providedBy from zope.interface.interfaces import IInterface from zope.pagetemplate.engine import Engine from zope.publisher.browser import BrowserView from zope.security import canAccess from zope.security import checkPermission from zope.security.interfaces import Forbidden from zope.security.interfaces import Unauthorized from zope.security.proxy import removeSecurityProxy from zope.traversing.publicationtraverse import PublicationTraverser from zope.browsermenu.interfaces import IBrowserMenu from zope.browsermenu.interfaces import IBrowserMenuItem from zope.browsermenu.interfaces import IBrowserSubMenuItem from zope.browsermenu.interfaces import IMenuAccessView from zope.browsermenu.interfaces import IMenuItemType @implementer(IBrowserMenu) class BrowserMenu: """Browser Menu""" def __init__(self, id, title='', description=''): self.id = id self.title = title self.description = description def getMenuItemType(self): return getUtility(IMenuItemType, self.id) def getMenuItems(self, object, request): """Return menu item entries in a TAL-friendly form.""" result = [] for _name, item in getAdapters((object, request), self.getMenuItemType()): if item.available(): result.append(item) # Now order the result. This is not as easy as it seems. # # (1) Look at the interfaces and put the more specific menu entries # to the front. # (2) Sort unambigious entries by order and then by title. ifaces = list(providedBy(removeSecurityProxy(object)).__iro__) max_key = len(ifaces) def iface_index(item): iface = item._for or Interface if IInterface.providedBy(iface): return ifaces.index(iface) if isinstance(removeSecurityProxy(object), item._for): # directly specified for class, this goes first. return -1 # no idea. This goes last. return max_key # pragma: no cover result = [(iface_index(item), item.order, item.title, item) for item in result] result.sort() result = [ {'title': title, 'description': item.description, 'action': item.action, 'selected': (item.selected() and 'selected') or '', 'icon': item.icon, 'extra': item.extra, 'submenu': (IBrowserSubMenuItem.providedBy(item) and getMenu(item.submenuId, object, request)) or None} for index, order, title, item in result] return result @implementer(IBrowserMenuItem) class BrowserMenuItem(BrowserView): """Browser Menu Item Class""" title = '' description = '' action = '' extra = None order = 0 permission = None filter = None icon = None _for = Interface def available(self): # Make sure we have the permission needed to access the menu's action if self.permission is not None: # If we have an explicit permission, check that we # can access it. if not checkPermission(self.permission, self.context): return False elif self.action != '': # Otherwise, test access by attempting access path = self.action pos = self.action.find('?') if pos >= 0: path = self.action[:pos] traverser = PublicationTraverser() try: view = traverser.traverseRelativeURL( self.request, self.context, path) except (Unauthorized, Forbidden, LookupError): return False else: # we're assuming that view pages are callable # this is a pretty sound assumption if not canAccess(view, '__call__'): return False # pragma: no cover # Make sure that we really want to see this menu item if self.filter is not None: try: include = self.filter(Engine.getContext( context=self.context, nothing=None, request=self.request, modules=sys.modules, )) except Unauthorized: return False else: if not include: return False return True def selected(self): request_url = self.request.getURL() normalized_action = self.action if self.action.startswith('@@'): normalized_action = self.action[2:] if request_url.endswith('/' + normalized_action): return True if request_url.endswith('/++view++' + normalized_action): return True if request_url.endswith('/@@' + normalized_action): return True return False @implementer(IBrowserSubMenuItem) class BrowserSubMenuItem(BrowserMenuItem): """Browser Menu Item Base Class""" submenuId = None def selected(self): if self.action == '': return False else: return super().selected() def getMenu(id, object, request): """Return menu item entries in a TAL-friendly form.""" menu = getUtility(IBrowserMenu, id) return menu.getMenuItems(object, request) def getFirstMenuItem(id, object, request): """Get the first item of a menu.""" items = getMenu(id, object, request) if items: return items[0] return None @implementer(IMenuAccessView) class MenuAccessView(BrowserView): """A view allowing easy access to menus.""" def __getitem__(self, menuId): return getMenu(menuId, self.context, self.request)
zope.browsermenu
/zope.browsermenu-5.0.tar.gz/zope.browsermenu-5.0/src/zope/browsermenu/menu.py
menu.py
"""Menu ZCML directives """ from zope.configuration.fields import GlobalInterface from zope.configuration.fields import GlobalObject from zope.configuration.fields import MessageID from zope.interface import Interface from zope.schema import Id from zope.schema import Int from zope.schema import TextLine from zope.security.zcml import Permission from zope.browsermenu.field import MenuField class IMenuDirective(Interface): """Define a browser menu""" id = TextLine( title="The name of the menu.", description="This is, effectively, an id.", required=False ) title = MessageID( title="Title", description="A descriptive title for documentation purposes", required=False ) description = MessageID( title="Description", description="A description title of the menu.", required=False ) class_ = GlobalObject( title="Menu Class", description="The menu class used to generate the menu.", required=False ) interface = GlobalInterface( title="The menu's interface.", required=False ) class IMenuItemsDirective(Interface): """ Define a group of browser menu items This directive is useful when many menu items are defined for the same interface and menu. """ menu = MenuField( title="Menu name", description="The (name of the) menu the items are defined for", required=True, ) for_ = GlobalObject( title="Interface", description="The interface the menu items are defined for", required=True ) layer = GlobalInterface( title="Layer", description="The Layer for which the item is declared.", required=False ) permission = Permission( title="The permission needed access the item", description=""" This can usually be inferred by the system, however, doing so may be expensive. When displaying a menu, the system tries to traverse to the URLs given in each action to determine whether the url is accessible to the current user. This can be avoided if the permission is given explicitly.""", required=False ) class IMenuItem(Interface): """Common menu item configuration """ title = MessageID( title="Title", description="The text to be displayed for the menu item", required=True ) description = MessageID( title="A longer explanation of the menu item", description=""" A UI may display this with the item or display it when the user requests more assistance.""", required=False ) icon = TextLine( title="Icon Path", description="Path to the icon resource representing this menu item.", required=False ) permission = Permission( title="The permission needed access the item", description=""" This can usually be inferred by the system, however, doing so may be expensive. When displaying a menu, the system tries to traverse to the URLs given in each action to determine whether the url is accessible to the current user. This can be avoided if the permission is given explicitly.""", required=False ) filter = TextLine( title="A condition for displaying the menu item", description=""" The condition is given as a TALES expression. The expression has access to the variables: context -- The object the menu is being displayed for request -- The browser request nothing -- None The menu item will not be displayed if there is a filter and the filter evaluates to a false value.""", required=False ) order = Int( title="Order", description="A relative position of the menu item in the menu.", required=False, default=0 ) item_class = GlobalObject( title="Menu item class", description=""" A class to be used as a factory for creating menu item""", required=False ) class IMenuItemSubdirective(IMenuItem): """Define a menu item within a group of menu items""" action = TextLine( title="The relative url to use if the item is selected", description=""" The url is relative to the object the menu is being displayed for.""", required=True ) class IMenuItemDirective(IMenuItemsDirective, IMenuItemSubdirective): """Define one menu item""" class ISubMenuItemSubdirective(IMenuItem): """Define a menu item that represents a a sub menu. For a sub-menu menu item, the action is optional, this the item itself might not represent a destination, but just an entry point to the sub menu. """ action = TextLine( title="The relative url to use if the item is selected", description=""" The url is relative to the object the menu is being displayed for.""", required=False ) submenu = TextLine( title="Sub-Menu Id", description="The menu that will be used to provide the sub-entries.", required=True, ) class ISubMenuItemDirective(IMenuItemsDirective, ISubMenuItemSubdirective): """Define one menu item""" class IAddMenuItemDirective(IMenuItem): """Define an add-menu item""" for_ = GlobalInterface( title="Interface", description="The interface the menu items are defined for", required=False ) class_ = GlobalObject( title="Class", description=""" A class to be used as a factory for creating new objects""", required=False ) factory = Id( title="Factory", description="A factory id for creating new objects", required=False, ) view = TextLine( title="Custom view name", description="The name of a custom add view", required=False, ) menu = MenuField( title="Menu name", description="The (name of the) menu the items are defined for", required=False, ) layer = GlobalInterface( title="The layer the custom view is declared for", description="The default layer for which the custom view is " "applicable. By default it is applied to all layers.", required=False )
zope.browsermenu
/zope.browsermenu-5.0.tar.gz/zope.browsermenu-5.0/src/zope/browsermenu/metadirectives.py
metadirectives.py
"""Menu Directives Configuration Handlers """ import sys # Create special modules that contain all menu item types from types import ModuleType as module from zope.browser.interfaces import IAdding from zope.component import getGlobalSiteManager from zope.component import queryUtility from zope.component.interface import provideInterface from zope.component.zcml import adapter from zope.component.zcml import proxify from zope.component.zcml import utility from zope.configuration.exceptions import ConfigurationError from zope.interface import Interface from zope.interface.interface import InterfaceClass from zope.pagetemplate.engine import Engine from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.security.checker import CheckerPublic from zope.security.checker import InterfaceChecker from zope.security.metaconfigure import ClassDirective from zope.browsermenu.interfaces import AddMenu from zope.browsermenu.interfaces import IBrowserMenu from zope.browsermenu.interfaces import IBrowserMenuItem from zope.browsermenu.interfaces import IBrowserSubMenuItem from zope.browsermenu.interfaces import IMenuItemType from zope.browsermenu.menu import BrowserMenu from zope.browsermenu.menu import BrowserMenuItem from zope.browsermenu.menu import BrowserSubMenuItem try: import zope.app # noqa: F401 (unused symbol) except ImportError: # we don't always have zope.app now sys.modules['zope.app'] = module('app') menus = module('menus') sys.modules['zope.app.menus'] = menus _order_counter = {} def menuDirective(_context, id=None, class_=BrowserMenu, interface=None, title='', description=''): """Register a new browser menu.""" if id is None and interface is None: raise ConfigurationError( "You must specify the 'id' or 'interface' attribute.") if interface is None: if id in dir(menus): # reuse existing interfaces for the id, without this we are not # able to override menus. interface = getattr(menus, id) else: interface = InterfaceClass(id, (), __doc__='Menu Item Type: %s' % id, __module__='zope.app.menus') # Add the menu item type to the `menus` module. # Note: We have to do this immediately, so that directives using # the MenuField can find the menu item type. setattr(menus, id, interface) path = 'zope.app.menus.' + id else: path = interface.__module__ + '.' + interface.getName() # If an id was specified, make this menu available under this id. # Note that the menu will be still available under its path, since it # is an adapter, and the `MenuField` can resolve paths as well. if id is None: id = path else: # Make the interface available in the `zope.app.menus` module, so # that other directives can find the interface under the name # before the CA is setup. _context.action( discriminator=('browser', 'MenuItemType', path), callable=provideInterface, args=(path, interface, IMenuItemType, _context.info) ) setattr(menus, id, interface) # Register the layer interface as an interface _context.action( discriminator=('interface', path), callable=provideInterface, args=(path, interface), kw={'info': _context.info} ) # Register the menu item type interface as an IMenuItemType _context.action( discriminator=('browser', 'MenuItemType', id), callable=provideInterface, args=(id, interface, IMenuItemType, _context.info) ) # Register the menu as a utility utility(_context, IBrowserMenu, class_(id, title, description), name=id) def menuItemDirective(_context, menu, for_, action, title, description='', icon=None, filter=None, permission=None, layer=IDefaultBrowserLayer, extra=None, order=0, item_class=None): """Register a single menu item.""" return menuItemsDirective(_context, menu, for_, layer).menuItem( _context, action, title, description, icon, filter, permission, extra, order, item_class) def subMenuItemDirective(_context, menu, for_, title, submenu, action='', description='', icon=None, filter=None, permission=None, layer=IDefaultBrowserLayer, extra=None, order=0, item_class=None): """Register a single sub-menu menu item.""" return menuItemsDirective(_context, menu, for_, layer).subMenuItem( _context, submenu, title, description, action, icon, filter, permission, extra, order, item_class) class MenuItemFactory: """generic factory for menu items.""" def __init__(self, factory, **kwargs): self.factory = factory if 'permission' in kwargs and kwargs['permission'] == 'zope.Public': kwargs['permission'] = CheckerPublic self.kwargs = kwargs def __call__(self, context, request): item = self.factory(context, request) for key, value in self.kwargs.items(): setattr(item, key, value) if item.permission is not None: checker = InterfaceChecker(IBrowserMenuItem, item.permission) item = proxify(item, checker) return item class menuItemsDirective: """Register several menu items for a particular menu.""" menuItemClass = BrowserMenuItem subMenuItemClass = BrowserSubMenuItem def __init__(self, _context, menu, for_, layer=IDefaultBrowserLayer, permission=None): self.for_ = for_ self.menuItemType = menu self.layer = layer self.permission = permission def menuItem(self, _context, action, title, description='', icon=None, filter=None, permission=None, extra=None, order=0, item_class=None): if filter is not None: filter = Engine.compile(filter) if permission is None: permission = self.permission if order == 0: order = _order_counter.get(self.for_, 1) _order_counter[self.for_] = order + 1 if item_class is None: item_class = self.menuItemClass if not IBrowserMenuItem.implementedBy(item_class): raise ValueError( "Item class (%s) must implement IBrowserMenuItem" % item_class) factory = MenuItemFactory( item_class, title=title, description=description, icon=icon, action=action, filter=filter, permission=permission, extra=extra, order=order, _for=self.for_) adapter(_context, (factory,), self.menuItemType, (self.for_, self.layer), name=title) def subMenuItem(self, _context, submenu, title, description='', action='', icon=None, filter=None, permission=None, extra=None, order=0, item_class=None): filter = Engine.compile(filter) if filter is not None else None if permission is None: permission = self.permission if order == 0: order = _order_counter.get(self.for_, 1) _order_counter[self.for_] = order + 1 if item_class is None: item_class = self.subMenuItemClass if not IBrowserSubMenuItem.implementedBy(item_class): raise ValueError( "Item class (%s) must implement IBrowserSubMenuItem" % item_class) factory = MenuItemFactory( item_class, title=title, description=description, icon=icon, action=action, filter=filter, permission=permission, extra=extra, order=order, _for=self.for_, submenuId=submenu) adapter(_context, (factory,), self.menuItemType, (self.for_, self.layer), name=title) def __call__(self, _context): """See menuItem or subMenuItem.""" def _checkViewFor(for_=None, layer=None, view_name=None): """Check if there is a view of that name registered for IAdding and IBrowserRequest. If not raise a ConfigurationError It will raise a ConfigurationError if : o view="" o if view_name is not registred """ if view_name is None: raise ConfigurationError( "Within a addMenuItem directive the view attribute" " is optional but can\'t be empty" ) gsm = getGlobalSiteManager() if gsm.adapters.lookup((for_, layer), Interface, view_name) is None: raise ConfigurationError( "view name %s not found " % view_name ) def addMenuItem(_context, title, description='', menu=None, for_=None, class_=None, factory=None, view=None, icon=None, filter=None, permission=None, layer=IDefaultBrowserLayer, extra=None, order=0, item_class=None): """Create an add menu item for a given class or factory As a convenience, a class can be provided, in which case, a factory is automatically defined based on the class. In this case, the factory id is based on the class name. """ if for_ is not None: _context.action( discriminator=None, callable=provideInterface, args=('', for_) ) forname = 'For' + for_.getName() else: for_ = IAdding forname = '' if menu is not None: if isinstance(menu, str): menu_name = menu menu = queryUtility(IMenuItemType, menu) if menu is None: raise ValueError("Missing menu id '%s'" % menu_name) if class_ is None: if factory is None: raise ValueError("Must specify either class or factory") else: if factory is not None: raise ValueError("Can't specify both class and factory") if permission is None: raise ValueError( "A permission must be specified when a class is used") factory = "BrowserAdd{}__{}.{}".format( forname, class_.__module__, class_.__name__) ClassDirective(_context, class_).factory(_context, id=factory) extra = {'factory': factory} if view: action = view # This action will check if the view exists _context.action( discriminator=None, callable=_checkViewFor, args=(for_, layer, view), order=999999 ) else: action = factory if menu is None: menu = AddMenu return menuItemsDirective(_context, menu, for_, layer=layer).menuItem( _context, action, title, description, icon, filter, permission, extra, order, item_class)
zope.browsermenu
/zope.browsermenu-5.0.tar.gz/zope.browsermenu-5.0/src/zope/browsermenu/metaconfigure.py
metaconfigure.py
========= Changes ========= 5.0 (2023-01-19) ================ - Drop support for Python 2.7, 3.5, 3.6. - Add support for Python 3.8, 3.9, 3.10, 3.11. - Drop support for running the tests using ``python setup.py test``. (`#11 <https://github.com/zopefoundation/zope.browserpage/issues/11>`_) 4.4.0 (2019-06-18) ================== - Fix regression in ``allowed_attributes`` and ``allowed_interface``. (`#7 <https://github.com/zopefoundation/zope.browserpage/pull/7>`_) - Drop support for Python 3.4. 4.3.0 (2018-10-05) ================== - Add support for Python 3.7. 4.2.0 (2017-08-02) ================== - Add support for Python 3.5 and 3.6. - Drop support for Python 2.6 and 3.3. 4.1.0 (2014-12-24) ================== - Fix deprecated unittest methods. - Add explicit support for Python 3.4. - Add explicit support for PyPy. 4.1.0a1 (2013-02-22) ==================== - Add support for Python 3.3. 4.0.0 (2012-07-04) ================== - When registering views, no longer pass the deprecated 'layer' agrument to ``zope.component.registerAdapter``. Instead, pass ``(for_, layer)`` as expected (forward-compatibility with ``zope.component`` 4.0.0). - Replace deprecated ``zope.interface.implements`` usage with equivalent ``zope.interface.implementer`` decorator. - Drop support for Python 2.4 and 2.5. 3.12.2 (2010-05-24) =================== - Fix unit tests broken under Python 2.4 by the switch to the standard library ``doctest`` module. 3.12.1 (2010-04-30) =================== - Prefer the standard library's ``doctest`` module to the one from ``zope.testing``. 3.12.0 (2010-04-26) =================== - Move the implementation of ``tales:expressiontype`` here from ``zope.app.pagetemplate``. 3.11.0 (2009-12-22) =================== - Move the named template implementation here from ``zope.app.pagetemplate``. 3.10.1 (2009-12-22) =================== - Depend on the ``untrustedpython`` extra of ``zope.security``, since we import from ``zope.pagetemplate.engine``. 3.10.0 (2009-12-22) =================== - Remove the dependency on ``zope.app.pagetemplate`` by moving ``viewpagetemplatefile``, ``simpleviewclass`` and ``metaconfigure.registerType`` into this package. 3.9.0 (2009-08-27) ================== - Initial release. This package was split off from ``zope.app.publisher``.
zope.browserpage
/zope.browserpage-5.0.tar.gz/zope.browserpage-5.0/CHANGES.rst
CHANGES.rst
====================== ``zope.browserpage`` ====================== .. image:: https://img.shields.io/pypi/v/zope.browserpage.svg :target: https://pypi.python.org/pypi/zope.browserpage/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.browserpage.svg :target: https://pypi.org/project/zope.browserpage/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.browserpage/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.browserpage/actions/workflows/tests.yml .. image:: https://coveralls.io/repos/github/zopefoundation/zope.browserpage/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.browserpage?branch=master .. note:: This package is at present not reusable without depending on a large chunk of the Zope Toolkit and its assumptions. It is maintained by the `Zope Toolkit project <http://docs.zope.org/zopetoolkit/>`_. This package provides ZCML directives for configuring browser views. More specifically it defines the following ZCML directives: - ``browser:page`` - ``browser:pages`` - ``browser:view`` These directives also support menu item registration for pages, when ``zope.browsermenu`` package is installed. Otherwise, they simply ignore the menu attribute.
zope.browserpage
/zope.browserpage-5.0.tar.gz/zope.browserpage-5.0/README.rst
README.rst
"""File-based page templates that can be used as methods on views. """ __docformat__ = 'restructuredtext' from zope.component import getMultiAdapter from zope.pagetemplate.engine import TrustedAppPT from zope.pagetemplate.pagetemplatefile import PageTemplateFile class ViewPageTemplateFile(TrustedAppPT, PageTemplateFile): """Page Templates used as methods of views defined as Python classes. """ def __init__(self, filename, _prefix=None, content_type=None): _prefix = self.get_path_from_prefix(_prefix) super().__init__(filename, _prefix) if content_type is not None: self.content_type = content_type def pt_getContext(self, instance, request, **_kw): # instance is a View component namespace = super().pt_getContext(**_kw) namespace['request'] = request namespace['view'] = instance namespace['context'] = context = instance.context namespace['views'] = ViewMapper(context, request) return namespace def __call__(self, instance, *args, **keywords): namespace = self.pt_getContext( request=instance.request, instance=instance, args=args, options=keywords) debug_flags = instance.request.debug s = self.pt_render( namespace, showtal=getattr(debug_flags, 'showTAL', 0), sourceAnnotations=getattr(debug_flags, 'sourceAnnotations', 0), ) response = instance.request.response if not response.getHeader("Content-Type"): response.setHeader("Content-Type", self.content_type) return s def __get__(self, instance, type): return BoundPageTemplate(self, instance) class ViewMapper: def __init__(self, ob, request): self.ob = ob self.request = request def __getitem__(self, name): return getMultiAdapter((self.ob, self.request), name=name) class BoundPageTemplate: def __init__(self, pt, ob): object.__setattr__(self, '__func__', pt) object.__setattr__(self, '__self__', ob) macros = property(lambda self: self.__func__.macros) filename = property(lambda self: self.__func__.filename) def __call__(self, *args, **kw): if self.__self__ is None: im_self, args = args[0], args[1:] else: im_self = self.__self__ return self.__func__(im_self, *args, **kw) def __setattr__(self, name, v): raise AttributeError("Can't set attribute", name) def __repr__(self): return "<BoundPageTemplateFile of %r>" % self.__self__ def NoTraverser(ob, request): return None
zope.browserpage
/zope.browserpage-5.0.tar.gz/zope.browserpage-5.0/src/zope/browserpage/viewpagetemplatefile.py
viewpagetemplatefile.py
=============== Named Templates =============== We often want to be able to define view logic and view templates independently. We'd like to be able to change the template used by a form without being forced to modify the form. Named templates provide templates that are registered as named view adapters. To define a named template, use the `NamedTemplateImplementation` constructor: >>> from zope.browserpage import ViewPageTemplateFile >>> from zope.browserpage.namedtemplate import ( ... NamedTemplateImplementation) >>> sample = ViewPageTemplateFile('tests/namedtemplate.pt') >>> sample = NamedTemplateImplementation(sample) Let's define a view that uses the named template. To use a named template, use the NamedTemplate constructor, and give a template name: >>> from zope.browserpage.namedtemplate import NamedTemplate >>> class MyView: ... def __init__(self, context, request): ... self.context = context ... self.request = request ... ... __call__ = NamedTemplate('sample') Normally, we'd register a named template for a view interface, to allow it to be registered for multiple views. We'll just register it for our view class. >>> from zope import component >>> component.provideAdapter(sample, [MyView], name='sample') Now, with this in place, we should be able to use our view: >>> class MyContent: ... def __init__(self, name): ... self.name = name >>> from zope.publisher.browser import TestRequest >>> view = MyView(MyContent('bob'), TestRequest()) >>> print(view(x=42).replace('\r\n', '\n')) <html><body> Hello bob The URL is http://127.0.0.1 The positional arguments were () The keyword argument x is 42 </body></html> <BLANKLINE> The view type that a named template is to be used for can be supplied when the named template is created: >>> class MyView: ... def __init__(self, context, request): ... self.context = context ... self.request = request ... ... __call__ = NamedTemplate('sample2') >>> sample = ViewPageTemplateFile('tests/namedtemplate.pt') >>> sample = NamedTemplateImplementation(sample, MyView) >>> component.provideAdapter(sample, name='sample2') >>> view = MyView(MyContent('bob'), TestRequest()) >>> print(view(x=42).replace('\r\n', '\n')) <html><body> Hello bob The URL is http://127.0.0.1 The positional arguments were () The keyword argument x is 42 </body></html> <BLANKLINE>
zope.browserpage
/zope.browserpage-5.0.tar.gz/zope.browserpage-5.0/src/zope/browserpage/namedtemplate.rst
namedtemplate.rst
"""ZCML directives for defining browser pages """ from zope.component.zcml import IBasicViewInformation from zope.configuration.fields import GlobalInterface from zope.configuration.fields import GlobalObject from zope.configuration.fields import MessageID from zope.configuration.fields import Path from zope.configuration.fields import PythonIdentifier from zope.interface import Interface from zope.schema import TextLine from zope.security.zcml import Permission try: from zope.browsermenu.field import MenuField except ImportError: # pragma: no cover # avoid hard dependency on zope.browsermenu MenuField = TextLine class IPagesDirective(IBasicViewInformation): """ Define multiple pages without repeating all of the parameters. The pages directive allows multiple page views to be defined without repeating the 'for', 'permission', 'class', 'layer', 'allowed_attributes', and 'allowed_interface' attributes. """ for_ = GlobalObject( title="The interface or class this view is for.", required=False ) layer = GlobalObject( title="The request interface or class this view is for.", description="Defaults to " "zope.publisher.interfaces.browser.IDefaultBrowserLayer.", required=False ) permission = Permission( title="Permission", description="The permission needed to use the view.", required=True ) class IViewDirective(IPagesDirective): """ The view directive defines a view that has subpages. The pages provided by the defined view are accessed by first traversing to the view name and then traversing to the page name. """ for_ = GlobalInterface( title="The interface this view is for.", required=False ) name = TextLine( title="The name of the view.", description="The name shows up in URLs/paths. For example 'foo'.", required=False, default='', ) menu = MenuField( title="The browser menu to include the page (view) in.", description=""" Many views are included in menus. It's convenient to name the menu in the page directive, rather than having to give a separate menuItem directive. 'zmi_views' is the menu most often used in the Zope management interface. This attribute will only work if zope.browsermenu is installed. """, required=False ) title = MessageID( title="The browser menu label for the page (view)", description=""" This attribute must be supplied if a menu attribute is supplied. This attribute will only work if zope.browsermenu is installed. """, required=False ) provides = GlobalInterface( title="The interface this view provides.", description=""" A view can provide an interface. This would be used for views that support other views.""", required=False, default=Interface, ) class IViewPageSubdirective(Interface): """ Subdirective to IViewDirective. """ name = TextLine( title="The name of the page (view)", description=""" The name shows up in URLs/paths. For example 'foo' or 'foo.html'. This attribute is required unless you use the subdirective 'page' to create sub views. If you do not have sub pages, it is common to use an extension for the view name such as '.html'. If you do have sub pages and you want to provide a view name, you shouldn't use extensions.""", required=True ) attribute = PythonIdentifier( title="The name of the view attribute implementing the page.", description=""" This refers to the attribute (method) on the view that is implementing a specific sub page.""", required=False ) template = Path( title="The name of a template that implements the page.", description=""" Refers to a file containing a page template (should end in extension '.pt' or '.html').""", required=False ) class IViewDefaultPageSubdirective(Interface): """ Subdirective to IViewDirective. """ name = TextLine( title="The name of the page that is the default.", description=""" The named page will be used as the default if no name is specified explicitly in the path. If no defaultPage directive is supplied, the default page will be the first page listed.""", required=True ) class IPagesPageSubdirective(IViewPageSubdirective): """ Subdirective to IPagesDirective """ menu = MenuField( title="The browser menu to include the page (view) in.", description=""" Many views are included in menus. It's convenient to name the menu in the page directive, rather than having to give a separate menuItem directive. This attribute will only work if zope.browsermenu is installed. """, required=False ) title = MessageID( title="The browser menu label for the page (view)", description=""" This attribute must be supplied if a menu attribute is supplied. This attribute will only work if zope.browsermenu is installed. """, required=False ) class IPageDirective(IPagesDirective, IPagesPageSubdirective): """ The page directive is used to create views that provide a single url or page. The page directive creates a new view class from a given template and/or class and registers it. """ class IExpressionTypeDirective(Interface): """Register a new TALES expression type""" name = TextLine( title="Name", description="""Name of the expression. This will also be used as the prefix in actual TALES expressions.""", required=True ) handler = GlobalObject( title="Handler", description="""Handler is class that implements zope.tales.interfaces.ITALESExpression.""", required=True )
zope.browserpage
/zope.browserpage-5.0.tar.gz/zope.browserpage-5.0/src/zope/browserpage/metadirectives.py
metadirectives.py
"""Browser page ZCML configuration code """ import os from zope.component import queryMultiAdapter from zope.component.interface import provideInterface from zope.component.zcml import handler from zope.configuration.exceptions import ConfigurationError from zope.interface import Interface from zope.interface import classImplements from zope.interface import implementer from zope.pagetemplate.engine import Engine from zope.pagetemplate.engine import TrustedEngine from zope.pagetemplate.engine import _Engine from zope.pagetemplate.engine import _TrustedEngine from zope.publisher.browser import BrowserView from zope.publisher.interfaces import NotFound from zope.publisher.interfaces.browser import IBrowserPublisher from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.security.checker import Checker from zope.security.checker import CheckerPublic from zope.security.checker import defineChecker from zope.browserpage.simpleviewclass import SimpleViewClass from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile def _fallbackMenuItemDirective(_context, *args, **kwargs): import warnings warnings.warn_explicit( 'Page directive used with "menu" argument, while "zope.browsermenu" ' 'package is not installed. Doing nothing.', UserWarning, _context.info.file, _context.info.line) return [] try: from zope.browsermenu.metaconfigure import menuItemDirective except ImportError: # pragma: no cover menuItemDirective = _fallbackMenuItemDirective # There are three cases we want to suport: # # Named view without pages (single-page view) # # <browser:page # for=".IContact.IContactInfo." # name="info.html" # template="info.pt" # class=".ContactInfoView." # permission="zope.View" # /> # # Unnamed view with pages (multi-page view) # # <browser:pages # for=".IContact." # class=".ContactEditView." # permission="ZopeProducts.Contact.ManageContacts" # > # # <browser:page name="edit.html" template="edit.pt" /> # <browser:page name="editAction.html" attribute="action" /> # </browser:pages> # # Named view with pages (add view is a special case of this) # # <browser:view # name="ZopeProducts.Contact" # for="Zope.App.OFS.Container.IAdding." # class=".ContactAddView." # permission="ZopeProducts.Contact.ManageContacts" # > # # <browser:page name="add.html" template="add.pt" /> # <browser:page name="action.html" attribute="action" /> # </browser:view> # We'll also provide a convenience directive for add views: # # <browser:add # name="ZopeProducts.Contact" # class=".ContactAddView." # permission="ZopeProducts.Contact.ManageContacts" # > # # <browser:page name="add.html" template="add.pt" /> # <browser:page name="action.html" attribute="action" /> # </browser:view> # page def _norm_template(_context, template): template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) return template def page(_context, name, permission, for_=Interface, layer=IDefaultBrowserLayer, template=None, class_=None, allowed_interface=None, allowed_attributes=None, attribute='__call__', menu=None, title=None): _handle_menu(_context, menu, title, [for_], name, permission, layer) required = {} permission = _handle_permission(_context, permission) if not (class_ or template): raise ConfigurationError("Must specify a class or template") if attribute != '__call__': if template: raise ConfigurationError( "Attribute and template cannot be used together.") assert class_, "Must have class if attribute is used" if template: template = _norm_template(_context, template) required['__getitem__'] = permission # TODO: new __name__ attribute must be tested if class_: if attribute != '__call__': if not hasattr(class_, attribute): raise ConfigurationError( "The provided class doesn't have the specified attribute " ) if template: # class and template new_class = SimpleViewClass(template, bases=(class_, ), name=name) else: cdict = {} cdict['__name__'] = name cdict['__page_attribute__'] = attribute new_class = type(class_.__name__, (class_, simple,), cdict) if hasattr(class_, '__implements__'): classImplements(new_class, IBrowserPublisher) else: # template new_class = SimpleViewClass(template, name=name) for n in (attribute, 'browserDefault', '__call__', 'publishTraverse'): required[n] = permission _handle_allowed_interface(_context, allowed_interface, permission, required) _handle_allowed_attributes(_context, allowed_attributes, permission, required) _handle_for(_context, for_) new_class._simple__whitelist = ( set(required) - {attribute, 'browserDefault', '__call__', 'publishTraverse'}) defineChecker(new_class, Checker(required)) _context.action( discriminator=('view', (for_, layer), name, IBrowserRequest), callable=handler, args=('registerAdapter', new_class, (for_, layer), Interface, name, _context.info), ) # pages, which are just a short-hand for multiple page directives. # Note that a class might want to access one of the defined # templates. If it does though, it should use getMultiAdapter. class pages: def __init__(self, _context, permission, for_=Interface, layer=IDefaultBrowserLayer, class_=None, allowed_interface=None, allowed_attributes=None): self.opts = dict( for_=for_, permission=permission, layer=layer, class_=class_, allowed_interface=allowed_interface, allowed_attributes=allowed_attributes, ) def page(self, _context, name, attribute='__call__', template=None, menu=None, title=None): return page(_context, name=name, attribute=attribute, template=template, menu=menu, title=title, **(self.opts)) def __call__(self): return () # view (named view with pages) # This is a different case. We actually build a class with attributes # for all of the given pages. class view: default = None def __init__(self, _context, permission, for_=Interface, name='', layer=IDefaultBrowserLayer, class_=None, allowed_interface=None, allowed_attributes=None, menu=None, title=None, provides=Interface): _handle_menu(_context, menu, title, [for_], name, permission, layer) permission = _handle_permission(_context, permission) self.args = (_context, name, (for_, layer), permission, class_, allowed_interface, allowed_attributes) self.pages = [] self.menu = menu self.provides = provides def page(self, _context, name, attribute=None, template=None): if template: template = _norm_template(_context, template) else: if not attribute: raise ConfigurationError( "Must specify either a template or an attribute name") self.pages.append((name, attribute, template)) return () def defaultPage(self, _context, name): self.default = name return () def __call__(self): (_context, name, (for_, layer), permission, class_, allowed_interface, allowed_attributes) = self.args required = {} cdict = {} pages = {} for pname, attribute, template in self.pages: if template: cdict[pname] = ViewPageTemplateFile(template) if attribute and attribute != name: cdict[attribute] = cdict[pname] else: if not hasattr(class_, attribute): raise ConfigurationError("Undefined attribute", attribute) attribute = attribute or pname required[pname] = permission pages[pname] = attribute # This should go away, but noone seems to remember what to do. :-( if hasattr(class_, 'publishTraverse'): def publishTraverse(self, request, name, pages=pages, getattr=getattr): if name in pages: return getattr(self, pages[name]) view = queryMultiAdapter((self, request), name=name) if view is not None: return view m = class_.publishTraverse.__get__(self) return m(request, name) else: def publishTraverse(self, request, name, pages=pages, getattr=getattr): if name in pages: return getattr(self, pages[name]) view = queryMultiAdapter((self, request), name=name) if view is not None: return view raise NotFound(self, name, request) cdict['publishTraverse'] = publishTraverse if not hasattr(class_, 'browserDefault'): if self.default or self.pages: _default = self.default or self.pages[0][0] cdict['browserDefault'] = ( lambda self, request, default=_default: (self, (default, )) ) elif providesCallable(class_): cdict['browserDefault'] = ( lambda self, request: (self, ()) ) bases = (simple,) if class_ is None else (class_, simple) try: cname = str(name) except Exception: # pragma: no cover cname = "GeneratedClass" cdict['__name__'] = name newclass = type(cname, bases, cdict) for n in ('publishTraverse', 'browserDefault', '__call__'): required[n] = permission _handle_allowed_interface(_context, allowed_interface, permission, required) _handle_allowed_attributes(_context, allowed_attributes, permission, required) _handle_for(_context, for_) defineChecker(newclass, Checker(required)) if self.provides is not None: _context.action( discriminator=None, callable=provideInterface, args=('', self.provides) ) _context.action( discriminator=('view', (for_, layer), name, self.provides), callable=handler, args=('registerAdapter', newclass, (for_, layer), self.provides, name, _context.info), ) def _handle_menu(_context, menu, title, for_, name, permission, layer=IDefaultBrowserLayer): if not menu and not title: # Neither of them return [] if not menu or not title: # Only one or the other raise ConfigurationError( "If either menu or title are specified, they must " "both be specified.") if len(for_) != 1: raise ConfigurationError( "Menus can be specified only for single-view, not for " "multi-views.") return menuItemDirective( _context, menu, for_[0], '@@' + name, title, permission=permission, layer=layer) def _handle_permission(_context, permission): if permission == 'zope.Public': permission = CheckerPublic return permission def _handle_allowed_interface(_context, allowed_interface, permission, required): # Allow access for all names defined by named interfaces if allowed_interface: for i in allowed_interface: _context.action( discriminator=None, callable=provideInterface, args=(None, i) ) for name in i: required[name] = permission def _handle_allowed_attributes(_context, allowed_attributes, permission, required): # Allow access for all named attributes if allowed_attributes: for name in allowed_attributes: required[name] = permission def _handle_for(_context, for_): if for_ is not None: _context.action( discriminator=None, callable=provideInterface, args=('', for_) ) @implementer(IBrowserPublisher) class simple(BrowserView): __page_attribute__ = '__call__' def publishTraverse(self, request, name): if name in getattr(self, "_simple__whitelist", []): self.__page_attribute__ = name return self else: raise NotFound(self, name, request) def __call__(self, *a, **k): # If a class doesn't provide it's own call, then get the attribute attr = self.__page_attribute__ if attr == '__call__': raise AttributeError("__call__") meth = getattr(self, attr) return meth(*a, **k) def browserDefault(self, request): # If a class doesn't provide it's own browserDefault, then get the # attribute given by the __page_attribute__. attr = self.__page_attribute__ if attr == 'browserDefault': # safety guard against recursion error: raise AttributeError("browserDefault") # pragma: no cover meth = getattr(self, attr) return (meth, "") def providesCallable(class_): if hasattr(class_, '__call__'): for c in class_.__mro__: if '__call__' in c.__dict__: return True return False def expressiontype(_context, name, handler): _context.action( discriminator=("tales:expressiontype", name), callable=registerType, args=(name, handler) ) def registerType(name, handler): Engine.registerType(name, handler) TrustedEngine.registerType(name, handler) def clear(): Engine.__init__() _Engine(Engine) TrustedEngine.__init__() _TrustedEngine(TrustedEngine) try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover pass else: addCleanUp(clear)
zope.browserpage
/zope.browserpage-5.0.tar.gz/zope.browserpage-5.0/src/zope/browserpage/metaconfigure.py
metaconfigure.py
========= Changes ========= 5.1 (2023-08-28) ================ - Make tests more resilient. 5.0 (2023-02-14) ================ - Drop support for Python 2.7, 3.5, 3.6. - Add support for Python 3.9, 3.10, 3.11. - Drop support for ``python setup.py test``. 4.4 (2019-12-10) ================ - Make the registration of the ``FileETag`` adapter conditional on the environment as Zope 4 registers this adapter explicitly in ``Products.Five.browser``. See `#12 <https://github.com/zopefoundation/zope.browserresource/pull/12>`_. - Add support for Python 3.8. - Drop support for Python 3.4. 4.3 (2018-10-05) ================ - Add support for Python 3.7. - Host documentation at https://zopebrowserresource.readthedocs.io - Add ``.git`` to the list of directory names that are ignored by default. - Fix test compatibility with zope.i18n 4.3. See `#8 <https://github.com/zopefoundation/zope.browserresource/issues/8>`_ 4.2.1 (2017-09-01) ================== - Fix dependencies of the ``zcml`` extra. 4.2.0 (2017-08-04) ================== - Add support for Python 3.5 and 3.6. - Drop support for Python 2.6 and 3.3. 4.1.0 (2014-12-26) ================== - Add support for PyPy. PyPy3 support awaits 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.2 (2014-11-04) ================== - Return no ETag if no adapter is registered, disabling the requirement for applications that was introduced in 3.11.0 (GitHub #1) 4.0.1 (2013-04-03) ================== - Fix some Python 3 string vs bytes issues. 4.0.0 (2013-02-20) ================== - Replace deprecated `zope.component.adapts` usage with equivalent `zope.component.adapter` decorator. - Replace deprecated `zope.interface.classProvides` usage with equivalent `zope.interface.provider` decorator. - Replace deprecated `zope.interface.implementsOnly` usage with equivalent `zope.interface.implementer_only` decorator. - Replace deprecated `zope.interface.implements` usage with equivalent `zope.interface.implementer` decorator. - Drop support for Python 2.4 and 2.5. - Add support for Python 3.3. 3.12.0 (2010-12-14) =================== - Add ``zcml`` extra dependencies and fixed dependencies of ``configure.zcml`` on other packages' ``meta.zcml``. - Add a test for including our own ``configure.zcml``. 3.11.0 (2010-08-13) =================== - Support the HTTP ETag header for file resources. ETag generation can be customized or disabled by providing an IETag multi-adapter on (IFileResource, your-application-skin). 3.10.3 (2010-04-30) =================== - Prefer the standard libraries doctest module to the one from zope.testing. 3.10.2 (2009-11-25) =================== - The previous release had a broken egg, sorry. 3.10.1 (2009-11-24) =================== - Import hooks functionality from zope.component after it was moved there from zope.site. This lifts the dependency on zope.site and thereby, ZODB. - Import ISite and IPossibleSite from zope.component after they were moved there from zope.location. 3.10.0 (2009-09-25) =================== - Add an ability to forbid publishing of some files in the resource directory, this is done by fnmatch'ing the wildcards in the ``forbidden_names``class attribute of ``DirectoryResource``. By default, the ``.svn`` is in that attribute, so directories won't publish subversion system directory that can contain private information. 3.9.0 (2009-08-27) ================== Initial release. This package was splitted off zope.app.publisher as a part of refactoring process. Additional changes that are made during refactoring: * Resource class for file resources are now selected the pluggable way. The resource directory publisher and browser:resource ZCML directive now creating file resources using factory utility lookup based on the file extension, so it's now possible to add new resource types without introducing new ZCML directives and they will work inside resource directories as well. NOTE: the "resource_factories" attribute from the DirectoryResource was removed, so if you were using this attribute for changing resource classes for some file extensions, you need to migrate your code to new utility-based mechanism. See zope.browserresource.interfaces.IResourceFactoryFactory interface. * The Image resource class was removed, as they are actually simple files. To migrate, simply rename the "image" argument in browser:resource and browser:i18n-resource directives to "file", if you don't do this, resouces will work, but you'll get deprecation warnings. If you need custom behaviour for images, you can register a resource factory utility for needed file extensions. * The PageTemplateResource was moved into a separate package, "zope.ptresource", which is a plugin for this package now. Because of that, the "template" argument of browser:resource directive was deprecated and you should rename it to "file" to migrate. The PageTemplateResource will be created for "pt", "zpt" and "html" files automatically, if zope.ptresource package is included in your configuration. * Fix stripping the "I" from an interface name for icon title, if no title is specified. * When publishing a resource via Resources view, set resource parent to an ISite object, not to current site manager. * Clean up code and improve test coverage.
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/CHANGES.rst
CHANGES.rst
====================== zope.browserresource ====================== .. image:: https://img.shields.io/pypi/v/zope.browserresource.svg :target: https://pypi.python.org/pypi/zope.browserresource/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.browserresource.svg :target: https://pypi.org/project/zope.browserresource/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.browserresource/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.browserresource/actions/workflows/tests.yml .. image:: https://coveralls.io/repos/github/zopefoundation/zope.browserresource/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.browserresource?branch=master .. image:: https://readthedocs.org/projects/zopebrowserresource/badge/?version=latest :target: https://zopebrowserresource.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status .. note:: This package is at present not reusable without depending on a large chunk of the Zope Toolkit and its assumptions. It is maintained by the `Zope Toolkit project <http://docs.zope.org/zopetoolkit/>`_. This package provides an implementation of browser resources. It also provides directives for defining those resources using ZCML. Resources are static files and directories that are served to the browser directly from the filesystem. The most common example are images, CSS style sheets, or JavaScript files. Resources are be registered under a symbolic name and can later be referred to by that name, so their usage is independent from their physical location. Resources can also easily be internationalized. Documentation is hosted at https://zopebrowserresource.readthedocs.io
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/README.rst
README.rst
import fnmatch import os from zope.component import queryUtility from zope.interface import implementer from zope.interface import provider from zope.publisher.browser import BrowserView from zope.publisher.interfaces import NotFound from zope.publisher.interfaces.browser import IBrowserPublisher from zope.browserresource.file import FileResourceFactory from zope.browserresource.interfaces import IResourceFactory from zope.browserresource.interfaces import IResourceFactoryFactory from zope.browserresource.resource import Resource _not_found = object() def empty(): return '' # we only need this class as a context for DirectoryResource class Directory: def __init__(self, path, checker, name): self.path = path self.checker = checker self.__name__ = name @implementer(IBrowserPublisher) class DirectoryResource(BrowserView, Resource): """ A resource representing an entire directory. It is traversable to the items contained within the directory. See `get`. """ #: The default resource factory to use for files if no more #: specific factory has been registered. default_factory = FileResourceFactory #: The resource factory to use for directories. directory_factory = None # this will be assigned later in the module #: A sequence of name patterns usable with `fnmatch.fnmatch`. #: Traversing to files that match these names will not #: produce resources. forbidden_names = ('.svn', '.git') def publishTraverse(self, request, name): """ Uses `get` to traverse to the *name*. .. seealso:: :meth:`zope.publisher.interfaces.browser.IBrowserPublisher.publishTraverse` """ # noqa: E501 line too long return self.get(name) def browserDefault(self, request): """ Returns an empty callable and tuple. .. seealso:: :meth:`zope.publisher.interfaces.browser.IBrowserPublisher.browserDefault` """ # noqa: E501 line too long return empty, () def __getitem__(self, name): res = self.get(name, None) if res is None: raise KeyError(name) return res def get(self, name, default=_not_found): """ Locate *name* on the filesystem and return a `.IResource` for it. If the *name* cannot be found and no *default* is given, then raise `.NotFound`. If the *name* matches one of the :attr:`forbidden patterns <forbidden_names>` then returns the *default* (if given) or raise `.NotFound` (when not given). When the *name* refers to a file, we `query <.queryUtility>` for a `.IResourceFactoryFactory` utility named for the file's extension (e.g., ``css``) and use it to produce a resource. If no such utility can be found, we use :attr:`our default <default_factory>`. When the *name* refers to a directory, we use :attr:`our directory factory <directory_factory>`. """ for pat in self.forbidden_names: if fnmatch.fnmatch(name, pat): if default is _not_found: raise NotFound(None, name) return default path = self.context.path filename = os.path.join(path, name) isfile = os.path.isfile(filename) isdir = os.path.isdir(filename) if not (isfile or isdir): if default is _not_found: raise NotFound(None, name) return default if isfile: ext = os.path.splitext(os.path.normcase(name))[1][1:] factory = queryUtility(IResourceFactoryFactory, ext, self.default_factory) else: factory = self.directory_factory rname = self.__name__ + '/' + name resource = factory(filename, self.context.checker, rname)(self.request) resource.__parent__ = self return resource @implementer(IResourceFactory) @provider(IResourceFactoryFactory) class DirectoryResourceFactory: factoryClass = DirectoryResource def __init__(self, path, checker, name): self.__dir = Directory(path, checker, name) self.__checker = checker self.__name = name def __call__(self, request): resource = self.factoryClass(self.__dir, request) resource.__Security_checker__ = self.__checker resource.__name__ = self.__name return resource DirectoryResource.directory_factory = DirectoryResourceFactory
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/src/zope/browserresource/directory.py
directory.py
"""Resource base class and AbsoluteURL adapter """ import zope.component.hooks import zope.traversing.browser.absoluteurl from zope.component import adapter from zope.component import getMultiAdapter from zope.component import queryMultiAdapter from zope.interface import implementer from zope.interface import implementer_only from zope.location import Location from zope.publisher.interfaces.browser import IBrowserRequest from zope.traversing.browser.interfaces import IAbsoluteURL from zope.browserresource.interfaces import IResource @implementer(IResource) class Resource(Location): """ Default implementation of `.IResource`. When called, this object gets a multi-adapter from itself and its request to :class:`zope.traversing.browser.interfaces.IAbsoluteURL` and returns the `str` of that object. """ def __init__(self, request): self.request = request def __call__(self): return str(getMultiAdapter((self, self.request), IAbsoluteURL)) @implementer_only(IAbsoluteURL) @adapter(IResource, IBrowserRequest) class AbsoluteURL(zope.traversing.browser.absoluteurl.AbsoluteURL): """ Default implementation of :class:`zope.traversing.browser.interfaces.IAbsoluteURL` for `.IResource`. This object always produces URLs based on the current site and the empty view, e.g., ``path/to/site/@@/resource-name``. When `str` is called on this object, it will first get the current site using `zope.component.hooks.getSite`. It will then attempt to adapt that site and the request to :class:`zope.traversing.browser.interfaces.IAbsoluteURL` named ``resource``, and if that isn't available it will use the unnamed adapter. The URL of that object (i.e., the URL of the site) will be combined with the name of the resource to produce the final URL. .. seealso:: `zope.browserresource.resources.Resources` For the unnamed view that the URLs we produce usually refer to. """ def __init__(self, context, request): self.context = context self.request = request def _createUrl(self, baseUrl, name): return "{}/@@/{}".format(baseUrl, name) def __str__(self): name = self.context.__name__ if name.startswith('++resource++'): name = name[12:] site = zope.component.hooks.getSite() base = queryMultiAdapter((site, self.request), IAbsoluteURL, name="resource") if base is None: url = str(getMultiAdapter((site, self.request), IAbsoluteURL)) else: url = str(base) return self._createUrl(url, name)
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/src/zope/browserresource/resource.py
resource.py
"""Resource interfaces """ from zope.interface import Attribute from zope.interface import Interface class IResource(Interface): """ A resource. Resources are static files and directories that are served to the browser directly from the filesystem. The most common example are images, CSS style sheets, or JavaScript files. Resources are be registered under a symbolic name and can later be referred to by that name, so their usage is independent from their physical location. .. seealso:: `zope.browserresource.resource.Resource` .. seealso:: `zope.browserresource.resource.AbsoluteURL` """ request = Attribute('Request object that is requesting the resource') def __call__(): """ Return the absolute URL of this resource. """ class IFileResource(IResource): """ A resource representing a single file. .. seealso:: `zope.browserresource.file.FileResource` """ class IResourceFactory(Interface): """ A callable object to produce `IResource` objects. """ def __call__(request): """Return an `IResource` object""" class IResourceFactoryFactory(Interface): """ A factory for `IResourceFactory` objects These factories are registered as named utilities that can be selected for creating resource factories in a pluggable way. `Resource directories <.DirectoryResource>` and the ``<browser:resource>`` `directive <.IResourceDirective>` use these utilities to choose what resource to create, depending on the file extension, so third-party packages could easily plug-in additional resource types. """ def __call__(path, checker, name): """Return an IResourceFactory""" class IETag(Interface): """ An adapter for computing resource ETags. These should be registered as multi-adapters on the resource and the request. .. seealso:: `zope.browserresource.file.FileETag` """ def __call__(mtime, content): """ Compute an ETag for a resource. :param float mtime: The filesystem modification time of the resource (`os.path.getmtime`) :param bytes content: The contents of the resource. :return: A string representing the ETag, or `None` to disable the ETag header. """
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/src/zope/browserresource/interfaces.py
interfaces.py
import os import re import time from email.utils import formatdate from email.utils import mktime_tz from email.utils import parsedate_tz from zope.component import adapter from zope.component import queryMultiAdapter from zope.contenttype import guess_content_type from zope.interface import implementer from zope.interface import provider from zope.publisher.browser import BrowserView from zope.publisher.interfaces import NotFound from zope.publisher.interfaces.browser import IBrowserPublisher from zope.publisher.interfaces.browser import IBrowserRequest from zope.browserresource.interfaces import IETag from zope.browserresource.interfaces import IFileResource from zope.browserresource.interfaces import IResourceFactory from zope.browserresource.interfaces import IResourceFactoryFactory from zope.browserresource.resource import Resource ETAG_RX = re.compile(r'[*]|(?:W/)?"(?:[^"\\]|[\\].)*"') def parse_etags(value): r"""Parse a list of entity tags. HTTP/1.1 specifies the following syntax for If-Match/If-None-Match headers: .. code-block:: abnf If-Match = "If-Match" ":" ( "*" | 1#entity-tag ) If-None-Match = "If-None-Match" ":" ( "*" | 1#entity-tag ) entity-tag = [ weak ] opaque-tag weak = "W/" opaque-tag = quoted-string quoted-string = ( <"> *(qdtext) <"> ) qdtext = <any TEXT except <">> The backslash character ("\") may be used as a single-character quoting mechanism only within quoted-string and comment constructs. Examples: >>> parse_etags('*') ['*'] >>> parse_etags(r' "qwerty", ,"foo",W/"bar" , "baz","\""') ['"qwerty"', '"foo"', 'W/"bar"', '"baz"', '"\\""'] Ill-formed headers are ignored >>> parse_etags("not an etag at all") [] """ return ETAG_RX.findall(value) def etag_matches(etag, tags): """Check if the entity tag matches any of the given tags. >>> etag_matches('"xyzzy"', ['"abc"', '"xyzzy"', 'W/"woof"']) True >>> etag_matches('"woof"', ['"abc"', 'W/"woof"']) False >>> etag_matches('"xyzzy"', ['*']) True Note that you pass quoted etags in both arguments! """ for tag in tags: if tag == etag or tag == '*': return True return False def quote_etag(etag): r"""Quote an etag value >>> quote_etag("foo") '"foo"' Special characters are escaped >>> quote_etag('"') '"\\""' >>> quote_etag('\\') '"\\\\"' """ return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"') class File: """ An object representing a file on the filesystem. These are created by `FileResourceFactory` for use with `FileResource`. """ def __init__(self, path, name): self.path = path self.__name__ = name with open(path, 'rb') as f: self.data = f.read() self.content_type = guess_content_type(path, self.data)[0] self.lmt = float(os.path.getmtime(path)) or time.time() self.lmh = formatdate(self.lmt, usegmt=True) @implementer(IFileResource, IBrowserPublisher) class FileResource(BrowserView, Resource): """ Default implementation of `.IFileResource`. This class also implements :class:`zope.publisher.interfaces.browser.IBrowserPublisher`. """ cacheTimeout = 86400 def publishTraverse(self, request, name): '''File resources can't be traversed further, so raise NotFound if someone tries to traverse it. >>> TestRequest = globals()['TestRequest'] >>> testFilePath = globals()['testFilePath'] >>> nullChecker = globals()['nullChecker'] >>> factory = FileResourceFactory( ... testFilePath, nullChecker, 'test.txt') >>> request = TestRequest() >>> resource = factory(request) >>> resource.publishTraverse(request, '_testData') Traceback (most recent call last): ... zope.publisher.interfaces.NotFound: Object: None, name: '_testData' ''' raise NotFound(None, name) def browserDefault(self, request): '''Return a callable for processing browser requests. >>> TestRequest = globals()['TestRequest'] >>> testFilePath = globals()['testFilePath'] >>> nullChecker = globals()['nullChecker'] >>> factory = FileResourceFactory( ... testFilePath, nullChecker, 'test.txt') >>> request = TestRequest(REQUEST_METHOD='GET') >>> resource = factory(request) >>> view, next = resource.browserDefault(request) >>> with open(testFilePath, 'rb') as f: ... view() == f.read() True >>> next == () True >>> request = TestRequest(REQUEST_METHOD='HEAD') >>> resource = factory(request) >>> view, next = resource.browserDefault(request) >>> view() == b'' True >>> next == () True ''' return getattr(self, request.method), () def chooseContext(self): """ Choose the appropriate context. This method can be overriden in subclasses, that need to choose appropriate file, based on current request or other condition, like, for example, i18n files. .. seealso:: `.I18nFileResource` .. seealso:: `.II18nResourceDirective` """ return self.context def GET(self): '''Return a file data for downloading with GET requests >>> TestRequest = globals()['TestRequest'] >>> testFilePath = globals()['testFilePath'] >>> nullChecker = globals()['nullChecker'] >>> factory = FileResourceFactory( ... testFilePath, nullChecker, 'test.txt') >>> request = TestRequest() >>> resource = factory(request) >>> with open(testFilePath, 'rb') as f: ... resource.GET() == f.read() True >>> request.response.getHeader('Content-Type') == 'text/plain' True ''' file = self.chooseContext() request = self.request response = request.response etag = self._makeETag(file) setCacheControl(response, self.cacheTimeout) can_return_304 = False all_cache_checks_passed = True # HTTP If-Modified-Since header handling. This is duplicated # from OFS.Image.Image - it really should be consolidated # somewhere... header = request.getHeader('If-Modified-Since', None) if header is not None: can_return_304 = True header = header.split(';')[0] # Some proxies seem to send invalid date strings for this # header. If the date string is not valid, we ignore it # rather than raise an error to be generally consistent # with common servers such as Apache (which can usually # understand the screwy date string as a lucky side effect # of the way they parse it). try: mod_since = int(mktime_tz(parsedate_tz(header))) except (ValueError, TypeError): mod_since = None if getattr(file, 'lmt', None): last_mod = int(file.lmt) else: last_mod = 0 if mod_since is None or last_mod <= 0 or last_mod > mod_since: all_cache_checks_passed = False # HTTP If-None-Match header handling header = request.getHeader('If-None-Match', None) if header is not None: can_return_304 = True tags = parse_etags(header) if not etag or not etag_matches(quote_etag(etag), tags): all_cache_checks_passed = False # 304 responses MUST contain ETag, if one would've been sent with # a 200 response if etag: response.setHeader('ETag', quote_etag(etag)) if can_return_304 and all_cache_checks_passed: response.setStatus(304) return b'' # 304 responses SHOULD NOT or MUST NOT include other entity headers, # depending on whether the conditional GET used a strong or a weak # validator. We only use strong validators, which makes it SHOULD # NOT. response.setHeader('Content-Type', file.content_type) response.setHeader('Last-Modified', file.lmh) return file.data def HEAD(self): '''Return proper headers and no content for HEAD requests >>> TestRequest = globals()['TestRequest'] >>> testFilePath = globals()['testFilePath'] >>> nullChecker = globals()['nullChecker'] >>> factory = FileResourceFactory( ... testFilePath, nullChecker, 'test.txt') >>> request = TestRequest() >>> resource = factory(request) >>> resource.HEAD() == b'' True >>> request.response.getHeader('Content-Type') == 'text/plain' True ''' file = self.chooseContext() etag = self._makeETag(file) response = self.request.response response.setHeader('Content-Type', file.content_type) response.setHeader('Last-Modified', file.lmh) if etag: response.setHeader('ETag', etag) setCacheControl(response, self.cacheTimeout) return b'' def _makeETag(self, file_): etag_adapter = queryMultiAdapter((self, self.request), IETag) if etag_adapter is None: return None return etag_adapter(file_.lmt, file_.data) # for unit tests def _testData(self): with open(self.context.path, 'rb') as f: return f.read() @adapter(IFileResource, IBrowserRequest) @implementer(IETag) class FileETag: """ Default implementation of `.IETag` registered for `.IFileResource` and :class:`zope.publisher.interfaces.browser.IBrowserRequest`. """ def __init__(self, context, request): self.context = context self.request = request def __call__(self, mtime, content): return '{}-{}'.format(mtime, len(content)) def setCacheControl(response, secs=86400): # Cache for one day by default response.setHeader('Cache-Control', 'public,max-age=%s' % secs) t = time.time() + secs response.setHeader('Expires', formatdate(t, usegmt=True)) @implementer(IResourceFactory) @provider(IResourceFactoryFactory) class FileResourceFactory: """ Implementation of `.IResourceFactory` producing `FileResource`. The class itself provides `.IResourceFactoryFactory` """ resourceClass = FileResource def __init__(self, path, checker, name): self.__file = File(path, name) self.__checker = checker self.__name = name def __call__(self, request): resource = self.resourceClass(self.__file, request) resource.__Security_checker__ = self.__checker resource.__name__ = self.__name return resource
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/src/zope/browserresource/file.py
file.py
"""Internationalized file resource. """ from zope.i18n.interfaces import II18nAware from zope.i18n.negotiator import negotiator from zope.interface import implementer from zope.interface import provider from zope.browserresource.file import FileResource from zope.browserresource.interfaces import IResourceFactory from zope.browserresource.interfaces import IResourceFactoryFactory @implementer(II18nAware) class I18nFileResource(FileResource): """ A :class:`zope.i18n.interfaces.II18nAware` file resource. .. seealso:: `.II18nResourceDirective` """ def __init__(self, data, request, defaultLanguage='en'): """ Creates an internationalized file resource. :param dict data: A mapping from languages to `.File` objects. """ self._data = data self.request = request self.defaultLanguage = defaultLanguage def chooseContext(self): """ Choose the appropriate context (file) according to language. """ langs = self.getAvailableLanguages() language = negotiator.getLanguage(langs, self.request) try: return self._data[language] except KeyError: return self._data[self.defaultLanguage] def getDefaultLanguage(self): 'See II18nAware' return self.defaultLanguage def setDefaultLanguage(self, language): 'See II18nAware' if language not in self._data: raise ValueError( 'cannot set nonexistent language (%s) as default' % language) self.defaultLanguage = language def getAvailableLanguages(self): """ The available languages are those defined in the *data* mapping given to this object. """ return self._data.keys() # for unit tests def _testData(self, language): with open(self._data[language].path, 'rb') as f: return f.read() @implementer(IResourceFactory) @provider(IResourceFactoryFactory) class I18nFileResourceFactory: def __init__(self, data, defaultLanguage): self.__data = data self.__defaultLanguage = defaultLanguage def __call__(self, request): return I18nFileResource(self.__data, request, self.__defaultLanguage)
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/src/zope/browserresource/i18nfile.py
i18nfile.py
"""ZCML directives for defining browser resources """ from zope.configuration.fields import GlobalInterface from zope.configuration.fields import GlobalObject from zope.configuration.fields import MessageID from zope.configuration.fields import Path from zope.interface import Interface from zope.schema import Int from zope.schema import TextLine from zope.security.zcml import Permission class IBasicResourceInformation(Interface): """ This is the basic information for all browser resources. """ layer = GlobalInterface( title="The layer the resource should be found in", description=""" For information on layers, see the documentation for the skin directive. Defaults to "default".""", required=False ) permission = Permission( title="The permission needed to access the resource.", description=""" If a permission isn't specified, the resource will always be accessible.""", required=False ) class IResourceDirective(IBasicResourceInformation): """ Defines a browser resource. .. seealso:: `.FileResourceFactory` """ name = TextLine( title="The name of the resource", description=""" This is the name used in resource urls. Resource urls are of the form ``<site>/@@/resourcename``, where ``<site>`` is the url of "site", a folder with a site manager. We make resource urls site-relative (as opposed to content-relative) so as not to defeat caches.""", required=True ) factory = GlobalObject( title="Resource Factory", description="The factory used to create the resource. The factory " "should only expect to get the request passed when " "called.", required=False ) file = Path( title="File", description="The file containing the resource data. The resource " "type that will be created depends on file extension. " "The named IResourceFactoryFactory utilities are " "registered per extension. If no factory is registered " "for given file extension, the default FileResource " "factory will be used.", required=False ) image = Path( title="Image", description=""" If the image attribute is used, then an image resource, rather than a file resource will be created. This attribute is deprecated in favor of pluggable resource types, registered per extension. Use the "file" attribute instead. """, required=False ) template = Path( title="Template", description=""" If the template attribute is used, then a page template resource, rather than a file resource will be created. This attribute is deprecated in favor of pluggable resource types, registered per extension. Use the "file" attribute instead. To use page template resources, you need to install zope.ptresource package. """, required=False ) class II18nResourceDirective(IBasicResourceInformation): """ Defines an i18n'd resource. """ name = TextLine( title="The name of the resource", description=""" This is the name used in resource urls. Resource urls are of the form ``<site>/@@/resourcename``, where ``<site>`` is the url of "site", a folder with a site manager. We make resource urls site-relative (as opposed to content-relative) so as not to defeat caches.""", required=True ) defaultLanguage = TextLine( title="Default language", description="Defines the default language", required=False ) class II18nResourceTranslationSubdirective(IBasicResourceInformation): """ Subdirective to `II18nResourceDirective`. """ language = TextLine( title="Language", description="Language of this translation of the resource", required=True ) file = Path( title="File", description="The file containing the resource data.", required=False ) image = Path( title="Image", description=""" If the image attribute is used, then an image resource, rather than a file resource will be created. This attribute is deprecated, as images are now simply files. Use the "file" attribute instead. """, required=False ) class IResourceDirectoryDirective(IBasicResourceInformation): """ Defines a directory containing browser resources. .. seealso:: `.DirectoryResource` """ name = TextLine( title="The name of the resource", description=""" This is the name used in resource urls. Resource urls are of the form ``<site>/@@/resourcename``, where ``<site>`` is the url of "site", a folder with a site manager. We make resource urls site-relative (as opposed to content-relative) so as not to defeat caches.""", required=True ) directory = Path( title="Directory", description="The directory containing the resource data.", required=True ) class IIconDirective(Interface): """ Define an icon for an interface. """ name = TextLine( title="The name of the icon.", description="The name shows up in URLs/paths. For example 'foo'.", required=True ) for_ = GlobalInterface( title="The interface this icon is for.", description=""" The icon will be for all objects that implement this interface.""", required=True ) file = Path( title="File", description="The file containing the icon.", required=False ) resource = TextLine( title="Resource", description="A resource containing the icon.", required=False ) title = MessageID( title="Title", description="Descriptive title", required=False ) layer = GlobalInterface( title="The layer the icon should be found in", description=""" For information on layers, see the documentation for the skin directive. Defaults to "default".""", required=False ) width = Int( title="The width of the icon.", description=""" The width will be used for the <img width="..." /> attribute. Defaults to 16.""", required=False, default=16 ) height = Int( title="The height of the icon.", description=""" The height will be used for the <img height="..." /> attribute. Defaults to 16.""", required=False, default=16 )
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/src/zope/browserresource/metadirectives.py
metadirectives.py
"""ZCML directive handlers for browser resources """ import os from zope.component import queryUtility from zope.component.interface import provideInterface from zope.component.zcml import handler from zope.configuration.exceptions import ConfigurationError from zope.interface import Interface from zope.interface import implementer from zope.interface import provider from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.security.checker import Checker from zope.security.checker import CheckerPublic from zope.security.checker import NamesChecker from zope.security.proxy import Proxy from zope.browserresource.directory import DirectoryResourceFactory from zope.browserresource.file import File from zope.browserresource.file import FileResourceFactory from zope.browserresource.i18nfile import I18nFileResourceFactory from zope.browserresource.icon import IconViewFactory from zope.browserresource.interfaces import IResourceFactory from zope.browserresource.interfaces import IResourceFactoryFactory allowed_names = ('GET', 'HEAD', 'publishTraverse', 'browserDefault', 'request', '__call__') @implementer(IResourceFactory) @provider(IResourceFactoryFactory) class ResourceFactoryWrapper: def __init__(self, factory, checker, name): self.__factory = factory self.__checker = checker self.__name = name def __call__(self, request): resource = self.__factory(request) resource.__Security_checker__ = self.__checker resource.__name__ = self.__name return resource def resource(_context, name, layer=IDefaultBrowserLayer, permission='zope.Public', factory=None, file=None, image=None, template=None): if permission == 'zope.Public': permission = CheckerPublic checker = NamesChecker(allowed_names, permission) too_many = bool(factory) + bool(file) + bool(image) + bool(template) if too_many > 1: raise ConfigurationError( "Must use exactly one of factory or file or image or template" " attributes for resource directives" ) if image or template: import warnings warnings.warn_explicit( 'The "template" and "image" attributes of resource ' 'directive are deprecated in favor of pluggable ' 'file resource factories based on file extensions. ' 'Use the "file" attribute instead.', DeprecationWarning, _context.info.file, _context.info.line) if image: file = image elif template: file = template _context.action( discriminator=('resource', name, IBrowserRequest, layer), callable=resourceHandler, args=(name, layer, checker, factory, file, _context.info), ) def resourceHandler(name, layer, checker, factory, file, context_info): if factory is not None: factory = ResourceFactoryWrapper(factory, checker, name) else: ext = os.path.splitext(os.path.normcase(file))[1][1:] factory_factory = queryUtility(IResourceFactoryFactory, ext, FileResourceFactory) factory = factory_factory(file, checker, name) handler('registerAdapter', factory, (layer,), Interface, name, context_info) def resourceDirectory(_context, name, directory, layer=IDefaultBrowserLayer, permission='zope.Public'): if permission == 'zope.Public': permission = CheckerPublic checker = NamesChecker(allowed_names + ('__getitem__', 'get'), permission) if not os.path.isdir(directory): raise ConfigurationError( "Directory %s does not exist" % directory ) factory = DirectoryResourceFactory(directory, checker, name) _context.action( discriminator=('resource', name, IBrowserRequest, layer), callable=handler, args=('registerAdapter', factory, (layer,), Interface, name, _context.info), ) def icon(_context, name, for_, file=None, resource=None, layer=IDefaultBrowserLayer, title=None, width=16, height=16): iname = for_.getName() if title is None: title = iname if title.startswith('I'): title = title[1:] # Remove leading 'I' if file is not None and resource is not None: raise ConfigurationError( "Can't use more than one of file, and resource " "attributes for icon directives" ) elif file is not None: resource = '-'.join(for_.__module__.split('.')) resource = "{}-{}-{}".format(resource, iname, name) ext = os.path.splitext(file)[1] if ext: resource += ext # give this module another name, so we can use the "resource" directive # in it that won't conflict with our local variable with the same name. from zope.browserresource import metaconfigure metaconfigure.resource(_context, file=file, name=resource, layer=layer) elif resource is None: raise ConfigurationError( "At least one of the file, and resource " "attributes for resource directives must be specified" ) vfactory = IconViewFactory(resource, title, width, height) _context.action( discriminator=('view', name, vfactory, layer), callable=handler, args=('registerAdapter', vfactory, (for_, layer), Interface, name, _context.info) ) _context.action( discriminator=None, callable=provideInterface, args=(for_.__module__ + '.' + for_.getName(), for_) ) class I18nResource: type = IBrowserRequest default_allowed_attributes = '__call__' def __init__(self, _context, name=None, defaultLanguage='en', layer=IDefaultBrowserLayer, permission=None): self._context = _context self.name = name self.defaultLanguage = defaultLanguage self.layer = layer self.permission = permission self.__data = {} def translation(self, _context, language, file=None, image=None): if file is not None and image is not None: raise ConfigurationError( "Can't use more than one of file, and image " "attributes for resource directives" ) elif file is None and image is None: raise ConfigurationError( "At least one of the file, and image " "attributes for resource directives must be specified" ) if image is not None: import warnings warnings.warn_explicit( 'The "image" attribute of i18n-resource directive is ' 'deprecated in favor of simple files. Use the "file" ' 'attribute instead.', DeprecationWarning, _context.info.file, _context.info.line) file = image self.__data[language] = File(_context.path(file), self.name) def __call__(self, require=None): if self.name is None: return if self.defaultLanguage not in self.__data: raise ConfigurationError( "A translation for the default language (%s) " "must be specified" % self.defaultLanguage ) permission = self.permission factory = I18nFileResourceFactory(self.__data, self.defaultLanguage) if permission: if require is None: require = {} if permission == 'zope.Public': permission = CheckerPublic if require: checker = Checker(require) factory = self._proxyFactory(factory, checker) self._context.action( discriminator=('i18n-resource', self.name, self.type, self.layer), callable=handler, args=('registerAdapter', factory, (self.layer,), Interface, self.name, self._context.info) ) def _proxyFactory(self, factory, checker): def proxyView(request, factory=factory, checker=checker): resource = factory(request) # We need this in case the resource gets unwrapped and # needs to be rewrapped resource.__Security_checker__ = checker return Proxy(resource, checker) return proxyView
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/src/zope/browserresource/metaconfigure.py
metaconfigure.py
"""Resource URL access """ from zope.component import queryAdapter from zope.interface import implementer from zope.location import locate from zope.publisher.browser import BrowserView from zope.publisher.interfaces import NotFound from zope.publisher.interfaces.browser import IBrowserPublisher @implementer(IBrowserPublisher) class Resources(BrowserView): """ A view that can be traversed further to access browser resources. This view is usually registered for :class:`zope.component.interfaces.ISite` objects with no name, so resources will be available at ``<site>/@@/<resource>``. Let's test how it's traversed to get registered resources. Let's create a sample resource class and register it. >>> from zope.component import provideAdapter >>> from zope.interface import Interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.publisher.browser import TestRequest >>> class Resource(object): ... def __init__(self,request): ... self.request = request ... def __call__(self): ... return 'http://localhost/testresource' >>> provideAdapter(Resource, (IDefaultBrowserLayer,), Interface, 'test') Now, create a site and request objects and get the Resources object to work with. >>> site = object() >>> request = TestRequest() >>> resources = Resources(site, request) Okay, let's test the `publishTraverse` method. It should traverse to our registered resource. >>> resource = resources.publishTraverse(request, 'test') >>> resource.__parent__ is site True >>> resource.__name__ == 'test' True >>> resource() 'http://localhost/testresource' However, it will raise `.NotFound` exception if we try to traverse to an unregistered resource. >>> resources.publishTraverse(request, 'does-not-exist') Traceback (most recent call last): ... zope.publisher.interfaces.NotFound: Object: <zope.browserresource.resources.Resources object at 0x...>, name: 'does-not-exist' When accessed without further traversing, it returns an empty page and no futher traversing steps. >>> view, path = resources.browserDefault(request) >>> view() == b'' True >>> path == () True The Resources view also provides ``__getitem__`` method for use in templates. It is equivalent to `publishTraverse`. >>> resource = resources['test'] >>> resource.__parent__ is site True >>> resource.__name__ == 'test' True >>> resource() 'http://localhost/testresource' """ # noqa: E501 line too long def publishTraverse(self, request, name): """ Query for the default adapter on *request* named *name* and return it. This is usually a `.IResource` as registered with `.IResourceDirective`. The resource object is `located <.locate>` beneath the context of this object with the given *name*. :raises NotFound: If no adapter can be found. .. seealso:: `zope.publisher.interfaces.browser.IBrowserPublisher` """ resource = queryAdapter(request, name=name) if resource is None: raise NotFound(self, name) locate(resource, self.context, name) return resource def browserDefault(self, request): """See zope.publisher.interfaces.browser.IBrowserPublisher interface""" return empty, () def __getitem__(self, name): """ A helper method to make this view usable from templates, so resources can be accessed in template like ``context/@@/<resourcename>``. """ return self.publishTraverse(self.request, name) def empty(): return b''
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/src/zope/browserresource/resources.py
resources.py
========== Overview ========== .. highlight:: xml This package provides an implementation of browser resources. It also provides directives for defining those resources using ZCML. Resources are static files and directories that are served to the browser directly from the filesystem. The most common example are images, CSS style sheets, or JavaScript files. Resources are be registered under a symbolic name and can later be referred to by that name, so their usage is independent from their physical location. Registering Resources ===================== You can register a single file with the ``<browser:resource>`` directive, and a whole directory with the ``<browser:resourceDirectory>`` directive, for example:: <browser:resource file="/path/to/static.file" name="myfile" /> <browser:resourceDirectory directory="/path/to/images" name="main-images" /> This causes a named default adapter to be registered that adapts the *request* to :class:`zope.interface.Interface` so to later retrieve a resource, use ``zope.component.getAdapter(request, name='myfile')``. .. note:: The default adapter (the one that adapts to :class:`zope.interface.Interface`) is used to reduce coupling between projects, specifically between this project and `zope.traversing.namespace`. Internationalization ==================== Resources can also be internationalized, which means that a single resource name can refer to any one of a number of files that are specific to different languages. When the resource is retrieved and served, the file that corresponds to the request's language is automatically sent:: <browser:i18n-resource name="myfile" defaultLanguage="en"> <browser:translation language="en" file="path/to/static.file" /> <browser:translation language="de" file="path/to/static.file.de" /> </browser:i18n-resource> Using Resources =============== There are two ways to traverse to a resource: 1. with the 'empty' view on a site, e. g. ``http://localhost/@@/myfile`` (This is declared by ``zope.browserresource``'s ``configure.zcml`` to be `.Resources`.) 2. with the ``++resource++`` namespace, e. g. ``http://localhost/++resource++myfile`` (This is declared by `zope.traversing.namespace`) In case of resource-directories traversal simply continues through its contents, e. g. ``http://localhost/@@/main-images/subdir/sample.jpg`` Rather than putting together the URL to a resource manually, you should use `zope.traversing.browser.interfaces.IAbsoluteURL` to get the URL, or for a shorthand, call the resource object. This has an additional benefit: If you want to serve resources from a different URL, for example because you want to use a web server specialized in serving static files instead of the appserver, you can register an ``IAbsoluteURL`` adapter for the site under the name ``resource`` that will be used to compute the base URLs for resources. (See `.AbsoluteURL` for the implementation.) For example, if you register ``http://static.example.com/`` as the base ``resource`` URL, the resources from the above example would yield the following absolute URLs: ``http://static.example.com/@@/myfile`` and ``http://static.example.com/@@/main-images``.
zope.browserresource
/zope.browserresource-5.1.tar.gz/zope.browserresource-5.1/docs/overview.rst
overview.rst
============== Method Cache ============== cachedIn ======== The `cachedIn` property allows to specify the attribute where to store the computed value: >>> import math >>> from zope.cachedescriptors import method >>> class Point(object): ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @method.cachedIn('_cache') ... def distance(self, x, y): ... """Compute the distance""" ... print('computing distance') ... return math.hypot(self.x - x, self.y - y) ... >>> point = Point(1.0, 2.0) The value is computed once: >>> point.distance(2, 2) computing distance 1.0 >>> point.distance(2, 2) 1.0 Using different arguments calculates a new distance: >>> point.distance(5, 2) computing distance 4.0 >>> point.distance(5, 2) 4.0 The data is stored at the given `_cache` attribute: >>> isinstance(point._cache, dict) True >>> sorted(point._cache.items()) [(((2, 2), ()), 1.0), (((5, 2), ()), 4.0)] It is possible to exlicitly invalidate the data: >>> point.distance.invalidate(point, 5, 2) >>> point.distance(5, 2) computing distance 4.0 Invalidating keys which are not in the cache, does not result in an error: >>> point.distance.invalidate(point, 47, 11) The documentation of the function is preserved (whether through the instance or the class), allowing Sphinx to extract it:: >>> print(point.distance.__doc__) Compute the distance >>> print(point.distance.__name__) distance >>> print(Point.distance.__doc__) Compute the distance >>> print(Point.distance.__name__) distance It is possible to pass in a factory for the cache attribute. Create another Point class: >>> class MyDict(dict): ... pass >>> class Point(object): ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @method.cachedIn('_cache', MyDict) ... def distance(self, x, y): ... print('computing distance') ... return math.sqrt((self.x - x)**2 + (self.y - y)**2) ... >>> point = Point(1.0, 2.0) >>> point.distance(2, 2) computing distance 1.0 Now the cache is a MyDict instance: >>> isinstance(point._cache, MyDict) True
zope.cachedescriptors
/zope.cachedescriptors-5.0-py3-none-any.whl/zope/cachedescriptors/method.rst
method.rst
=================== Cached Properties =================== Cached properties are computed properties that cache their computed values. They take into account instance attributes that they depend on, so when the instance attributes change, the properties will change the values they return. CachedProperty ============== Cached properties cache their data in ``_v_`` attributes, so they are also useful for managing the computation of volatile attributes for persistent objects. Let's look at an example: >>> from zope.cachedescriptors import property >>> import math >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.CachedProperty('x', 'y') ... def radius(self): ... print('computing radius') ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) If we ask for the radius the first time: >>> '%.2f' % point.radius computing radius '2.24' We see that the radius function is called, but if we ask for it again: >>> '%.2f' % point.radius '2.24' The function isn't called. If we change one of the attribute the radius depends on, it will be recomputed: >>> point.x = 2.0 >>> '%.2f' % point.radius computing radius '2.83' But changing other attributes doesn't cause recomputation: >>> point.q = 1 >>> '%.2f' % point.radius '2.83' Note that we don't have any non-volitile attributes added: >>> names = [name for name in point.__dict__ if not name.startswith('_v_')] >>> names.sort() >>> names ['q', 'x', 'y'] For backwards compatibility, the same thing can alternately be written without using decorator syntax: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... def radius(self): ... print('computing radius') ... return math.sqrt(self.x**2 + self.y**2) ... radius = property.CachedProperty(radius, 'x', 'y') >>> point = Point(1.0, 2.0) If we ask for the radius the first time: >>> '%.2f' % point.radius computing radius '2.24' We see that the radius function is called, but if we ask for it again: >>> '%.2f' % point.radius '2.24' The function isn't called. If we change one of the attribute the radius depends on, it will be recomputed: >>> point.x = 2.0 >>> '%.2f' % point.radius computing radius '2.83' Documentation and the ``__name__`` are preserved if the attribute is accessed through the class. This allows Sphinx to extract the documentation. >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.CachedProperty('x', 'y') ... def radius(self): ... '''The length of the line between self.x and self.y''' ... print('computing radius') ... return math.sqrt(self.x**2 + self.y**2) >>> print(Point.radius.__doc__) The length of the line between self.x and self.y >>> print(Point.radius.__name__) radius It is possible to specify a CachedProperty that has no dependencies. For backwards compatibility this can be written in a few different ways:: >>> class Point: ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.CachedProperty ... def no_deps_no_parens(self): ... print("No deps, no parens") ... return 1 ... ... @property.CachedProperty() ... def no_deps(self): ... print("No deps") ... return 2 ... ... def no_deps_old_style(self): ... print("No deps, old style") ... return 3 ... no_deps_old_style = property.CachedProperty(no_deps_old_style) >>> point = Point(1.0, 2.0) >>> point.no_deps_no_parens No deps, no parens 1 >>> point.no_deps_no_parens 1 >>> point.no_deps No deps 2 >>> point.no_deps 2 >>> point.no_deps_old_style No deps, old style 3 >>> point.no_deps_old_style 3 Lazy Computed Attributes ======================== The `property` module provides another descriptor that supports a slightly different caching model: lazy attributes. Like cached proprties, they are computed the first time they are used. however, they aren't stored in volatile attributes and they aren't automatically updated when other attributes change. Furthermore, the store their data using their attribute name, thus overriding themselves. This provides much faster attribute access after the attribute has been computed. Let's look at the previous example using lazy attributes: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.Lazy ... def radius(self): ... print('computing radius') ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) If we ask for the radius the first time: >>> '%.2f' % point.radius computing radius '2.24' We see that the radius function is called, but if we ask for it again: >>> '%.2f' % point.radius '2.24' The function isn't called. If we change one of the attribute the radius depends on, it still isn't called: >>> point.x = 2.0 >>> '%.2f' % point.radius '2.24' If we want the radius to be recomputed, we have to manually delete it: >>> del point.radius >>> point.x = 2.0 >>> '%.2f' % point.radius computing radius '2.83' Note that the radius is stored in the instance dictionary: >>> '%.2f' % point.__dict__['radius'] '2.83' The lazy attribute needs to know the attribute name. It normally deduces the attribute name from the name of the function passed. If we want to use a different name, we need to pass it: >>> def d(point): ... print('computing diameter') ... return 2*point.radius >>> Point.diameter = property.Lazy(d, 'diameter') >>> '%.2f' % point.diameter computing diameter '5.66' Documentation and the ``__name__`` are preserved if the attribute is accessed through the class. This allows Sphinx to extract the documentation. >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.Lazy ... def radius(self): ... '''The length of the line between self.x and self.y''' ... print('computing radius') ... return math.sqrt(self.x**2 + self.y**2) >>> print(Point.radius.__doc__) The length of the line between self.x and self.y >>> print(Point.radius.__name__) radius The documentation of the attribute when accessed through the instance will be the same as the return-value: >>> p = Point(1.0, 2.0) >>> p.radius.__doc__ == float.__doc__ computing radius True This is the same behaviour as the standard Python ``property`` decorator. readproperty ============ readproperties are like lazy computed attributes except that the attribute isn't set by the property: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.readproperty ... def radius(self): ... print('computing radius') ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius computing radius '2.24' But you *can* replace the property by setting a value. This is the major difference to the builtin `property`: >>> point.radius = 5 >>> point.radius 5 Documentation and the ``__name__`` are preserved if the attribute is accessed through the class. This allows Sphinx to extract the documentation. >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.readproperty ... def radius(self): ... '''The length of the line between self.x and self.y''' ... print('computing radius') ... return math.sqrt(self.x**2 + self.y**2) >>> print(Point.radius.__doc__) The length of the line between self.x and self.y >>> print(Point.radius.__name__) radius cachedIn ======== The `cachedIn` property allows to specify the attribute where to store the computed value: >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.cachedIn('_radius_attribute') ... def radius(self): ... print('computing radius') ... return math.sqrt(self.x**2 + self.y**2) >>> point = Point(1.0, 2.0) >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius '2.24' The radius is cached in the attribute with the given name, `_radius_attribute` in this case: >>> '%.2f' % point._radius_attribute '2.24' When the attribute is removed the radius is re-calculated once. This allows invalidation: >>> del point._radius_attribute >>> '%.2f' % point.radius computing radius '2.24' >>> '%.2f' % point.radius '2.24' Documentation is preserved if the attribute is accessed through the class. This allows Sphinx to extract the documentation. >>> class Point: ... ... def __init__(self, x, y): ... self.x, self.y = x, y ... ... @property.cachedIn('_radius_attribute') ... def radius(self): ... '''The length of the line between self.x and self.y''' ... print('computing radius') ... return math.sqrt(self.x**2 + self.y**2) >>> print(Point.radius.__doc__) The length of the line between self.x and self.y
zope.cachedescriptors
/zope.cachedescriptors-5.0-py3-none-any.whl/zope/cachedescriptors/property.rst
property.rst
from functools import update_wrapper ncaches = 0 class _CachedProperty: """ Cached property implementation class. """ def __init__(self, func, *names): global ncaches ncaches += 1 self.data = (func, names, "_v_cached_property_key_%s" % ncaches, "_v_cached_property_value_%s" % ncaches) update_wrapper(self, func) def __get__(self, inst, class_): if inst is None: return self func, names, key_name, value_name = self.data key = names and [getattr(inst, name) for name in names] value = getattr(inst, value_name, self) if value is not self: # We have a cached value if key == getattr(inst, key_name, self): # Cache is still good! return value # We need to compute and cache the value value = func(inst) setattr(inst, key_name, key) setattr(inst, value_name, value) return value def CachedProperty(*args): """ CachedProperties. This is usable directly as a decorator when given names, or when not. Any of these patterns will work: * ``@CachedProperty`` * ``@CachedProperty()`` * ``@CachedProperty('n','n2')`` * def thing(self: ...; thing = CachedProperty(thing) * def thing(self: ...; thing = CachedProperty(thing, 'n') """ if not args: # @CachedProperty() # A callable that produces the decorated function return _CachedProperty arg1 = args[0] names = args[1:] if callable( arg1): # @CachedProperty, *or* thing = CachedProperty(thing, ...) return _CachedProperty(arg1, *names) # @CachedProperty( 'n' ) # Ok, must be a list of string names. Which means we are used like a # factory so we return a callable object to produce the actual decorated # function. def factory(function): return _CachedProperty(function, arg1, *names) return factory class Lazy: """Lazy Attributes. """ def __init__(self, func, name=None): if name is None: name = func.__name__ self.data = (func, name) update_wrapper(self, func) def __get__(self, inst, class_): if inst is None: return self func, name = self.data value = func(inst) inst.__dict__[name] = value return value class readproperty: def __init__(self, func): self.func = func update_wrapper(self, func) def __get__(self, inst, class_): if inst is None: return self func = self.func return func(inst) class cachedIn: """Cached property with given cache attribute.""" def __init__(self, attribute_name): self.attribute_name = attribute_name def __call__(self, func): def get(instance): try: value = getattr(instance, self.attribute_name) except AttributeError: value = func(instance) setattr(instance, self.attribute_name, value) return value update_wrapper(get, func) return property(get)
zope.cachedescriptors
/zope.cachedescriptors-5.0-py3-none-any.whl/zope/cachedescriptors/property.py
property.py
========= Changes ========= 5.0 (2023-09-01) ================ - Drop support for Python 2.7, 3.5, 3.6. - Drop support for deprecated ``python setup.py test``. - Add support for Python 3.11. 4.4.1 (2022-09-01) ================== - Fix deprecation warning. 4.4.0 (2022-04-06) ================== - Add support for Python 3.7, 3.8, 3.9, 3.10. - Drop support for Python 3.4. 4.3.0 (2021-03-19) ================== - Drop support for Python 3.3. - Replace deprecated usage of ``zope.site.hooks`` with ``zope.component.hooks``. - Replace deprecated test usage of ``zope.component.interfaces.IComponentLookup`` with the proper import from ``zope.interface``. This only impacted testing this package. 4.2.1 (2017-05-09) ================== - Fix the definition of ``IAttributeIndex`` to specify a ``NativeStringLine`` instead of a ``BytesLine``. Bytes cannot be used with ``getattr`` on Python 3. See `issue 7 <https://github.com/zopefoundation/zope.catalog/issues/7>`_. 4.2.0 (2017-05-05) ================== - Add support for Python 3.5 and 3.6. - Drop support for Python 2.6. - Fix the text index throwing a ``WrongType`` error on import in Python 3. See `issue 5 <https://github.com/zopefoundation/zope.catalog/issues/5>`_. 4.1.0 (2015-06-02) ================== - Replace use of long-deprecated ``zope.testing.doctest`` with stdlib's ``doctest``. - Add support for PyPy (PyPy3 support is blocked on a PyPy3-compatible release of ``zodbpickle``). - Convert doctests to Sphinx documentation, including building docs and running doctest snippets under ``tox``. 4.0.0 (2014-12-24) ================== - Add support for Python 3.4. 4.0.0a1 (2013-02-25) ==================== - Add support for Python 3.3. - Replace deprecated ``zope.interface.implements`` usage with equivalent ``zope.interface.implementer`` decorator. - Drop support for Python 2.4 and 2.5. 3.8.2 (2011-11-29) ================== - Conform to repository policy. 3.8.1 (2009-12-27) ================== - Remov ``zope.app.testing`` dependency. 3.8.0 (2009-02-01) ================== - Move core functionality from ``zope.app.catalog`` to this package. The ``zope.app.catalog`` package now only contains ZMI-related browser views and backward-compatibility imports.
zope.catalog
/zope.catalog-5.0.tar.gz/zope.catalog-5.0/CHANGES.rst
CHANGES.rst
============== zope.catalog ============== .. image:: https://img.shields.io/pypi/v/zope.catalog.svg :target: https://pypi.python.org/pypi/zope.catalog/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.catalog.svg :target: https://pypi.org/project/zope.catalog/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/zope.catalog/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.catalog/actions/workflows/tests.yml .. image:: https://coveralls.io/repos/github/zopefoundation/zope.catalog/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.catalog?branch=master .. image:: https://readthedocs.org/projects/zopecatalog/badge/?version=latest :target: http://zopecatalog.readthedocs.org/en/latest/ :alt: Documentation Status Catalogs provide management of collections of related indexes with a basic search algorithm.
zope.catalog
/zope.catalog-5.0.tar.gz/zope.catalog-5.0/README.rst
README.rst
import zope.container.constraints import zope.container.interfaces import zope.index.interfaces import zope.interface import zope.schema from zope.i18nmessageid import ZopeMessageFactory as _ class ICatalogQuery(zope.interface.Interface): """Provides Catalog Queries.""" def searchResults(**kw): """Search on the given indexes. Keyword arguments dictionary keys are index names and values are queries for these indexes. Keyword arguments has some special names, used by the catalog itself: * _sort_index - The name of index to sort results with. This index must implement zope.index.interfaces.IIndexSort. * _limit - Limit result set by this number, useful when used with sorting. * _reverse - Reverse result set, also useful with sorting. """ class ICatalogEdit(zope.index.interfaces.IInjection): """Allows one to manipulate the Catalog information.""" def updateIndexes(): """Reindex all objects.""" class ICatalogIndex(zope.index.interfaces.IInjection, zope.index.interfaces.IIndexSearch, ): """An index to be used in a catalog """ __parent__ = zope.schema.Field() zope.container.constraints.containers('.ICatalog') class ICatalog(ICatalogQuery, ICatalogEdit, zope.container.interfaces.IContainer): """Marker to describe a catalog in content space.""" zope.container.constraints.contains(ICatalogIndex) class IAttributeIndex(zope.interface.Interface): """I index objects by first adapting them to an interface, then retrieving a field on the adapted object. """ interface = zope.schema.Choice( title=_("Interface"), description=_("Objects will be adapted to this interface"), vocabulary="Interfaces", required=False, ) field_name = zope.schema.NativeStringLine( title=_("Field Name"), description=_("Name of the field to index"), ) field_callable = zope.schema.Bool( title=_("Field Callable"), description=_("If true, then the field should be called to get the " "value to be indexed"), ) class INoAutoIndex(zope.interface.Interface): """Marker for objects that should not be automatically indexed""" class INoAutoReindex(zope.interface.Interface): """Marker for objects that should not be automatically reindexed"""
zope.catalog
/zope.catalog-5.0.tar.gz/zope.catalog-5.0/src/zope/catalog/interfaces.py
interfaces.py
"""Catalog """ import BTrees import zope.index.interfaces from zope.annotation.interfaces import IAttributeAnnotatable from zope.container.btree import BTreeContainer from zope.interface import implementer from zope.intid.interfaces import IIntIdAddedEvent from zope.intid.interfaces import IIntIdRemovedEvent from zope.intid.interfaces import IIntIds from zope.lifecycleevent import IObjectModifiedEvent from zope.lifecycleevent.interfaces import IObjectAddedEvent from zope.location import location from zope.location.interfaces import ILocationInfo from zope import component from zope.catalog.interfaces import ICatalog from zope.catalog.interfaces import ICatalogIndex from zope.catalog.interfaces import INoAutoIndex from zope.catalog.interfaces import INoAutoReindex class ResultSet: """Lazily accessed set of objects.""" def __init__(self, uids, uidutil): self.uids = uids self.uidutil = uidutil def __len__(self): return len(self.uids) def __iter__(self): for uid in self.uids: obj = self.uidutil.getObject(uid) yield obj @implementer(ICatalog, IAttributeAnnotatable, zope.index.interfaces.IIndexSearch, ) class Catalog(BTreeContainer): family = BTrees.family32 def __init__(self, family=None): super().__init__() if family is not None: self.family = family def clear(self): for index in self.values(): index.clear() def index_doc(self, docid, texts): """Register the data in indexes of this catalog.""" for index in self.values(): index.index_doc(docid, texts) def unindex_doc(self, docid): """Unregister the data from indexes of this catalog.""" for index in self.values(): index.unindex_doc(docid) def _visitSublocations(self): """Restricts the access to the objects that live within the nearest site if the catalog itself is locatable. """ uidutil = None locatable = ILocationInfo(self, None) if locatable is not None: site = locatable.getNearestSite() sm = site.getSiteManager() uidutil = sm.queryUtility(IIntIds) if uidutil not in [c.component for c in sm.registeredUtilities()]: # we do not have a local inits utility uidutil = component.getUtility(IIntIds, context=self) for uid in uidutil: obj = uidutil.getObject(uid) if location.inside(obj, site): yield uid, obj return if uidutil is None: uidutil = component.getUtility(IIntIds) for uid in uidutil: yield uid, uidutil.getObject(uid) def updateIndex(self, index): for uid, obj in self._visitSublocations(): index.index_doc(uid, obj) def updateIndexes(self): for uid, obj in self._visitSublocations(): for index in self.values(): index.index_doc(uid, obj) def apply(self, query): results = [] for index_name, index_query in query.items(): index = self[index_name] r = index.apply(index_query) if r is None: continue if not r: # empty results return r results.append((len(r), r)) if not results: # no applicable indexes, so catalog was not applicable return None results.sort(key=lambda x: x[0]) # order from smallest to largest _, result = results.pop(0) for _, r in results: _, result = self.family.IF.weightedIntersection(result, r) return result def searchResults(self, **searchterms): sort_index = searchterms.pop('_sort_index', None) limit = searchterms.pop('_limit', None) reverse = searchterms.pop('_reverse', False) results = self.apply(searchterms) if results is not None: if sort_index is not None: index = self[sort_index] if not zope.index.interfaces.IIndexSort.providedBy(index): raise ValueError( 'Index %s does not support sorting.' % sort_index) results = list( index.sort( results, limit=limit, reverse=reverse)) else: if reverse or limit: results = list(results) if reverse: results.reverse() if limit: del results[limit:] uidutil = component.getUtility(IIntIds) results = ResultSet(results, uidutil) return results @component.adapter(ICatalogIndex, IObjectAddedEvent) def indexAdded(index, event): """When an index is added to a catalog, we have to index existing objects When an index is added, we tell it's parent to index it: >>> class FauxCatalog: ... updated = None ... def updateIndex(self, index): ... self.updated = index >>> class FauxIndex: ... pass >>> index = FauxIndex() >>> index.__parent__ = FauxCatalog() >>> from zope.catalog.catalog import indexAdded >>> indexAdded(index, None) >>> index.__parent__.updated is index True """ index.__parent__.updateIndex(index) @component.adapter(IIntIdAddedEvent) def indexDocSubscriber(event): """A subscriber to IntIdAddedEvent""" ob = event.object if INoAutoIndex.providedBy(ob): return for cat in component.getAllUtilitiesRegisteredFor(ICatalog, context=ob): id = component.getUtility(IIntIds, context=cat).getId(ob) cat.index_doc(id, ob) @component.adapter(IObjectModifiedEvent) def reindexDocSubscriber(event): """A subscriber to ObjectModifiedEvent""" ob = event.object if INoAutoReindex.providedBy(ob): return for cat in component.getAllUtilitiesRegisteredFor(ICatalog, context=ob): id = component.getUtility(IIntIds, context=cat).queryId(ob) if id is not None: cat.index_doc(id, ob) @component.adapter(IIntIdRemovedEvent) def unindexDocSubscriber(event): """A subscriber to IntIdRemovedEvent""" ob = event.object for cat in component.getAllUtilitiesRegisteredFor(ICatalog, context=ob): id = component.getUtility(IIntIds, context=cat).queryId(ob) if id is not None: cat.unindex_doc(id)
zope.catalog
/zope.catalog-5.0.tar.gz/zope.catalog-5.0/src/zope/catalog/catalog.py
catalog.py
"""Index interface-defined attributes """ __docformat__ = 'restructuredtext' import zope.interface from zope.catalog.interfaces import IAttributeIndex @zope.interface.implementer(IAttributeIndex) class AttributeIndex: """Index interface-defined attributes Mixin for indexing a particular attribute of an object after first adapting the object to be indexed to an interface. The class is meant to be mixed with a base class that defines an ``index_doc`` method and an ``unindex_doc`` method: >>> class BaseIndex(object): ... def __init__(self): ... self.data = [] ... def index_doc(self, id, value): ... self.data.append((id, value)) ... def unindex_doc(self, id): ... for n, (iid, _) in enumerate(self.data): ... if id == iid: ... del self.data[n] ... break The class does two things. The first is to get a named field from an object: >>> class Data(object): ... def __init__(self, v): ... self.x = v >>> from zope.catalog.attribute import AttributeIndex >>> class Index(AttributeIndex, BaseIndex): ... pass >>> index = Index('x') >>> index.index_doc(11, Data(1)) >>> index.index_doc(22, Data(2)) >>> index.data [(11, 1), (22, 2)] If the field value is ``None``, indexing it removes it from the index: >>> index.index_doc(11, Data(None)) >>> index.data [(22, 2)] If the field names a method (any callable object), the results of calling that field can be indexed: >>> def z(self): return self.x + 20 >>> Data.z = z >>> index = Index('z', field_callable=True) >>> index.index_doc(11, Data(1)) >>> index.index_doc(22, Data(2)) >>> index.data [(11, 21), (22, 22)] Of course, if you neglect to set ``field_callable`` when you index a method, it's likely that most concrete index implementations will raise an exception, but this class will happily pass that callable on: >>> index = Index('z') >>> data = Data(1) >>> index.index_doc(11, data) >>> index.data [(11, <bound method ...>>)] The class can also adapt an object to an interface before getting the field: >>> from zope.interface import Interface >>> class I(Interface): ... pass >>> class Data(object): ... def __init__(self, v): ... self.x = v ... def __conform__(self, iface): ... if iface is I: ... return Data2(self.x) >>> class Data2(object): ... def __init__(self, v): ... self.y = v * v >>> index = Index('y', I) >>> index.index_doc(11, Data(3)) >>> index.index_doc(22, Data(2)) >>> index.data [(11, 9), (22, 4)] If adapting to the interface fails, the object is not indexed: >>> class I2(Interface): pass >>> I2(Data(3), None) is None True >>> index = Index('y', I2) >>> index.index_doc(11, Data(3)) >>> index.data [] When you define an index class, you can define a default interface and/or a default interface: >>> class Index(AttributeIndex, BaseIndex): ... default_interface = I ... default_field_name = 'y' >>> index = Index() >>> index.index_doc(11, Data(3)) >>> index.index_doc(22, Data(2)) >>> index.data [(11, 9), (22, 4)] """ #: Subclasses can set this to a string if they want to allow #: construction without passing the ``field_name``. default_field_name = None #: Subclasses can set this to an interface (a callable taking #: the object do index and the default value to return) #: if they want to allow construction that doesn't provide an #: ``interface``. default_interface = None def __init__(self, field_name=None, interface=None, field_callable=False, *args, **kwargs): super().__init__(*args, **kwargs) if field_name is None and self.default_field_name is None: raise ValueError("Must pass a field_name") if field_name is None: self.field_name = self.default_field_name else: self.field_name = field_name if interface is None: self.interface = self.default_interface else: self.interface = interface self.field_callable = field_callable def index_doc(self, docid, object): """ Derives the value to index for *object*. Uses the interface passed to the constructor to adapt the object, and then gets the field (calling it if ``field_callable`` was set). If the value thus found is ``None``, calls ``unindex_doc``. Otherwise, passes the *docid* and the value to the superclass's implementation of ``index_doc``. """ if self.interface is not None: object = self.interface(object, None) if object is None: return None value = getattr(object, self.field_name, None) if value is not None and self.field_callable: # do not eat the exception raised below value = value() if value is None: # unindex the previous value! super().unindex_doc(docid) return None return super().index_doc(docid, value)
zope.catalog
/zope.catalog-5.0.tar.gz/zope.catalog-5.0/src/zope/catalog/attribute.py
attribute.py
============== zope.catalog ============== Interfaces ========== .. automodule:: zope.catalog.interfaces Catalog ======= .. automodule:: zope.catalog.catalog Index Implementations ===================== The implementations of various kinds of indexes are spread across a few modules. Attribute Indexes ----------------- .. automodule:: zope.catalog.attribute Field Indexes ------------- .. automodule:: zope.catalog.field Keyword Indexes --------------- .. automodule:: zope.catalog.keyword Text Indexes ------------ .. automodule:: zope.catalog.text
zope.catalog
/zope.catalog-5.0.tar.gz/zope.catalog-5.0/docs/api.rst
api.rst
Hacking on :mod:`zope.catalog` ============================== Getting the Code ################ The main repository for :mod:`zope.catalog` is in the Zope Foundation Github repository: https://github.com/zopefoundation/zope.catalog You can get a read-only checkout from there: .. code-block:: sh $ git clone https://github.com/zopefoundation/zope.catalog.git or fork it and get a writeable checkout of your fork: .. code-block:: sh $ git clone [email protected]/jrandom/zope.catalog.git The project also mirrors the trunk from the Github repository as a Bazaar branch on Launchpad: https://code.launchpad.net/zope.catalog You can branch the trunk from there using Bazaar: .. code-block:: sh $ bzr branch lp:zope.catalog 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.catalog Next, get this package registered as a "development egg" in the environment: .. code-block:: sh $ /tmp/hack-zope.catalog/bin/python setup.py develop Running the tests ----------------- Run the tests using the build-in ``setuptools`` testrunner: .. code-block:: sh $ /tmp/hack-zope.catalog/bin/python setup.py test running test ................. ---------------------------------------------------------------------- Ran 17 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.catalog/bin/easy_install nose ... $ /tmp/hack-zope.catalog/bin/nosetests ................. ---------------------------------------------------------------------- Ran 17 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.catalog/bin/easy_install nose coverage ... $ /tmp/hack-zope.catalog/bin/nosetests --with coverage running nosetests ................... Name Stmts Miss Cover Missing ---------------------------------------------------------- zope/catalog.py 0 0 100% zope/catalog/attribute.py 31 0 100% zope/catalog/catalog.py 125 0 100% zope/catalog/field.py 10 0 100% zope/catalog/interfaces.py 22 0 100% zope/catalog/keyword.py 13 0 100% zope/catalog/text.py 15 0 100% ---------------------------------------------------------- TOTAL 216 16 100% ---------------------------------------------------------------------- Ran 19 tests in 0.554s OK Building the documentation -------------------------- :mod:`zope.catalog` 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.catalog/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 =============== 117 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.catalog` 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.catalog/.' ... 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.catalog` 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.catalog` and dependencies, and runs the tests via ``python setup.py test -q``. - The ``coverage`` environment builds a ``virtualenv`` with ``python2.6``, installs :mod:`zope.catalog`, installs :mod:`nose` and :mod:`coverage`, and runs ``nosetests`` with statement coverage. - The ``docs`` environment builds a virtualenv with ``python2.6``, installs :mod:`zope.catalog`, 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 17 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 =============== 117 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.catalog` ################################### Submitting a Bug Report ----------------------- :mod:`zope.catalog` tracks its bugs on Github: https://github.com/zopefoundation/zope.catalog/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.catalog/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.catalog/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.catalog
/zope.catalog-5.0.tar.gz/zope.catalog-5.0/docs/hacking.rst
hacking.rst
=========================== Using :mod:`zope.catalog` =========================== .. testsetup:: from zope.testing.cleanup import setUp setUp() .. testcleanup:: from zope.testing.cleanup import tearDown tearDown() Basic Usage =========== Let's look at an example: .. doctest:: >>> from zope.catalog.catalog import Catalog >>> cat = Catalog() We can add catalog indexes to catalogs. A catalog index is, among other things, an attribute index. It indexes attributes of objects. To see how this works, we'll create a demonstration attribute index. Our attribute index will simply keep track of objects that have a given attribute value. The `catalog` package provides an attribute-index mix-in class that is meant to work with a base indexing class. First, we'll write the base index class: .. doctest:: >>> import persistent, BTrees.OOBTree, BTrees.IFBTree, BTrees.IOBTree >>> import zope.interface, zope.index.interfaces >>> @zope.interface.implementer( ... zope.index.interfaces.IInjection, ... zope.index.interfaces.IIndexSearch, ... zope.index.interfaces.IIndexSort, ... ) ... class BaseIndex(persistent.Persistent): ... ... def clear(self): ... self.forward = BTrees.OOBTree.OOBTree() ... self.backward = BTrees.IOBTree.IOBTree() ... ... __init__ = clear ... ... def index_doc(self, docid, value): ... if docid in self.backward: ... self.unindex_doc(docid) ... self.backward[docid] = value ... ... set = self.forward.get(value) ... if set is None: ... set = BTrees.IFBTree.IFTreeSet() ... self.forward[value] = set ... set.insert(docid) ... ... def unindex_doc(self, docid): ... value = self.backward.get(docid) ... if value is None: ... return ... self.forward[value].remove(docid) ... del self.backward[docid] ... ... def apply(self, value): ... set = self.forward.get(value) ... if set is None: ... set = BTrees.IFBTree.IFTreeSet() ... return set ... ... def sort(self, docids, limit=None, reverse=False): ... key_func = lambda x: self.backward.get(x, -1) ... for i, docid in enumerate( ... sorted(docids, key=key_func, reverse=reverse)): ... yield docid ... if limit and i >= (limit - 1): ... break The class implements `IInjection` to allow values to be indexed and unindexed and `IIndexSearch` to support searching via the `apply` method. Now, we can use the AttributeIndex mixin to make this an attribute index: .. doctest:: >>> import zope.catalog.attribute >>> import zope.catalog.interfaces >>> import zope.container.contained >>> @zope.interface.implementer(zope.catalog.interfaces.ICatalogIndex) ... class Index(zope.catalog.attribute.AttributeIndex, ... BaseIndex, ... zope.container.contained.Contained, ... ): ... pass Unfortunately, because of the way we currently handle containment constraints, we have to provide `ICatalogIndex`, which extends `IContained`. We subclass `Contained` to get an implementation for `IContained`. Now let's add some of these indexes to our catalog. Let's create some indexes. First we'll define some interfaces providing data to index: .. doctest:: >>> class IFavoriteColor(zope.interface.Interface): ... color = zope.interface.Attribute("Favorite color") >>> class IPerson(zope.interface.Interface): ... def age(): ... """Return the person's age, in years""" We'll create color and age indexes: .. doctest:: >>> cat['color'] = Index('color', IFavoriteColor) >>> cat['age'] = Index('age', IPerson, True) >>> cat['size'] = Index('sz') The indexes are created with: - the name of the of the attribute to index - the interface defining the attribute, and - a flag indicating whether the attribute should be called, which defaults to false. If an interface is provided, then we'll only be able to index an object if it can be adapted to the interface, otherwise, we'll simply try to get the attribute from the object. If the attribute isn't present, then we'll ignore the object. Now, let's create some objects and index them: .. doctest:: >>> @zope.interface.implementer(IPerson) ... class Person: ... def __init__(self, age): ... self._age = age ... def age(self): ... return self._age >>> @zope.interface.implementer(IFavoriteColor) ... class Discriminating: ... def __init__(self, color): ... self.color = color >>> class DiscriminatingPerson(Discriminating, Person): ... def __init__(self, age, color): ... Discriminating.__init__(self, color) ... Person.__init__(self, age) >>> class Whatever: ... def __init__(self, **kw): #** ... self.__dict__.update(kw) >>> o1 = Person(10) >>> o2 = DiscriminatingPerson(20, 'red') >>> o3 = Discriminating('blue') >>> o4 = Whatever(a=10, c='blue', sz=5) >>> o5 = Whatever(a=20, c='red', sz=6) >>> o6 = DiscriminatingPerson(10, 'blue') >>> cat.index_doc(1, o1) >>> cat.index_doc(2, o2) >>> cat.index_doc(3, o3) >>> cat.index_doc(4, o4) >>> cat.index_doc(5, o5) >>> cat.index_doc(6, o6) We search by providing query mapping objects that have a key for every index we want to use: .. doctest:: >>> list(cat.apply({'age': 10})) [1, 6] >>> list(cat.apply({'age': 10, 'color': 'blue'})) [6] >>> list(cat.apply({'age': 10, 'color': 'blue', 'size': 5})) [] >>> list(cat.apply({'size': 5})) [4] We can unindex objects: .. doctest:: >>> cat.unindex_doc(4) >>> list(cat.apply({'size': 5})) [] and reindex objects: .. doctest:: >>> o5.sz = 5 >>> cat.index_doc(5, o5) >>> list(cat.apply({'size': 5})) [5] If we clear the catalog, we'll clear all of the indexes: .. doctest:: >>> cat.clear() >>> [len(index.forward) for index in cat.values()] [0, 0, 0] Note that you don't have to use the catalog's search methods. You can access its indexes directly, since the catalog is a mapping: .. doctest:: >>> [(str(name), cat[name].field_name) for name in cat] [('age', 'age'), ('color', 'color'), ('size', 'sz')] Catalogs work with int-id utilities, which are responsible for maintaining id <-> object mappings. To see how this works, we'll create a utility to work with our catalog: .. doctest:: >>> import zope.intid.interfaces >>> @zope.interface.implementer(zope.intid.interfaces.IIntIds) ... class Ids: ... def __init__(self, data): ... self.data = data ... def getObject(self, id): ... return self.data[id] ... def __iter__(self): ... return iter(self.data) >>> ids = Ids({1: o1, 2: o2, 3: o3, 4: o4, 5: o5, 6: o6}) >>> from zope.component import provideUtility >>> provideUtility(ids, zope.intid.interfaces.IIntIds) With this utility in place, catalogs can recompute indexes: .. doctest:: >>> cat.updateIndex(cat['size']) >>> list(cat.apply({'size': 5})) [4, 5] Of course, that only updates *that* index: .. doctest:: >>> list(cat.apply({'age': 10})) [] We can update all of the indexes: .. doctest:: >>> cat.updateIndexes() >>> list(cat.apply({'age': 10})) [1, 6] >>> list(cat.apply({'color': 'red'})) [2] There's an alternate search interface that returns "result sets". Result sets provide access to objects, rather than object ids: .. doctest:: >>> result = cat.searchResults(size=5) >>> len(result) 2 >>> list(result) == [o4, o5] True The searchResults method also provides a way to sort, limit and reverse results. When not using sorting, limiting and reversing are done by simple slicing and list reversing. .. doctest:: >>> list(cat.searchResults(size=5, _reverse=True)) == [o5, o4] True >>> list(cat.searchResults(size=5, _limit=1)) == [o4] True >>> list(cat.searchResults(size=5, _limit=1, _reverse=True)) == [o5] True However, when using sorting by index, the limit and reverse parameters are passed to the index ``sort`` method so it can do it efficiently. Let's index more objects to work with: .. doctest:: >>> o7 = DiscriminatingPerson(7, 'blue') >>> o8 = DiscriminatingPerson(3, 'blue') >>> o9 = DiscriminatingPerson(14, 'blue') >>> o10 = DiscriminatingPerson(1, 'blue') >>> ids.data.update({7: o7, 8: o8, 9: o9, 10: o10}) >>> cat.index_doc(7, o7) >>> cat.index_doc(8, o8) >>> cat.index_doc(9, o9) >>> cat.index_doc(10, o10) Now we can search all people who like blue, ordered by age: .. doctest:: >>> results = list(cat.searchResults(color='blue', _sort_index='age')) >>> results == [o3, o10, o8, o7, o6, o9] True >>> results = list(cat.searchResults(color='blue', _sort_index='age', _limit=3)) >>> results == [o3, o10, o8] True >>> results = list(cat.searchResults(color='blue', _sort_index='age', _reverse=True)) >>> results == [o9, o6, o7, o8, o10, o3] True >>> results = list(cat.searchResults(color='blue', _sort_index='age', _reverse=True, _limit=4)) >>> results == [o9, o6, o7, o8] True The index example we looked at didn't provide document scores. Simple indexes normally don't, but more complex indexes might give results scores, according to how closely a document matches a query. Let's create a new index, a "keyword index" that indexes sequences of values: .. doctest:: >>> @zope.interface.implementer( ... zope.index.interfaces.IInjection, ... zope.index.interfaces.IIndexSearch, ... ) ... class BaseKeywordIndex(persistent.Persistent): ... ... def clear(self): ... self.forward = BTrees.OOBTree.OOBTree() ... self.backward = BTrees.IOBTree.IOBTree() ... ... __init__ = clear ... ... def index_doc(self, docid, values): ... if docid in self.backward: ... self.unindex_doc(docid) ... self.backward[docid] = values ... ... for value in values: ... set = self.forward.get(value) ... if set is None: ... set = BTrees.IFBTree.IFTreeSet() ... self.forward[value] = set ... set.insert(docid) ... ... def unindex_doc(self, docid): ... values = self.backward.get(docid) ... if values is None: ... return ... for value in values: ... self.forward[value].remove(docid) ... del self.backward[docid] ... ... def apply(self, values): ... result = BTrees.IFBTree.IFBucket() ... for value in values: ... set = self.forward.get(value) ... if set is not None: ... _, result = BTrees.IFBTree.weightedUnion(result, set) ... return result >>> @zope.interface.implementer(zope.catalog.interfaces.ICatalogIndex) ... class KeywordIndex(zope.catalog.attribute.AttributeIndex, ... BaseKeywordIndex, ... zope.container.contained.Contained, ... ): ... pass Now, we'll add a hobbies index: .. doctest:: >>> cat['hobbies'] = KeywordIndex('hobbies') >>> o1.hobbies = 'camping', 'music' >>> o2.hobbies = 'hacking', 'sailing' >>> o3.hobbies = 'music', 'camping', 'sailing' >>> o6.hobbies = 'cooking', 'dancing' >>> cat.updateIndexes() When we apply the catalog: .. doctest:: >>> cat.apply({'hobbies': ['music', 'camping', 'sailing']}) BTrees.IFBTree.IFBucket([(1, 2.0), (2, 1.0), (3, 3.0)]) We found objects 1-3, because they each contained at least some of the words in the query. The scores represent the number of words that matched. If we also include age: .. doctest:: >>> cat.apply({'hobbies': ['music', 'camping', 'sailing'], 'age': 10}) BTrees.IFBTree.IFBucket([(1, 3.0)]) The score increased because we used an additional index. If an index doesn't provide scores, scores of 1.0 are assumed. Additional Topics ================= .. toctree:: :maxdepth: 2 events
zope.catalog
/zope.catalog-5.0.tar.gz/zope.catalog-5.0/docs/narrative.rst
narrative.rst
Automatic indexing with events ============================== .. testsetup:: from zope.catalog.tests import placefulSetUp root = placefulSetUp() .. testcleanup:: from zope.catalog.tests import placefulTearDown placefulTearDown() In order to automatically keep the catalog up-to-date any objects that are added to a intid utility are indexed automatically. Also when an object gets modified it is reindexed by listening to IObjectModified events. Let us create a fake catalog to demonstrate this behaviour. We only need to implement the index_doc method for this test. .. doctest:: >>> from zope.catalog.interfaces import ICatalog >>> from zope import interface, component >>> @interface.implementer(ICatalog) ... class FakeCatalog(object): ... indexed = [] ... def index_doc(self, docid, obj): ... self.indexed.append((docid, obj)) >>> cat = FakeCatalog() >>> component.provideUtility(cat) We also need an intid util and a keyreference adapter. .. doctest:: >>> from zope.intid import IntIds >>> from zope.intid.interfaces import IIntIds >>> intids = IntIds() >>> component.provideUtility(intids, IIntIds) >>> from zope.keyreference.testing import SimpleKeyReference >>> component.provideAdapter(SimpleKeyReference) >>> from zope.container.contained import Contained >>> class Dummy(Contained): ... def __init__(self, name): ... self.__name__ = name ... def __repr__(self): ... return '<Dummy %r>' % str(self.__name__) We have a subscriber to IIntidAddedEvent. .. doctest:: >>> from zope.catalog import catalog >>> from zope.intid.interfaces import IntIdAddedEvent >>> d1 = Dummy(u'one') >>> id1 = intids.register(d1) >>> catalog.indexDocSubscriber(IntIdAddedEvent(d1, None)) Now we have indexed the object. .. doctest:: >>> cat.indexed.pop() (..., <Dummy 'one'>) When an object is modified an objectmodified event should be fired by the application. Here is the handler for such an event. .. doctest:: >>> from zope.lifecycleevent import ObjectModifiedEvent >>> catalog.reindexDocSubscriber(ObjectModifiedEvent(d1)) >>> len(cat.indexed) 1 >>> cat.indexed.pop() (..., <Dummy 'one'>) Preventing automatic indexing ----------------------------- Sometimes it is not accurate to automatically index an object. For example when a lot of indexes are in the catalog and only specific indexes needs to be updated. There are marker interfaces to achieve this. .. doctest:: >>> from zope.catalog.interfaces import INoAutoIndex If an object provides this interface it is not automatically indexed. .. doctest:: >>> interface.alsoProvides(d1, INoAutoIndex) >>> catalog.indexDocSubscriber(IntIdAddedEvent(d1, None)) >>> len(cat.indexed) 0 >>> from zope.catalog.interfaces import INoAutoReindex If an object provides this interface it is not automatically reindexed. .. doctest:: >>> interface.alsoProvides(d1, INoAutoReindex) >>> catalog.reindexDocSubscriber(ObjectModifiedEvent(d1)) >>> len(cat.indexed) 0
zope.catalog
/zope.catalog-5.0.tar.gz/zope.catalog-5.0/docs/events.rst
events.rst
"""zope.security support for the configuration handlers """ from zope.interface import providedBy from zope.proxy import ProxyBase from zope.proxy import getProxiedObject from zope.component._compat import ZOPE_SECURITY_NOT_AVAILABLE_EX try: from zope.security.adapter import LocatingTrustedAdapterFactory from zope.security.adapter import LocatingUntrustedAdapterFactory from zope.security.adapter import TrustedAdapterFactory from zope.security.checker import Checker from zope.security.checker import CheckerPublic from zope.security.checker import InterfaceChecker from zope.security.proxy import Proxy except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover def _no_security(*args, **kw): raise TypeError( "security proxied components are not " "supported because zope.security is not available") LocatingTrustedAdapterFactory = _no_security LocatingUntrustedAdapterFactory = _no_security TrustedAdapterFactory = _no_security Checker = _no_security CheckerPublic = _no_security InterfaceChecker = _no_security PublicPermission = 'zope.Public' class PermissionProxy(ProxyBase): __slots__ = ('__Security_checker__', ) def __providedBy__(self): return providedBy(getProxiedObject(self)) __providedBy__ = property(__providedBy__) def _checker(_context, permission, allowed_interface, allowed_attributes): if (not allowed_attributes) and (not allowed_interface): allowed_attributes = ["__call__"] if permission == PublicPermission: permission = CheckerPublic require = {} if allowed_attributes: for name in allowed_attributes: require[name] = permission if allowed_interface: for i in allowed_interface: for name in i.names(all=True): require[name] = permission checker = Checker(require) return checker def proxify(ob, checker=None, provides=None, permission=None): """Try to get the object proxied with the `checker`, but not too soon We really don't want to proxy the object unless we need to. """ if checker is None: if provides is None or permission is None: raise ValueError('Required arguments: ' 'checker or both provides and permissions') if permission == PublicPermission: permission = CheckerPublic checker = InterfaceChecker(provides, permission) ob = PermissionProxy(ob) ob.__Security_checker__ = checker return ob def protectedFactory(original_factory, provides, permission): if permission == PublicPermission: permission = CheckerPublic checker = InterfaceChecker(provides, permission) # This has to be named 'factory', aparently, so as not to confuse apidoc :( def factory(*args): ob = original_factory(*args) try: ob.__Security_checker__ = checker except AttributeError: ob = Proxy(ob, checker) return ob factory.factory = original_factory return factory def securityAdapterFactory(factory, permission, locate, trusted): if permission == PublicPermission: permission = CheckerPublic if locate or (permission is not None and permission is not CheckerPublic): if trusted: return LocatingTrustedAdapterFactory(factory) else: return LocatingUntrustedAdapterFactory(factory) elif trusted: return TrustedAdapterFactory(factory) else: return factory
zope.component
/zope.component-6.0-py3-none-any.whl/zope/component/security.py
security.py
"""Zope 3 Component Architecture """ import sys import zope.interface.interface from zope.hookable import hookable from zope.interface import Interface from zope.interface.interfaces import ComponentLookupError from zope.interface.interfaces import IComponentLookup from zope.component.interfaces import IFactory from zope.component.interfaces import inherits_arch_docs as inherits_docs # getSiteManager() returns a component registry. Although the term # "site manager" is deprecated in favor of "component registry", # the old term is kept around to maintain a stable API. base = None @hookable @inherits_docs def getSiteManager(context=None): """ See IComponentArchitecture. """ global base if context is None: if base is None: from zope.component.globalregistry import base return base else: # Use the global site manager to adapt context to `IComponentLookup` # to avoid the recursion implied by using a local `getAdapter()` call. try: return IComponentLookup(context) except TypeError as error: raise ComponentLookupError(*error.args) # Adapter API @inherits_docs def getAdapterInContext(object, interface, context): adapter = queryAdapterInContext(object, interface, context) if adapter is None: raise ComponentLookupError(object, interface) return adapter @inherits_docs def queryAdapterInContext(object, interface, context, default=None): conform = getattr(object, '__conform__', None) if conform is not None: try: adapter = conform(interface) except TypeError: # We got a TypeError. It might be an error raised by # the __conform__ implementation, or *we* may have # made the TypeError by calling an unbound method # (object is a class). In the later case, we behave # as though there is no __conform__ method. We can # detect this case by checking whether there is more # than one traceback object in the traceback chain: if sys.exc_info()[2].tb_next is not None: # There is more than one entry in the chain, so # reraise the error: raise # This clever trick is from Phillip Eby else: if adapter is not None: return adapter if interface.providedBy(object): return object return getSiteManager(context).queryAdapter(object, interface, '', default) @inherits_docs def getAdapter(object, interface=Interface, name='', context=None): adapter = queryAdapter(object, interface, name, None, context) if adapter is None: raise ComponentLookupError(object, interface, name) return adapter @inherits_docs def queryAdapter(object, interface=Interface, name='', default=None, context=None): if context is None: return adapter_hook(interface, object, name, default) return getSiteManager(context).queryAdapter(object, interface, name, default) @inherits_docs def getMultiAdapter(objects, interface=Interface, name='', context=None): adapter = queryMultiAdapter(objects, interface, name, context=context) if adapter is None: raise ComponentLookupError(objects, interface, name) return adapter @inherits_docs def queryMultiAdapter(objects, interface=Interface, name='', default=None, context=None): try: sitemanager = getSiteManager(context) except ComponentLookupError: # Oh blast, no site manager. This should *never* happen! return default return sitemanager.queryMultiAdapter(objects, interface, name, default) @inherits_docs def getAdapters(objects, provided, context=None): try: sitemanager = getSiteManager(context) except ComponentLookupError: # Oh blast, no site manager. This should *never* happen! return [] return sitemanager.getAdapters(objects, provided) @inherits_docs def subscribers(objects, interface, context=None): try: sitemanager = getSiteManager(context) except ComponentLookupError: # Oh blast, no site manager. This should *never* happen! return [] return sitemanager.subscribers(objects, interface) @inherits_docs def handle(*objects): getSiteManager(None).subscribers(objects, None) ############################################################################# # Register the component architectures adapter hook, with the adapter hook # registry of the `zope.inteface` package. This way we will be able to call # interfaces to create adapters for objects. For example, `I1(ob)` is # equvalent to `getAdapterInContext(I1, ob, '')`. @hookable def adapter_hook(interface, object, name='', default=None): try: sitemanager = getSiteManager() except ComponentLookupError: # pragma: no cover w/o context, cannot test # Oh blast, no site manager. This should *never* happen! return None return sitemanager.queryAdapter(object, interface, name, default) zope.interface.interface.adapter_hooks.append(adapter_hook) ############################################################################# # Utility API @inherits_docs def getUtility(interface, name='', context=None): utility = queryUtility(interface, name, context=context) if utility is not None: return utility raise ComponentLookupError(interface, name) @inherits_docs def queryUtility(interface, name='', default=None, context=None): return getSiteManager(context).queryUtility(interface, name, default) @inherits_docs def getUtilitiesFor(interface, context=None): return getSiteManager(context).getUtilitiesFor(interface) @inherits_docs def getAllUtilitiesRegisteredFor(interface, context=None): return getSiteManager(context).getAllUtilitiesRegisteredFor(interface) _marker = object() @inherits_docs def queryNextUtility(context, interface, name='', default=None): """Query for the next available utility. Find the next available utility providing `interface` and having the specified name. If no utility was found, return the specified `default` value. """ try: sm = getSiteManager(context) except ComponentLookupError: return default bases = sm.__bases__ for base in bases: util = base.queryUtility(interface, name, _marker) if util is not _marker: return util return default @inherits_docs def getNextUtility(context, interface, name=''): """Get the next available utility. If no utility was found, a `ComponentLookupError` is raised. """ util = queryNextUtility(context, interface, name, _marker) if util is _marker: raise ComponentLookupError( "No more utilities for {}, '{}' have been found.".format( interface, name)) return util # Factories @inherits_docs def createObject(__factory_name, *args, **kwargs): """Invoke the named factory and return the result. ``__factory_name`` is a positional-only argument. """ context = kwargs.pop('context', None) return getUtility(IFactory, __factory_name, context)(*args, **kwargs) @inherits_docs def getFactoryInterfaces(name, context=None): """Return the interface provided by the named factory's objects Result might be a single interface. XXX """ return getUtility(IFactory, name, context).getInterfaces() @inherits_docs def getFactoriesFor(interface, context=None): """Return info on all factories implementing the given interface. """ utils = getSiteManager(context) for (name, factory) in utils.getUtilitiesFor(IFactory): interfaces = factory.getInterfaces() try: if interfaces.isOrExtends(interface): yield name, factory except AttributeError: for iface in interfaces: if iface.isOrExtends(interface): yield name, factory break
zope.component
/zope.component-6.0-py3-none-any.whl/zope/component/_api.py
_api.py
"""Component Architecture configuration handlers """ from zope.configuration.exceptions import ConfigurationError from zope.configuration.fields import Bool from zope.configuration.fields import GlobalInterface from zope.configuration.fields import GlobalObject from zope.configuration.fields import PythonIdentifier from zope.configuration.fields import Tokens from zope.i18nmessageid import MessageFactory from zope.interface import Interface from zope.interface import implementedBy from zope.interface import providedBy from zope.schema import TextLine from zope.component._api import getSiteManager from zope.component._compat import ZOPE_SECURITY_NOT_AVAILABLE_EX from zope.component._declaration import adaptedBy from zope.component._declaration import getName from zope.component.interface import provideInterface try: from zope.security.zcml import Permission except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover def _no_security(*args, **kw): raise ConfigurationError( "security proxied components are not " "supported because zope.security is not available") _checker = proxify = protectedFactory = security = _no_security Permission = TextLine else: from zope.component.security import _checker from zope.component.security import protectedFactory from zope.component.security import proxify from zope.component.security import securityAdapterFactory _ = MessageFactory('zope') class ComponentConfigurationError(ValueError, ConfigurationError): pass def handler(methodName, *args, **kwargs): method = getattr(getSiteManager(), methodName) method(*args, **kwargs) class IBasicComponentInformation(Interface): component = GlobalObject( title=_("Component to use"), description=_("Python name of the implementation object. This" " must identify an object in a module using the" " full dotted name. If specified, the" " ``factory`` field must be left blank."), required=False, ) permission = Permission( title=_("Permission"), description=_("Permission required to use this component."), required=False, ) factory = GlobalObject( title=_("Factory"), description=_("Python name of a factory which can create the" " implementation object. This must identify an" " object in a module using the full dotted name." " If specified, the ``component`` field must" " be left blank."), required=False, ) class IAdapterDirective(Interface): """ Register an adapter """ factory = Tokens( title=_("Adapter factory/factories"), description=_("A list of factories (usually just one) that create" " the adapter instance."), required=True, value_type=GlobalObject() ) provides = GlobalInterface( title=_("Interface the component provides"), description=_("This attribute specifies the interface the adapter" " instance must provide."), required=False, ) for_ = Tokens( title=_("Specifications to be adapted"), description=_("This should be a list of interfaces or classes"), required=False, value_type=GlobalObject( missing_value=object(), ), ) permission = Permission( title=_("Permission"), description=_("This adapter is only available, if the principal" " has this permission."), required=False, ) name = TextLine( title=_("Name"), description=_("Adapters can have names.\n\n" "This attribute allows you to specify the name for" " this adapter."), required=False, ) trusted = Bool( title=_("Trusted"), description=_("""Make the adapter a trusted adapter Trusted adapters have unfettered access to the objects they adapt. If asked to adapt security-proxied objects, then, rather than getting an unproxied adapter of security-proxied objects, you get a security-proxied adapter of unproxied objects. """), required=False, default=False, ) locate = Bool( title=_("Locate"), description=_("""Make the adapter a locatable adapter Located adapter should be used if a non-public permission is used. """), required=False, default=False, ) def _rolledUpFactory(factories): # This has to be named 'factory', aparently, so as not to confuse # apidoc :( def factory(ob): for f in factories: ob = f(ob) return ob # Store the original factory for documentation factory.factory = factories[0] return factory def adapter(_context, factory, provides=None, for_=None, permission=None, name='', trusted=False, locate=False): if for_ is None: if len(factory) == 1: for_ = adaptedBy(factory[0]) if for_ is None: raise TypeError("No for attribute was provided and can't " "determine what the factory adapts.") for_ = tuple(for_) if provides is None: if len(factory) == 1: p = list(implementedBy(factory[0])) if len(p) == 1: provides = p[0] if provides is None: raise TypeError("Missing 'provides' attribute") if name == '': if len(factory) == 1: name = getName(factory[0]) # Generate a single factory from multiple factories: factories = factory if len(factories) == 1: factory = factories[0] elif len(factories) < 1: raise ComponentConfigurationError("No factory specified") elif len(factories) > 1 and len(for_) != 1: raise ComponentConfigurationError( "Can't use multiple factories and multiple for") else: factory = _rolledUpFactory(factories) if permission is not None: factory = protectedFactory(factory, provides, permission) # invoke custom adapter factories if locate or permission is not None or trusted: factory = securityAdapterFactory(factory, permission, locate, trusted) _context.action( discriminator=('adapter', for_, provides, name), callable=handler, args=('registerAdapter', factory, for_, provides, name, _context.info), ) _context.action( discriminator=None, callable=provideInterface, args=('', provides) ) if for_: for iface in for_: if iface is not None: _context.action( discriminator=None, callable=provideInterface, args=('', iface) ) class ISubscriberDirective(Interface): """ Register a subscriber """ factory = GlobalObject( title=_("Subscriber factory"), description=_("A factory used to create the subscriber instance."), required=False, ) handler = GlobalObject( title=_("Handler"), description=_("A callable object that handles events."), required=False, ) provides = GlobalInterface( title=_("Interface the component provides"), description=_("This attribute specifies the interface the adapter" " instance must provide."), required=False, ) for_ = Tokens( title=_("Interfaces or classes that this subscriber depends on"), description=_("This should be a list of interfaces or classes"), required=False, value_type=GlobalObject( missing_value=object(), ), ) permission = Permission( title=_("Permission"), description=_("This subscriber is only available, if the" " principal has this permission."), required=False, ) trusted = Bool( title=_("Trusted"), description=_("""Make the subscriber a trusted subscriber Trusted subscribers have unfettered access to the objects they adapt. If asked to adapt security-proxied objects, then, rather than getting an unproxied subscriber of security-proxied objects, you get a security-proxied subscriber of unproxied objects. """), required=False, default=False, ) locate = Bool( title=_("Locate"), description=_("""Make the subscriber a locatable subscriber Located subscribers should be used if a non-public permission is used. """), required=False, default=False, ) _handler = handler def subscriber(_context, for_=None, factory=None, handler=None, provides=None, permission=None, trusted=False, locate=False): if factory is None: if handler is None: raise TypeError("No factory or handler provided") if provides is not None: raise TypeError("Cannot use handler with provides") factory = handler else: if handler is not None: raise TypeError("Cannot use handler with factory") if provides is None: p = list(implementedBy(factory)) if len(p) == 1: provides = p[0] if provides is None: raise TypeError( "You must specify a provided interface when registering " "a factory") if for_ is None: for_ = adaptedBy(factory) if for_ is None: raise TypeError("No for attribute was provided and can't " "determine what the factory (or handler) adapts.") if permission is not None: factory = protectedFactory(factory, provides, permission) for_ = tuple(for_) # invoke custom adapter factories if locate or permission is not None or trusted: factory = securityAdapterFactory(factory, permission, locate, trusted) if handler is not None: _context.action( discriminator=None, callable=_handler, args=('registerHandler', handler, for_, '', _context.info), ) else: _context.action( discriminator=None, callable=_handler, args=('registerSubscriptionAdapter', factory, for_, provides, '', _context.info), ) if provides is not None: _context.action( discriminator=None, callable=provideInterface, args=('', provides) ) # For each interface, state that the adapter provides that interface. for iface in for_: if iface is not None: _context.action( discriminator=None, callable=provideInterface, args=('', iface) ) class IUtilityDirective(IBasicComponentInformation): """Register a utility.""" provides = GlobalInterface( title=_("Provided interface"), description=_("Interface provided by the utility."), required=False, ) name = TextLine( title=_("Name"), description=_("Name of the registration. This is used by" " application code when locating a utility."), required=False, ) def utility(_context, provides=None, component=None, factory=None, permission=None, name=''): if factory and component: raise TypeError("Can't specify factory and component.") if provides is None: if factory: provides = list(implementedBy(factory)) else: provides = list(providedBy(component)) if len(provides) == 1: provides = provides[0] else: raise TypeError("Missing 'provides' attribute") if name == '': if factory: name = getName(factory) else: name = getName(component) if permission is not None: if component: component = proxify(component, provides=provides, permission=permission) if factory: factory = protectedFactory(factory, provides, permission) _context.action( discriminator=('utility', provides, name), callable=handler, args=('registerUtility', component, provides, name, _context.info), kw=dict(factory=factory), ) _context.action( discriminator=None, callable=provideInterface, args=('', provides), ) class IInterfaceDirective(Interface): """ Define an interface """ interface = GlobalInterface( title=_("Interface"), required=True, ) type = GlobalInterface( title=_("Interface type"), required=False, ) name = TextLine( title=_("Name"), required=False, ) def interface(_context, interface, type=None, name=''): _context.action( discriminator=None, callable=provideInterface, args=(name, interface, type) ) class IBasicViewInformation(Interface): """This is the basic information for all views.""" for_ = Tokens( title=_("Specifications of the objects to be viewed"), description=_("""This should be a list of interfaces or classes """), required=True, value_type=GlobalObject( missing_value=object(), ), ) permission = Permission( title=_("Permission"), description=_("The permission needed to use the view."), required=False, ) class_ = GlobalObject( title=_("Class"), description=_("A class that provides attributes used by the view."), required=False, ) allowed_interface = Tokens( title=_("Interface that is also allowed if user has permission."), description=_(""" By default, 'permission' only applies to viewing the view and any possible sub views. By specifying this attribute, you can make the permission also apply to everything described in the supplied interface. Multiple interfaces can be provided, separated by whitespace."""), required=False, value_type=GlobalInterface(), ) allowed_attributes = Tokens( title=_("View attributes that are also allowed if the user" " has permission."), description=_(""" By default, 'permission' only applies to viewing the view and any possible sub views. By specifying 'allowed_attributes', you can make the permission also apply to the extra attributes on the view object."""), required=False, value_type=PythonIdentifier(), ) class IBasicResourceInformation(Interface): """ Basic information for resources """ name = TextLine( title=_("The name of the resource."), description=_("The name shows up in URLs/paths. For example 'foo'."), required=True, default='', ) provides = GlobalInterface( title=_("The interface this component provides."), description=_(""" A view can provide an interface. This would be used for views that support other views."""), required=False, default=Interface, ) type = GlobalInterface( title=_("Request type"), required=True ) class IViewDirective(IBasicViewInformation, IBasicResourceInformation): """Register a view for a component""" factory = Tokens( title=_("Factory"), required=False, value_type=GlobalObject(), ) def view(_context, factory, type, name, for_, permission=None, allowed_interface=None, allowed_attributes=None, provides=Interface, ): if ((allowed_attributes or allowed_interface) and (not permission)): raise ComponentConfigurationError( "'permission' required with 'allowed_interface' or " "'allowed_attributes'") if permission is not None: checker = _checker(_context, permission, allowed_interface, allowed_attributes) class ProxyView: """Class to create simple proxy views.""" def __init__(self, factory, checker): self.factory = factory self.checker = checker def __call__(self, *objects): return proxify(self.factory(*objects), self.checker) factory[-1] = ProxyView(factory[-1], checker) if not for_: raise ComponentConfigurationError("No for interfaces specified") for_ = tuple(for_) # Generate a single factory from multiple factories: factories = factory if len(factories) == 1: factory = factories[0] elif len(factories) < 1: raise ComponentConfigurationError("No view factory specified") elif len(factories) > 1 and len(for_) > 1: raise ComponentConfigurationError( "Can't use multiple factories and multiple for") else: def factory(ob, request): for f in factories[:-1]: ob = f(ob) return factories[-1](ob, request) factory.factory = factories[0] for_ = for_ + (type,) _context.action( discriminator=('view', for_, name, provides), callable=handler, args=('registerAdapter', factory, for_, provides, name, _context.info), ) _context.action( discriminator=None, callable=provideInterface, args=('', provides) ) if for_ is not None: for iface in for_: if iface is not None: _context.action( discriminator=None, callable=provideInterface, args=('', iface) ) class IResourceDirective(IBasicComponentInformation, IBasicResourceInformation): """Register a resource""" allowed_interface = Tokens( title=_("Interface that is also allowed if user has permission."), required=False, value_type=GlobalInterface(), ) allowed_attributes = Tokens( title=_("View attributes that are also allowed if user" " has permission."), required=False, value_type=PythonIdentifier(), ) def resource(_context, factory, type, name, permission=None, allowed_interface=None, allowed_attributes=None, provides=Interface): if ((allowed_attributes or allowed_interface) and (not permission)): raise ComponentConfigurationError( "Must use name attribute with allowed_interface or " "allowed_attributes" ) if permission is not None: checker = _checker(_context, permission, allowed_interface, allowed_attributes) def proxyResource(request, factory=factory, checker=checker): return proxify(factory(request), checker) proxyResource.factory = factory factory = proxyResource _context.action( discriminator=('resource', name, type, provides), callable=handler, args=('registerAdapter', factory, (type,), provides, name, _context.info)) _context.action( discriminator=None, callable=provideInterface, args=('', type)) _context.action( discriminator=None, callable=provideInterface, args=('', provides))
zope.component
/zope.component-6.0-py3-none-any.whl/zope/component/zcml.py
zcml.py
from zope.interface import Attribute from zope.interface import Interface # pylint:disable=inherit-non-class,no-self-argument,no-method-argument class IComponentArchitecture(Interface): """The Component Architecture is defined by two key components: Adapters and Utiltities. Both are managed by site managers. All other components build on top of them. """ # Site Manager API def getGlobalSiteManager(): """Return the global site manager. This function should never fail and always return an object that provides `zope.interface.interfaces.IComponents`. """ def getSiteManager(context=None): """Get the nearest site manager in the given context. If *context* is `None`, return the global site manager. If the *context* is not `None`, it is expected that an adapter from the *context* to :mod:`zope.interface.interfaces.IComponentLookup` can be found. If no adapter is found, a `~zope.interface.interfaces.ComponentLookupError` is raised. """ # Utility API def getUtility(interface, name='', context=None): """Get the utility that provides interface Returns the nearest utility to the context that implements the specified interface. If one is not found, raises `~zope.interface.interfaces.ComponentLookupError`. """ def queryUtility(interface, name='', default=None, context=None): """Look for the utility that provides *interface* Returns the nearest utility to the *context* that implements the specified interface. If one is not found, returns *default*. """ def queryNextUtility(context, interface, name='', default=None): """Query for the next available utility. Find the next available utility providing *interface* and having the specified name. If no utility was found, return the specified *default* value. """ def getNextUtility(context, interface, name=''): """Get the next available utility. If no utility was found, a `~zope.interface.interfaces.ComponentLookupError` is raised. """ def getUtilitiesFor(interface, context=None): """Return the utilities that provide an interface An iterable of utility name-value pairs is returned. """ def getAllUtilitiesRegisteredFor(interface, context=None): """Return all registered utilities for an interface This includes overridden utilities. An iterable of utility instances is returned. No names are returned. """ # Adapter API def getAdapter(object, interface=Interface, name='', context=None): """Get a named adapter to an interface for an object Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, raises `~zope.interface.interfaces.ComponentLookupError`. """ def getAdapterInContext(object, interface, context): """Get a special adapter to an interface for an object .. note:: This method should only be used if a custom context needs to be provided to provide custom component lookup. Otherwise, call the interface, as in:: interface(object) Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, raises `~zope.interface.interfaces.ComponentLookupError`. If the object has a ``__conform__`` method, this method will be called with the requested interface. If the method returns a non-None value, that value will be returned. Otherwise, if the object already implements the interface, the object will be returned. """ def getMultiAdapter(objects, interface=Interface, name='', context=None): """Look for a multi-adapter to an *interface* for an *objects* Returns a multi-adapter that can adapt *objects* to *interface*. If a matching adapter cannot be found, raises `~zope.interface.interfaces.ComponentLookupError`. The name consisting of an empty string is reserved for unnamed adapters. The unnamed adapter methods will often call the named adapter methods with an empty string for a name. """ def queryAdapter(object, interface=Interface, name='', default=None, context=None): """Look for a named adapter to an interface for an object Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, returns the default. """ def queryAdapterInContext(object, interface, context, default=None): """ Look for a special adapter to an interface for an object .. note:: This method should only be used if a custom context needs to be provided to provide custom component lookup. Otherwise, call the interface, as in:: interface(object, default) Returns an adapter that can adapt object to interface. If a matching adapter cannot be found, returns the default. If the object has a ``__conform__`` method, this method will be called with the requested interface. If the method returns a non-None value, that value will be returned. Otherwise, if the object already implements the interface, the object will be returned. """ def queryMultiAdapter(objects, interface=Interface, name='', default=None, context=None): """Look for a multi-adapter to an interface for objects Returns a multi-adapter that can adapt objects to interface. If a matching adapter cannot be found, returns the default. The name consisting of an empty string is reserved for unnamed adapters. The unnamed adapter methods will often call the named adapter methods with an empty string for a name. """ def getAdapters(objects, provided, context=None): """ Look for all matching adapters to a provided interface for objects Return a list of adapters that match. If an adapter is named, only the most specific adapter of a given name is returned. """ def subscribers(required, provided, context=None): """Get subscribers Subscribers are returned that provide the provided interface and that depend on and are computed from the sequence of required objects. """ def handle(*objects): """Call all of the handlers for the given objects Handlers are subscription adapter factories that don't produce anything. They do all of their work when called. Handlers are typically used to handle events. """ def adapts(*interfaces): """ Declare that a class adapts the given interfaces. This function can only be used in a class definition. (TODO, allow classes to be passed as well as interfaces.) """ # Factory service def createObject(factory_name, *args, **kwargs): """Create an object using a factory Finds the named factory in the current site and calls it with the given arguments. If a matching factory cannot be found raises `~zope.interface.interfaces.ComponentLookupError`. Returns the created object. A context keyword argument can be provided to cause the factory to be looked up in a location other than the current site. (Of course, this means that it is impossible to pass a keyword argument named "context" to the factory. """ def getFactoryInterfaces(name, context=None): """Get interfaces implemented by a factory Finds the factory of the given name that is nearest to the context, and returns the interface or interface tuple that object instances created by the named factory will implement. """ def getFactoriesFor(interface, context=None): """Return a tuple (name, factory) of registered factories that create objects which implement the given interface. """ class IRegistry(Interface): """Object that supports component registry """ def registrations(): """Return an iterable of component registrations """ class IComponentRegistrationConvenience(Interface): """API for registering components. .. caution:: This API should only be used from test or application-setup code. This api shouldn't be used by regular library modules, as component registration is a configuration activity. """ def provideUtility(component, provides=None, name=''): """Register a utility globally A utility is registered to provide an interface with a name. If a component provides only one interface, then the provides argument can be omitted and the provided interface will be used. (In this case, provides argument can still be provided to provide a less specific interface.) """ def provideAdapter(factory, adapts=None, provides=None, name=''): """Register an adapter globally An adapter is registered to provide an interface with a name for some number of object types. If a factory implements only one interface, then the provides argument can be omitted and the provided interface will be used. (In this case, a provides argument can still be provided to provide a less specific interface.) If the factory has an adapts declaration, then the adapts argument can be omitted and the declaration will be used. (An adapts argument can be provided to override the declaration.) """ def provideSubscriptionAdapter(factory, adapts=None, provides=None): """Register a subscription adapter A subscription adapter is registered to provide an interface for some number of object types. If a factory implements only one interface, then the provides argument can be omitted and the provided interface will be used. (In this case, a provides argument can still be provided to provide a less specific interface.) If the factory has an adapts declaration, then the adapts argument can be omitted and the declaration will be used. (An adapts argument can be provided to override the declaration.) """ def provideHandler(handler, adapts=None): """Register a handler Handlers are subscription adapter factories that don't produce anything. They do all of their work when called. Handlers are typically used to handle events. If the handler has an adapts declaration, then the adapts argument can be omitted and the declaration will be used. (An adapts argument can be provided to override the declaration.) """ class IPossibleSite(Interface): """An object that could be a site. """ def setSiteManager(sitemanager): """Sets the site manager for this object. """ def getSiteManager(): """Returns the site manager contained in this object. If there isn't a site manager, raise a component lookup. """ class ISite(IPossibleSite): """Marker interface to indicate that we have a site""" class Misused(Exception): """A component is being used (registered) for the wrong interface.""" class IFactory(Interface): """A factory is responsible for creating other components.""" title = Attribute("The factory title.") description = Attribute("A brief description of the factory.") def __call__(*args, **kw): """Return an instance of the objects we're a factory for.""" def getInterfaces(): """Get the interfaces implemented by the factory Return the interface(s), as an instance of Implements, that objects created by this factory will implement. If the callable's Implements instance cannot be created, an empty Implements instance is returned. """ # Internal helpers def _inherits_docs(func, iface): doc = iface[func.__name__].__doc__ # doc can be None if the interpreter drops all docstrings when the # environment variable PYTHONOPTIMIZE is set 2. if doc is None: return func # pragma: no cover # By adding the ..seealso:: we get a link from our overview page # to the specific narrative place where the function is described, because # our overview page uses :noindex: doc += "\n .. seealso::" doc += f"\n Function `~zope.component.{func.__name__}` for" doc += " notes, and " doc += f"\n `~zope.component.interfaces.{iface.__name__}` for" doc += " the defining interface.\n" func.__doc__ = doc return func def inherits_arch_docs(func): return _inherits_docs(func, IComponentArchitecture) def inherits_reg_docs(func): return _inherits_docs(func, IComponentRegistrationConvenience)
zope.component
/zope.component-6.0-py3-none-any.whl/zope/component/interfaces.py
interfaces.py
"""Global components support """ from zope.interface.adapter import AdapterRegistry from zope.interface.registry import Components from zope.component.interfaces import inherits_arch_docs from zope.component.interfaces import inherits_reg_docs def GAR(components, registryName): return getattr(components, registryName) class GlobalAdapterRegistry(AdapterRegistry): """A global adapter registry This adapter registry's main purpose is to be picklable in combination with a site manager.""" def __init__(self, parent, name): self.__parent__ = parent self.__name__ = name super().__init__() def __reduce__(self): return GAR, (self.__parent__, self.__name__) class BaseGlobalComponents(Components): def _init_registries(self): self.adapters = GlobalAdapterRegistry(self, 'adapters') self.utilities = GlobalAdapterRegistry(self, 'utilities') def __reduce__(self): # Global site managers are pickled as global objects return self.__name__ base = BaseGlobalComponents('base') try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover pass else: addCleanUp(lambda: base.__init__('base')) del addCleanUp globalSiteManager = base @inherits_arch_docs def getGlobalSiteManager(): return globalSiteManager # The following APIs provide global registration support for Python code. # We eventually want to deprecate these in favor of using the global # component registry directly. @inherits_reg_docs def provideUtility(component, provides=None, name=''): base.registerUtility(component, provides, name, event=False) @inherits_reg_docs def provideAdapter(factory, adapts=None, provides=None, name=''): base.registerAdapter(factory, adapts, provides, name, event=False) @inherits_reg_docs def provideSubscriptionAdapter(factory, adapts=None, provides=None): base.registerSubscriptionAdapter(factory, adapts, provides, event=False) @inherits_reg_docs def provideHandler(factory, adapts=None): base.registerHandler(factory, adapts, event=False)
zope.component
/zope.component-6.0-py3-none-any.whl/zope/component/globalregistry.py
globalregistry.py
"""Hooks for getting and setting a site in the thread global namespace. """ __docformat__ = 'restructuredtext' import contextlib import threading from zope.component._compat import ZOPE_SECURITY_NOT_AVAILABLE_EX try: from zope.security.proxy import removeSecurityProxy except ZOPE_SECURITY_NOT_AVAILABLE_EX: # pragma: no cover def removeSecurityProxy(x): return x from zope.interface.interfaces import ComponentLookupError from zope.interface.interfaces import IComponentLookup from zope.component.globalregistry import getGlobalSiteManager __all__ = [ 'setSite', 'getSite', 'site', 'getSiteManager', 'setHooks', 'resetHooks', ] class read_property: """Descriptor for property-like computed attributes. Unlike the standard 'property', this descriptor allows assigning a value to the instance, shadowing the property getter function. """ def __init__(self, func): self.func = func def __get__(self, inst, cls): if inst is None: return self return self.func(inst) class SiteInfo(threading.local): site = None sm = getGlobalSiteManager() @read_property def adapter_hook(self): adapter_hook = self.sm.adapters.adapter_hook self.adapter_hook = adapter_hook return adapter_hook siteinfo = SiteInfo() def setSite(site=None): if site is None: sm = getGlobalSiteManager() else: # We remove the security proxy because there's no way for # untrusted code to get at it without it being proxied again. # We should really look look at this again though, especially # once site managers do less. There's probably no good reason why # they can't be proxied. Well, except maybe for performance. site = removeSecurityProxy(site) # The getSiteManager method is defined by IPossibleSite. sm = site.getSiteManager() siteinfo.site = site siteinfo.sm = sm try: del siteinfo.adapter_hook except AttributeError: pass def getSite(): return siteinfo.site @contextlib.contextmanager def site(site): """ site(site) -> None Context manager that sets *site* as the current site for the duration of the ``with`` body. """ old_site = getSite() setSite(site) try: yield finally: setSite(old_site) def getSiteManager(context=None): """A special hook for getting the site manager. Here we take the currently set site into account to find the appropriate site manager. """ if context is None: return siteinfo.sm # We remove the security proxy because there's no way for # untrusted code to get at it without it being proxied again. # We should really look look at this again though, especially # once site managers do less. There's probably no good reason why # they can't be proxied. Well, except maybe for performance. sm = IComponentLookup( context, getGlobalSiteManager()) sm = removeSecurityProxy(sm) return sm def adapter_hook(interface, object, name='', default=None): try: return siteinfo.adapter_hook(interface, object, name, default) except ComponentLookupError: return default def setHooks(): """ Make `zope.component.getSiteManager` and interface adaptation respect the current site. Most applications will want to be sure te call this early in their startup sequence. Test code that uses these APIs should also arrange to call this. .. seealso:: :mod:`zope.component.testlayer` """ from zope.component import _api _api.adapter_hook.sethook(adapter_hook) _api.getSiteManager.sethook(getSiteManager) def resetHooks(): """ Reset `zope.component.getSiteManager` and interface adaptation to their original implementations that are unaware of the current site. Use caution when calling this; most code will not need to call this. If code using the global API executes following this, it will most likely use the base global component registry instead of a site-specific registry it was expected. This can lead to failures in adaptation and utility lookup. """ # Reset hookable functions to original implementation. from zope.component import _api _api.adapter_hook.reset() _api.getSiteManager.reset() # be sure the old adapter hook isn't cached, since # it is derived from the SiteManager try: del siteinfo.adapter_hook except AttributeError: pass # Clear the site thread global clearSite = setSite try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover pass else: addCleanUp(resetHooks)
zope.component
/zope.component-6.0-py3-none-any.whl/zope/component/hooks.py
hooks.py
"""Interface utility functions """ from zope.interface import alsoProvides from zope.interface.interfaces import ComponentLookupError from zope.interface.interfaces import IInterface from zope.component._api import getSiteManager from zope.component._api import queryUtility def provideInterface(id, interface, iface_type=None, info=''): """ Mark *interface* as a named utility providing *iface_type*'. .. versionchanged:: 5.0.0 The named utility is registered in the current site manager. Previously it was always registered in the global site manager. """ if not id: id = "{}.{}".format(interface.__module__, interface.__name__) if not IInterface.providedBy(interface): if not isinstance(interface, type): raise TypeError(id, "is not an interface or class") return if iface_type is not None: if not iface_type.extends(IInterface): raise TypeError(iface_type, "is not an interface type") alsoProvides(interface, iface_type) else: iface_type = IInterface site_man = getSiteManager() site_man.registerUtility(interface, iface_type, id, info) def getInterface(context, id): """Return interface or raise ComponentLookupError """ iface = queryInterface(id, None) if iface is None: raise ComponentLookupError(id) return iface def queryInterface(id, default=None): """Return an interface or ``None`` """ return queryUtility(IInterface, id, default) def searchInterface(context, search_string=None, base=None): """Interfaces search """ return [iface_util[1] for iface_util in searchInterfaceUtilities(context, search_string, base)] def searchInterfaceIds(context, search_string=None, base=None): """Interfaces search """ return [iface_util[0] for iface_util in searchInterfaceUtilities(context, search_string, base)] def searchInterfaceUtilities(context, search_string=None, base=None): site_man = getSiteManager() iface_utilities = site_man.getUtilitiesFor(IInterface) if search_string: search_string = search_string.lower() iface_utilities = [iface_util for iface_util in iface_utilities if (getInterfaceAllDocs(iface_util[1]). find(search_string) >= 0)] if base: res = [iface_util for iface_util in iface_utilities if iface_util[1].isOrExtends(base)] else: res = list(iface_utilities) return res def getInterfaceAllDocs(interface): iface_id = '{}.{}'.format(interface.__module__, interface.__name__) docs = [str(iface_id).lower(), str(interface.__doc__).lower()] if IInterface.providedBy(interface): for name in sorted(interface): docs.append( str(interface.getDescriptionFor(name).__doc__).lower()) return '\n'.join(docs) def nameToInterface(context, id): if id == 'None': return None iface = getInterface(context, id) return iface def interfaceToName(context, interface): if interface is None: return 'None' return '{}.{}'.format(interface.__module__, interface.__name__)
zope.component
/zope.component-6.0-py3-none-any.whl/zope/component/interface.py
interface.py
"""Persistent component managers. """ from persistent import Persistent from persistent.list import PersistentList from persistent.mapping import PersistentMapping from zope.interface.adapter import VerifyingAdapterRegistry from zope.interface.registry import Components class PersistentAdapterRegistry(VerifyingAdapterRegistry, Persistent): """ An adapter registry that is also a persistent object. .. versionchanged:: 5.0.0 Internal data structures are now composed of :class:`persistent.mapping.PersistentMapping` and :class:`persistent.list.PersistentList`. This helps scale to larger registries. Previously they were :class:`dict`, :class:`list` and :class:`tuple`, meaning that as soon as this object was unpickled, the entire registry tree had to be unpickled, and when a change was made (an object registered or unregisterd), the entire registry had to be pickled. Now, only the parts that are in use are loaded, and only the parts that are modified are stored. The above applies without reservation to newly created instances. For existing persistent instances, however, the data will continue to be in dicts and tuples, with some few exceptions for newly added or changed data. To fix this, call :meth:`rebuild` and commit the transaction. This will rewrite the internal data structures to use the new types. """ # The persistent types we use, replacing the basic types inherited # from ``BaseAdapterRegistry``. _sequenceType = PersistentList _leafSequenceType = PersistentList _mappingType = PersistentMapping _providedType = PersistentMapping # The methods needed to manipulate the leaves of the subscriber # tree. When we're manipulating unmigrated data, it's safe to # migrate it, but not otherwise (we don't want to write in an # otherwise read-only transaction). def _addValueToLeaf(self, existing_leaf_sequence, new_item): if not existing_leaf_sequence: existing_leaf_sequence = self._leafSequenceType() elif isinstance(existing_leaf_sequence, tuple): # Converting from old state. existing_leaf_sequence = self._leafSequenceType( existing_leaf_sequence) existing_leaf_sequence.append(new_item) return existing_leaf_sequence def _removeValueFromLeaf(self, existing_leaf_sequence, to_remove): if isinstance(existing_leaf_sequence, tuple): # Converting from old state existing_leaf_sequence = self._leafSequenceType( existing_leaf_sequence) without_removed = VerifyingAdapterRegistry._removeValueFromLeaf( self, existing_leaf_sequence, to_remove) existing_leaf_sequence[:] = without_removed return existing_leaf_sequence def changed(self, originally_changed): if originally_changed is self: # XXX: This is almost certainly redundant, even if we # have old data consisting of plain dict/list/tuple. That's # because the super class will now increment the ``_generation`` # attribute to keep caches in sync. For this same reason, # it's not worth trying to "optimize" for the case that we're a # new or rebuilt object containing only Persistent sub-objects: # the changed() mechanism will still result in mutating this # object via ``_generation``. self._p_changed = True super().changed(originally_changed) def __getstate__(self): state = super().__getstate__().copy() for name in self._delegated: state.pop(name, 0) state.pop('ro', None) return state def __setstate__(self, state): bases = state.pop('__bases__', ()) super().__setstate__(state) self._createLookup() self.__bases__ = bases self._v_lookup.changed(self) class PersistentComponents(Components): """ A component implementation that uses `PersistentAdapterRegistry`. Note that this object itself is *not* `Persistent`. """ def _init_registries(self): self.adapters = PersistentAdapterRegistry() self.utilities = PersistentAdapterRegistry() def _init_registrations(self): self._utility_registrations = PersistentMapping() self._adapter_registrations = PersistentMapping() self._subscription_registrations = PersistentList() self._handler_registrations = PersistentList()
zope.component
/zope.component-6.0-py3-none-any.whl/zope/component/persistentregistry.py
persistentregistry.py
from zope.interface import Interface from zope.interface import implementedBy from zope.interface import moduleProvides from zope.interface import named from zope.interface import providedBy from zope.interface.interfaces import ComponentLookupError from zope.interface.interfaces import IComponentLookup from zope.component._api import adapter_hook from zope.component._api import createObject from zope.component._api import getAdapter from zope.component._api import getAdapterInContext from zope.component._api import getAdapters from zope.component._api import getAllUtilitiesRegisteredFor from zope.component._api import getFactoriesFor from zope.component._api import getFactoryInterfaces from zope.component._api import getMultiAdapter from zope.component._api import getNextUtility from zope.component._api import getSiteManager from zope.component._api import getUtilitiesFor from zope.component._api import getUtility from zope.component._api import handle from zope.component._api import queryAdapter from zope.component._api import queryAdapterInContext from zope.component._api import queryMultiAdapter from zope.component._api import queryNextUtility from zope.component._api import queryUtility from zope.component._api import subscribers from zope.component._declaration import adaptedBy from zope.component._declaration import adapter from zope.component._declaration import adapts from zope.component.globalregistry import getGlobalSiteManager from zope.component.globalregistry import globalSiteManager from zope.component.globalregistry import provideAdapter from zope.component.globalregistry import provideHandler from zope.component.globalregistry import provideSubscriptionAdapter from zope.component.globalregistry import provideUtility from zope.component.interfaces import IComponentArchitecture from zope.component.interfaces import IComponentRegistrationConvenience from zope.component.interfaces import IFactory moduleProvides(IComponentArchitecture, IComponentRegistrationConvenience) __all__ = tuple(IComponentArchitecture) \ + tuple(IComponentRegistrationConvenience) \ + ('named', 'adapts', 'adapter', 'adaptedBy', )
zope.component
/zope.component-6.0-py3-none-any.whl/zope/component/__init__.py
__init__.py
========= Changes ========= 2.3.0 (2021-12-17) ================== - Add support for Python 3.8, 3.9, and 3.10. - Drop support for Python 3.4. 2.2.0 (2018-10-19) ================== - Add support for Python 3.7. - Drop support for ``setup.py test``. 2.1.0 (2017-07-25) ================== - Add support for Python 3.5 and 3.6. - Drop support for Python 2.6 and 3.3. 2.0.0 (2014-12-24) ================== - Added 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. 2.0.0a1 (2013-02-25) ==================== - Add support for Python 3.3. - Replace deprecated ``zope.interface.classProvides`` usage with equivalent ``zope.interface.provider`` decorator. - Replace deprecated ``zope.interface.implements`` usage with equivalent ``zope.interface.implementer`` decorator. - Drop support for Python 2.4 and 2.5. - When loading this package's ZCML configuration, make sure to configure ``zope.component`` first since we require part of its configuration. 1.0.1 (2010-09-25) ================== - Add undeclared but needed dependency on ``zope.component``. - Add test extra to declare test dependency on ``zope.component[test]``. 1.0 (2009-05-19) ================ * Initial public release, derived from zope.app.component and zope.app.interface to replace them.
zope.componentvocabulary
/zope.componentvocabulary-2.3.0.tar.gz/zope.componentvocabulary-2.3.0/CHANGES.rst
CHANGES.rst
``zope.componentvocabulary`` ============================ .. image:: https://github.com/zopefoundation/zope.componentvocabulary/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/zope.componentvocabulary/actions/workflows/tests.yml .. image:: https://coveralls.io/repos/github/zopefoundation/zope.componentvocabulary/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.componentvocabulary?branch=master This package contains various vocabularies.
zope.componentvocabulary
/zope.componentvocabulary-2.3.0.tar.gz/zope.componentvocabulary-2.3.0/README.rst
README.rst
__docformat__ = "reStructuredText" import base64 import six import zope.component from zope.component.interface import interfaceToName from zope.interface import implementer, provider, Interface, providedBy from zope.interface.interfaces import IInterface from zope.interface.interfaces import IUtilityRegistration from zope.security.proxy import removeSecurityProxy from zope.schema.interfaces import IVocabularyTokenized from zope.schema.interfaces import ITokenizedTerm, ITitledTokenizedTerm from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm from zope.componentvocabulary.i18n import ZopeMessageFactory as _ @implementer(ITokenizedTerm) class UtilityTerm(object): """A term representing a utility. The token of the term is the name of the utility. Here is a brief example on how the IVocabulary interface is handled in this term as a utility: >>> from zope.interface.verify import verifyObject >>> from zope.schema.interfaces import IVocabulary >>> term = UtilityTerm(IVocabulary, 'zope.schema.interfaces.IVocabulary') >>> verifyObject(ITokenizedTerm, term) True >>> term.value <InterfaceClass zope.schema.interfaces.IVocabulary> >>> term.token 'zope.schema.interfaces.IVocabulary' >>> term <UtilityTerm zope.schema.interfaces.IVocabulary, instance of InterfaceClass> """ # noqa: E501 line too long def __init__(self, value, token): """Create a term for value and token.""" self.value = value self.token = token def __repr__(self): return '<UtilityTerm %s, instance of %s>' % ( self.token, self.value.__class__.__name__) @implementer(IVocabularyTokenized) @provider(IVocabularyFactory) class UtilityVocabulary(object): """Vocabulary that provides utilities of a specified interface. Here is a short example of how the vocabulary should work. First we need to create a utility interface and some utilities: >>> class IObject(Interface): ... 'Simple interface to mark object utilities.' >>> >>> @implementer(IObject) ... class Object(object): ... def __init__(self, name): ... self.name = name ... def __repr__(self): ... return '<Object %s>' %self.name Now we register some utilities for IObject >>> from zope import component >>> object1 = Object('object1') >>> component.provideUtility(object1, IObject, 'object1') >>> object2 = Object('object2') >>> component.provideUtility(object2, IObject, 'object2') >>> object3 = Object('object3') >>> component.provideUtility(object3, IObject, 'object3') >>> object4 = Object('object4') We are now ready to create a vocabulary that we can use; in our case everything is global, so the context is None. >>> vocab = UtilityVocabulary(None, interface=IObject) >>> import pprint >>> pprint.pprint(sorted(vocab._terms.items())) [(u'object1', <UtilityTerm object1, instance of Object>), (u'object2', <UtilityTerm object2, instance of Object>), (u'object3', <UtilityTerm object3, instance of Object>)] Now let's see how the other methods behave in this context. First we can just use the 'in' opreator to test whether a value is available. >>> object1 in vocab True >>> object4 in vocab False We can also create a lazy iterator. Note that the utility terms might appear in a different order than the utilities were registered. >>> iterator = iter(vocab) >>> terms = list(iterator) >>> names = [term.token for term in terms] >>> names.sort() >>> names [u'object1', u'object2', u'object3'] Determining the amount of utilities available via the vocabulary is also possible. >>> len(vocab) 3 Next we are looking at some of the more vocabulary-characteristic API methods. One can get a term for a given value using ``getTerm()``: >>> vocab.getTerm(object1) <UtilityTerm object1, instance of Object> >>> vocab.getTerm(object4) Traceback (most recent call last): ... LookupError: <Object object4> On the other hand, if you want to get a term by the token, then you do that with: >>> vocab.getTermByToken('object1') <UtilityTerm object1, instance of Object> >>> vocab.getTermByToken('object4') Traceback (most recent call last): ... LookupError: object4 That's it. It is all pretty straight forward, but it allows us to easily create a vocabulary for any utility. In fact, to make it easy to register such a vocabulary via ZCML, the `interface` argument to the constructor can be a string that is resolved via the utility registry. The ZCML looks like this: <zope:vocabulary name='IObjects' factory='zope.app.utility.vocabulary.UtilityVocabulary' interface='zope.app.utility.vocabulary.IObject' /> >>> component.provideUtility(IObject, IInterface, ... 'zope.app.utility.vocabulary.IObject') >>> vocab = UtilityVocabulary( ... None, interface='zope.app.utility.vocabulary.IObject') >>> pprint.pprint(sorted(vocab._terms.items())) [(u'object1', <UtilityTerm object1, instance of Object>), (u'object2', <UtilityTerm object2, instance of Object>), (u'object3', <UtilityTerm object3, instance of Object>)] Sometimes it is desirable to only select the name of a utility. For this purpose a `nameOnly` argument was added to the constructor, in which case the UtilityTerm's value is not the utility itself but the name of the utility. >>> vocab = UtilityVocabulary(None, interface=IObject, nameOnly=True) >>> pprint.pprint([term.value for term in vocab]) [u'object1', u'object2', u'object3'] """ # override these in subclasses interface = Interface nameOnly = False def __init__(self, context, **kw): if kw: # BBB 2006/02/24, to be removed after 12 months # the 'interface' and 'nameOnly' parameters are supposed to be # set as class-level attributes in custom subclasses now. self.nameOnly = bool(kw.get('nameOnly', False)) interface = kw.get('interface', Interface) if isinstance(interface, six.string_types): interface = zope.component.getUtility(IInterface, interface) self.interface = interface utils = zope.component.getUtilitiesFor(self.interface, context) self._terms = dict( (name, UtilityTerm(self.nameOnly and name or util, name)) for name, util in utils) def __contains__(self, value): """See zope.schema.interfaces.IBaseVocabulary""" return value in (term.value for term in self._terms.values()) def getTerm(self, value): """See zope.schema.interfaces.IBaseVocabulary""" try: return [term for name, term in self._terms.items() if term.value == value][0] except IndexError: raise LookupError(value) def getTermByToken(self, token): """See zope.schema.interfaces.IVocabularyTokenized""" try: return self._terms[token] except KeyError: raise LookupError(token) def __iter__(self): """See zope.schema.interfaces.IIterableVocabulary""" # Sort the terms by the token (utility name) values = sorted(self._terms.values(), key=lambda x: x.token) return iter(values) def __len__(self): """See zope.schema.interfaces.IIterableVocabulary""" return len(self._terms) @provider(IVocabularyFactory) class InterfacesVocabulary(UtilityVocabulary): interface = IInterface @provider(IVocabularyFactory) class ObjectInterfacesVocabulary(SimpleVocabulary): """A vocabulary that provides a list of all interfaces that its context provides. Here a quick demonstration: >>> from zope.interface import Interface, implementer >>> class I1(Interface): ... pass >>> class I2(Interface): ... pass >>> class I3(I2): ... pass >>> @implementer(I3, I1) ... class Object(object): ... pass >>> vocab = ObjectInterfacesVocabulary(Object()) >>> import pprint >>> names = [term.token for term in vocab] >>> names.sort() >>> pprint.pprint(names) ['zope.componentvocabulary.vocabulary.I1', 'zope.componentvocabulary.vocabulary.I2', 'zope.componentvocabulary.vocabulary.I3', 'zope.interface.Interface'] """ def __init__(self, context): # Remove the security proxy so the values from the vocabulary # are the actual interfaces and not proxies. component = removeSecurityProxy(context) interfaces = providedBy(component).flattened() terms = [SimpleTerm(interface, interfaceToName(context, interface)) for interface in interfaces] super(ObjectInterfacesVocabulary, self).__init__(terms) @provider(IVocabularyFactory) class UtilityComponentInterfacesVocabulary(ObjectInterfacesVocabulary): def __init__(self, context): if IUtilityRegistration.providedBy(context): context = context.component super(UtilityComponentInterfacesVocabulary, self).__init__( context) @implementer(ITitledTokenizedTerm) class UtilityNameTerm(object): r"""Simple term that provides a utility name as a value. >>> t1 = UtilityNameTerm('abc') >>> t2 = UtilityNameTerm(u'\xC0\xDF\xC7') >>> t1.value u'abc' >>> t2.value u'\xc0\xdf\xc7' >>> t1.title u'abc' >>> t2.title == u'\xC0\xDF\xC7' True >>> ITitledTokenizedTerm.providedBy(t1) True The tokens used for form values are Base-64 encodings of the names, with the letter 't' prepended to ensure the unnamed utility is supported: >>> t1.token 'tYWJj' >>> t2.token 'tw4DDn8OH' The unnamed utility is given an artificial title for use in user interfaces: >>> t3 = UtilityNameTerm(u'') >>> t3.title u'(unnamed utility)' """ def __init__(self, value): self.value = value.decode() if isinstance(value, bytes) else value @property def token(self): # Return our value as a token. This is required to be 7-bit # printable ascii. We'll use base64 generated from the UTF-8 # representation. (The default encoding rules should not be # allowed to apply.) return "t" + base64.b64encode(self.value.encode('utf-8')).decode() @property def title(self): return self.value or _("(unnamed utility)") @implementer(IVocabularyTokenized) class UtilityNames(object): """Vocabulary with utility names for a single interface as values. >>> class IMyUtility(Interface): ... pass >>> @implementer(IMyUtility) ... class MyUtility(object): ... pass >>> vocab = UtilityNames(IMyUtility) >>> from zope.schema.interfaces import IVocabulary >>> IVocabulary.providedBy(vocab) True >>> IVocabularyTokenized.providedBy(vocab) True >>> from zope.component.testing import PlacelessSetup >>> from zope import component >>> ps = PlacelessSetup() >>> ps.setUp() >>> component.provideUtility(MyUtility(), IMyUtility, 'one') >>> component.provideUtility(MyUtility(), IMyUtility, 'two') >>> unames = UtilityNames(IMyUtility) >>> len(list(unames)) 2 >>> L = [t.value for t in unames] >>> L.sort() >>> L [u'one', u'two'] >>> u'one' in vocab True >>> u'three' in vocab False >>> component.provideUtility(MyUtility(), IMyUtility, 'three') >>> u'three' in vocab True If the term is not found, a ValueError is raised from ``getTerm`` >>> u'four' in vocab False >>> vocab.getTerm(u'four') Traceback (most recent call last): ... ValueError: four >>> component.provideUtility(MyUtility(), IMyUtility) >>> u'' in vocab True >>> term1 = vocab.getTerm(u'') >>> term2 = vocab.getTermByToken(term1.token) >>> term2.value u'' >>> term3 = vocab.getTerm(u'one') >>> term3.token 'tb25l' >>> term3a = vocab.getTermByToken('tb25l') >>> term3.value u'one' If we ask ``getTermByToken`` to find a missing token, a ``LookupError`` is raised: >>> vocab.getTermByToken(u'no such term') Traceback (most recent call last): ... LookupError: no matching token: 'no such term' >>> ps.tearDown() """ def __init__(self, interface): self.interface = interface def __contains__(self, value): return zope.component.queryUtility(self.interface, value) is not None def getTerm(self, value): if value in self: return UtilityNameTerm(value) raise ValueError(value) def getTermByToken(self, token): for name, ut in zope.component.getUtilitiesFor(self.interface): name = name.decode() if isinstance(name, bytes) else name if token == "t": if not name: break elif UtilityNameTerm(name).token == token: break else: raise LookupError("no matching token: %r" % token) return self.getTerm(name) def __iter__(self): for name, ut in zope.component.getUtilitiesFor(self.interface): yield UtilityNameTerm(name) def __len__(self): """Return the number of valid terms, or sys.maxint.""" return len(list(zope.component.getUtilitiesFor(self.interface)))
zope.componentvocabulary
/zope.componentvocabulary-2.3.0.tar.gz/zope.componentvocabulary-2.3.0/src/zope/componentvocabulary/vocabulary.py
vocabulary.py
"""Zope Configuration (ZCML) interfaces """ from zope.interface import Interface from zope.schema import BytesLine from zope.schema.interfaces import ValidationError __all__ = [ 'InvalidToken', 'IConfigurationContext', 'IGroupingContext', ] class InvalidToken(ValidationError): """Invalid token in list.""" class IConfigurationContext(Interface): """Configuration Context The configuration context manages information about the state of the configuration system, such as the package containing the configuration file. More importantly, it provides methods for importing objects and opening files relative to the package. """ package = BytesLine( title=("The current package name"), description=("""\ This is the name of the package containing the configuration file being executed. If the configuration file was not included by package, then this is None. """), required=False, ) def resolve(dottedname): """Resolve a dotted name to an object A dotted name is constructed by concatenating a dotted module name with a global name within the module using a dot. For example, the object named "spam" in the foo.bar module has a dotted name of foo.bar.spam. If the current package is a prefix of a dotted name, then the package name can be relaced with a leading dot, So, for example, if the configuration file is in the foo package, then the dotted name foo.bar.spam can be shortened to .bar.spam. If the current package is multiple levels deep, multiple leading dots can be used to refer to higher-level modules. For example, if the current package is x.y.z, the dotted object name ..foo refers to x.y.foo. """ def path(filename): """Compute a full file name for the given file If the filename is relative to the package, then the returned name will include the package path, otherwise, the original file name is returned. Environment variables in the path are expanded, and if the path begins with the username marker (~), that is expanded as well. .. versionchanged:: 4.2.0 Start expanding home directories and environment variables. """ def checkDuplicate(filename): """Check for duplicate imports of the same file. Raises an exception if this file had been processed before. This is better than an unlimited number of conflict errors. """ def processFile(filename): """Check whether a file needs to be processed. Return True if processing is needed and False otherwise. If the file needs to be processed, it will be marked as processed, assuming that the caller will procces the file if it needs to be procssed. """ def action(discriminator, callable, args=(), kw={}, order=0, includepath=None, info=None): """Record a configuration action The job of most directives is to compute actions for later processing. The action method is used to record those actions. :param callable: The object to call to implement the action. :param tuple args: Arguments to pass to *callable* :param dict kw: Keyword arguments to pass to *callable* :param object discriminator: Used to to find actions that conflict. Actions conflict if they have equal discriminators. The exception to this is the special case of the discriminator with the value `None`. An action with a discriminator of `None` never conflicts with other actions. :keyword int order: This is possible to add an order argument to crudely control the order of execution. :keyword str info: Optional source line information :keyword includepath: is None (the default) or a tuple of include paths for this action. """ def provideFeature(name): """Record that a named feature is available in this context.""" def hasFeature(name): """Check whether a named feature is available in this context.""" class IGroupingContext(Interface): def before(): """Do something before processing nested directives """ def after(): """Do something after processing nested directives """
zope.configuration
/zope.configuration-5.0-py3-none-any.whl/zope/configuration/interfaces.py
interfaces.py
"""Helper Utility to wrap a text to a set width of characters """ __docformat__ = 'restructuredtext' import re __all__ = [ 'wrap', 'makeDocStructures', ] para_sep = re.compile('\n{2,}') whitespace = re.compile('[ \t\n\r]+') def wrap(text, width=78, indent=0): """ Makes sure that we keep a line length of a certain width. Examples: >>> from zope.configuration.docutils import wrap >>> print(wrap('foo bar')[:-2]) foo bar >>> print(wrap('foo bar', indent=2)[:-2]) foo bar >>> print(wrap('foo bar, more foo bar', 10)[:-2]) foo bar, more foo bar >>> print(wrap('foo bar, more foo bar', 10, 2)[:-2]) foo bar, more foo bar """ paras = para_sep.split(text.strip()) new_paras = [] for par in paras: words = filter(None, whitespace.split(par)) lines = [] line = [] length = indent for word in words: if length + len(word) <= width: line.append(word) length += len(word) + 1 else: lines.append(' ' * indent + ' '.join(line)) line = [word] length = len(word) + 1 + indent lines.append(' ' * indent + ' '.join(line)) new_paras.append('\n'.join(lines)) return '\n\n'.join(new_paras) + '\n\n' def makeDocStructures(context): """ makeDocStructures(context) -> namespaces, subdirs Creates two structures that provide a friendly format for documentation. *namespaces* is a dictionary that maps namespaces to a directives dictionary with the key being the name of the directive and the value is a tuple: (schema, handler, info). *subdirs* maps a (namespace, name) pair to a list of subdirectives that have the form (namespace, name, schema, info). """ namespaces = {} subdirs = {} registry = context._docRegistry for (namespace, name), schema, usedIn, handler, info, parent in registry: if not parent: ns_entry = namespaces.setdefault(namespace, {}) ns_entry[name] = (schema, handler, info) else: sd_entry = subdirs.setdefault((parent.namespace, parent.name), []) sd_entry.append((namespace, name, schema, handler, info)) return namespaces, subdirs
zope.configuration
/zope.configuration-5.0-py3-none-any.whl/zope/configuration/docutils.py
docutils.py
"""Configuration processor """ import builtins import operator import os.path import sys from keyword import iskeyword from zope.interface import Interface from zope.interface import implementer from zope.interface import providedBy from zope.interface.adapter import AdapterRegistry from zope.schema import URI from zope.schema import TextLine from zope.schema import ValidationError from zope.configuration._compat import implementer_if_needed from zope.configuration.exceptions import ConfigurationError from zope.configuration.exceptions import ConfigurationWrapperError from zope.configuration.fields import GlobalInterface from zope.configuration.fields import GlobalObject from zope.configuration.fields import PathProcessor from zope.configuration.interfaces import IConfigurationContext from zope.configuration.interfaces import IGroupingContext __all__ = [ 'ConfigurationContext', 'ConfigurationAdapterRegistry', 'ConfigurationMachine', 'IStackItem', 'SimpleStackItem', 'RootStackItem', 'GroupingStackItem', 'ComplexStackItem', 'GroupingContextDecorator', 'DirectiveSchema', 'IDirectivesInfo', 'IDirectivesContext', 'DirectivesHandler', 'IDirectiveInfo', 'IFullInfo', 'IStandaloneDirectiveInfo', 'defineSimpleDirective', 'defineGroupingDirective', 'IComplexDirectiveContext', 'ComplexDirectiveDefinition', 'subdirective', 'IProvidesDirectiveInfo', 'provides', 'toargs', 'expand_action', 'resolveConflicts', 'ConfigurationConflictError', ] zopens = 'http://namespaces.zope.org/zope' metans = 'http://namespaces.zope.org/meta' testns = 'http://namespaces.zope.org/test' class ConfigurationContext: """ Mix-in for implementing. :class:`zope.configuration.interfaces.IConfigurationContext`. Note that this class itself does not actually declare that it implements that interface; the subclass must do that. In addition, subclasses must provide a ``package`` attribute and a ``basepath`` attribute. If the base path is not None, relative paths are converted to absolute paths using the the base path. If the package is not none, relative imports are performed relative to the package. In general, the basepath and package attributes should be consistent. When a package is provided, the base path should be set to the path of the package directory. Subclasses also provide an ``actions`` attribute, which is a list of actions, an ``includepath`` attribute, and an ``info`` attribute. The include path is appended to each action and is used when resolving conflicts among actions. Normally, only the a ConfigurationMachine provides the actions attribute. Decorators simply use the actions of the context they decorate. The ``includepath`` attribute is a tuple of names. Each name is typically the name of an included configuration file. The ``info`` attribute contains descriptive information helpful when reporting errors. If not set, it defaults to an empty string. The actions attribute is a sequence of dictionaries where each dictionary has the following keys: - ``discriminator``, a value that identifies the action. Two actions that have the same (non None) discriminator conflict. - ``callable``, an object that is called to execute the action, - ``args``, positional arguments for the action - ``kw``, keyword arguments for the action - ``includepath``, a tuple of include file names (defaults to ()) - ``info``, an object that has descriptive information about the action (defaults to '') """ # pylint:disable=no-member def __init__(self): super().__init__() self._seen_files = set() self._features = set() def resolve(self, dottedname): """ Resolve a dotted name to an object. Examples: >>> from zope.configuration.config import ConfigurationContext >>> c = ConfigurationContext() >>> import zope, zope.interface >>> c.resolve('zope') is zope True >>> c.resolve('zope.interface') is zope.interface True >>> c.resolve('zope.configuration.eek') #doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ConfigurationError: ImportError: Module zope.configuration has no global eek >>> c.resolve('.config.ConfigurationContext') Traceback (most recent call last): ... AttributeError: 'ConfigurationContext' object has no attribute 'package' >>> import zope.configuration >>> c.package = zope.configuration >>> c.resolve('.') is zope.configuration True >>> c.resolve('.config.ConfigurationContext') is ConfigurationContext True >>> c.resolve('..interface') is zope.interface True >>> c.resolve('str') is str True """ # noqa: E501 line too long name = dottedname.strip() if not name: raise ValueError("The given name is blank") if name == '.': return self.package names = name.split('.') if not names[-1]: raise ValueError( "Trailing dots are no longer supported in dotted names") if len(names) == 1: # Check for built-in objects marker = object() obj = getattr(builtins, names[0], marker) if obj is not marker: return obj if not names[0]: # Got a relative name. Convert it to abs using package info if self.package is None: raise ConfigurationError( "Can't use leading dots in dotted names, " "no package has been set.") pnames = self.package.__name__.split(".") pnames.append('') while names and not names[0]: names.pop(0) try: pnames.pop() except IndexError: raise ConfigurationError("Invalid global name", name) names[0:0] = pnames # Now we should have an absolute dotted name # Split off object name: oname, mname = names[-1], '.'.join(names[:-1]) # Import the module if not mname: # Just got a single name. Must me a module mname = oname oname = '' try: # Without a fromlist, this returns the package rather than the # module if the name contains a dot. Using a fromlist requires # star imports to work, which may not be true if there are # unicode items in __all__ due to unicode_literals on Python 2. # Getting the module from sys.modules instead avoids both # problems. __import__(mname) mod = sys.modules[mname] except ImportError as v: if sys.exc_info()[2].tb_next is not None: # ImportError was caused deeper raise raise ConfigurationError( f"ImportError: Couldn't import {mname}, {v}") if not oname: # see not mname case above return mod try: obj = getattr(mod, oname) return obj except AttributeError: # No such name, maybe it's a module that we still need to import try: moname = mname + '.' + oname __import__(moname) return sys.modules[moname] except ImportError: if sys.exc_info()[2].tb_next is not None: # ImportError was caused deeper raise raise ConfigurationError( f"ImportError: Module {mname} has no global {oname}") def path(self, filename): """ Compute package-relative paths. Examples: >>> import os >>> from zope.configuration.config import ConfigurationContext >>> c = ConfigurationContext() >>> c.path("/x/y/z") == os.path.normpath("/x/y/z") True >>> c.path("y/z") Traceback (most recent call last): ... AttributeError: 'ConfigurationContext' object has no attribute 'package' >>> import zope.configuration >>> c.package = zope.configuration >>> import os >>> d = os.path.dirname(zope.configuration.__file__) >>> c.path("y/z") == d + os.path.normpath("/y/z") True >>> c.path("y/./z") == d + os.path.normpath("/y/z") True >>> c.path("y/../z") == d + os.path.normpath("/z") True """ # noqa: E501 line too long filename, needs_processing = PathProcessor.expand(filename) if not needs_processing: return filename # Got a relative path, combine with base path. # If we have no basepath, compute the base path from the package # path. basepath = getattr(self, 'basepath', '') if not basepath: if self.package is None: basepath = os.getcwd() else: if hasattr(self.package, '__path__'): basepath = self.package.__path__[0] else: basepath = os.path.dirname(self.package.__file__) basepath = os.path.abspath(os.path.normpath(basepath)) self.basepath = basepath return os.path.normpath(os.path.join(basepath, filename)) def checkDuplicate(self, filename): """ Check for duplicate imports of the same file. Raises an exception if this file had been processed before. This is better than an unlimited number of conflict errors. Examples: >>> from zope.configuration.config import ConfigurationContext >>> from zope.configuration.config import ConfigurationError >>> c = ConfigurationContext() >>> c.checkDuplicate('/foo.zcml') >>> try: ... c.checkDuplicate('/foo.zcml') ... except ConfigurationError as e: ... # On Linux the exact msg has /foo, on Windows \\foo. ... str(e).endswith("foo.zcml' included more than once") True You may use different ways to refer to the same file: >>> import zope.configuration >>> c.package = zope.configuration >>> import os >>> d = os.path.dirname(zope.configuration.__file__) >>> c.checkDuplicate('bar.zcml') >>> try: ... c.checkDuplicate(d + os.path.normpath('/bar.zcml')) ... except ConfigurationError as e: ... str(e).endswith("bar.zcml' included more than once") ... True """ path = self.path(filename) if path in self._seen_files: raise ConfigurationError('%r included more than once' % path) self._seen_files.add(path) def processFile(self, filename): """ Check whether a file needs to be processed. Return True if processing is needed and False otherwise. If the file needs to be processed, it will be marked as processed, assuming that the caller will procces the file if it needs to be procssed. Examples: >>> from zope.configuration.config import ConfigurationContext >>> c = ConfigurationContext() >>> c.processFile('/foo.zcml') True >>> c.processFile('/foo.zcml') False You may use different ways to refer to the same file: >>> import zope.configuration >>> c.package = zope.configuration >>> import os >>> d = os.path.dirname(zope.configuration.__file__) >>> c.processFile('bar.zcml') True >>> c.processFile(os.path.join(d, 'bar.zcml')) False """ path = self.path(filename) if path in self._seen_files: return False self._seen_files.add(path) return True def action(self, discriminator, callable=None, args=(), kw=None, order=0, includepath=None, info=None, **extra): """ Add an action with the given discriminator, callable and arguments. For testing purposes, the callable and arguments may be omitted. In that case, a default noop callable is used. The discriminator must be given, but it can be None, to indicate that the action never conflicts. Examples: >>> from zope.configuration.config import ConfigurationContext >>> c = ConfigurationContext() Normally, the context gets actions from subclasses. We'll provide an actions attribute ourselves: >>> c.actions = [] We'll use a test callable that has a convenient string representation >>> from zope.configuration.tests.directives import f >>> c.action(1, f, (1, ), {'x': 1}) >>> from pprint import PrettyPrinter >>> pprint = PrettyPrinter(width=60).pprint >>> pprint(c.actions) [{'args': (1,), 'callable': f, 'discriminator': 1, 'includepath': (), 'info': '', 'kw': {'x': 1}, 'order': 0}] >>> c.action(None) >>> pprint(c.actions) [{'args': (1,), 'callable': f, 'discriminator': 1, 'includepath': (), 'info': '', 'kw': {'x': 1}, 'order': 0}, {'args': (), 'callable': None, 'discriminator': None, 'includepath': (), 'info': '', 'kw': {}, 'order': 0}] Now set the include path and info: >>> c.includepath = ('foo.zcml',) >>> c.info = "?" >>> c.action(None) >>> pprint(c.actions[-1]) {'args': (), 'callable': None, 'discriminator': None, 'includepath': ('foo.zcml',), 'info': '?', 'kw': {}, 'order': 0} We can add an order argument to crudely control the order of execution: >>> c.action(None, order=99999) >>> pprint(c.actions[-1]) {'args': (), 'callable': None, 'discriminator': None, 'includepath': ('foo.zcml',), 'info': '?', 'kw': {}, 'order': 99999} We can also pass an includepath argument, which will be used as the the includepath for the action. (if includepath is None, self.includepath will be used): >>> c.action(None, includepath=('abc',)) >>> pprint(c.actions[-1]) {'args': (), 'callable': None, 'discriminator': None, 'includepath': ('abc',), 'info': '?', 'kw': {}, 'order': 0} We can also pass an info argument, which will be used as the the source line info for the action. (if info is None, self.info will be used): >>> c.action(None, info='abc') >>> pprint(c.actions[-1]) {'args': (), 'callable': None, 'discriminator': None, 'includepath': ('foo.zcml',), 'info': 'abc', 'kw': {}, 'order': 0} """ if kw is None: kw = {} action = extra if info is None: info = getattr(self, 'info', '') if includepath is None: includepath = getattr(self, 'includepath', ()) action.update( dict( discriminator=discriminator, callable=callable, args=args, kw=kw, includepath=includepath, info=info, order=order, ) ) self.actions.append(action) def hasFeature(self, feature): """ Check whether a named feature has been provided. Initially no features are provided. Examples: >>> from zope.configuration.config import ConfigurationContext >>> c = ConfigurationContext() >>> c.hasFeature('onlinehelp') False You can declare that a feature is provided >>> c.provideFeature('onlinehelp') and it becomes available >>> c.hasFeature('onlinehelp') True """ return feature in self._features def provideFeature(self, feature): """ Declare that a named feature has been provided. See :meth:`hasFeature` for examples. """ self._features.add(feature) class ConfigurationAdapterRegistry: """ Simple adapter registry that manages directives as adapters. Examples: >>> from zope.configuration.interfaces import IConfigurationContext >>> from zope.configuration.config import ConfigurationAdapterRegistry >>> from zope.configuration.config import ConfigurationMachine >>> r = ConfigurationAdapterRegistry() >>> c = ConfigurationMachine() >>> r.factory(c, ('http://www.zope.com', 'xxx')) Traceback (most recent call last): ... ConfigurationError: ('Unknown directive', 'http://www.zope.com', 'xxx') >>> def f(): ... pass >>> r.register( ... IConfigurationContext, ('http://www.zope.com', 'xxx'), f) >>> r.factory(c, ('http://www.zope.com', 'xxx')) is f True >>> r.factory(c, ('http://www.zope.com', 'yyy')) is f Traceback (most recent call last): ... ConfigurationError: ('Unknown directive', 'http://www.zope.com', 'yyy') >>> r.register(IConfigurationContext, 'yyy', f) >>> r.factory(c, ('http://www.zope.com', 'yyy')) is f True Test the documentation feature: >>> from zope.configuration.config import IFullInfo >>> r._docRegistry [] >>> r.document(('ns', 'dir'), IFullInfo, IConfigurationContext, None, ... 'inf', None) >>> r._docRegistry[0][0] == ('ns', 'dir') True >>> r._docRegistry[0][1] is IFullInfo True >>> r._docRegistry[0][2] is IConfigurationContext True >>> r._docRegistry[0][3] is None True >>> r._docRegistry[0][4] == 'inf' True >>> r._docRegistry[0][5] is None True >>> r.document('all-dir', None, None, None, None) >>> r._docRegistry[1][0] ('', 'all-dir') """ def __init__(self): super().__init__() self._registry = {} # Stores tuples of form: # (namespace, name), schema, usedIn, info, parent self._docRegistry = [] def register(self, interface, name, factory): r = self._registry.get(name) if r is None: r = AdapterRegistry() self._registry[name] = r r.register([interface], Interface, '', factory) def document(self, name, schema, usedIn, handler, info, parent=None): if isinstance(name, str): name = ('', name) self._docRegistry.append((name, schema, usedIn, handler, info, parent)) def factory(self, context, name): r = self._registry.get(name) if r is None: # Try namespace-independent name ns, n = name r = self._registry.get(n) if r is None: raise ConfigurationError("Unknown directive", ns, n) f = r.lookup1(providedBy(context), Interface) if f is None: raise ConfigurationError( f"The directive {name} cannot be used in this context") return f @implementer(IConfigurationContext) class ConfigurationMachine(ConfigurationAdapterRegistry, ConfigurationContext): """ Configuration machine. Example: >>> from zope.configuration.config import ConfigurationMachine >>> machine = ConfigurationMachine() >>> ns = "http://www.zope.org/testing" Register a directive: >>> from zope.configuration.config import metans >>> machine((metans, "directive"), ... namespace=ns, name="simple", ... schema="zope.configuration.tests.directives.ISimple", ... handler="zope.configuration.tests.directives.simple") and try it out: >>> machine((ns, "simple"), a=u"aa", c=u"cc") >>> from pprint import PrettyPrinter >>> pprint = PrettyPrinter(width=60).pprint >>> pprint(machine.actions) [{'args': ('aa', 'xxx', 'cc'), 'callable': f, 'discriminator': ('simple', 'aa', 'xxx', 'cc'), 'includepath': (), 'info': None, 'kw': {}, 'order': 0}] """ package = None basepath = None includepath = () info = '' #: These `Exception` subclasses are allowed to be raised from #: `execute_actions` without being re-wrapped into a #: `~.ConfigurationError`. (`BaseException` and other #: `~.ConfigurationError` instances are never wrapped.) #: #: Users of instances of this class may modify this before calling #: `execute_actions` if they need to propagate specific exceptions. #: #: .. versionadded:: 4.2.0 pass_through_exceptions = () def __init__(self): super().__init__() self.actions = [] self.stack = [RootStackItem(self)] self.i18n_strings = {} _bootstrap(self) def begin(self, __name, __data=None, __info=None, **kw): if __data: if kw: raise TypeError("Can't provide a mapping object and keyword " "arguments") else: __data = kw self.stack.append(self.stack[-1].contained(__name, __data, __info)) def end(self): self.stack.pop().finish() def __call__(self, __name, __info=None, **__kw): self.begin(__name, __kw, __info) self.end() def getInfo(self): return self.stack[-1].context.info def setInfo(self, info): self.stack[-1].context.info = info def execute_actions(self, clear=True, testing=False): """ Execute the configuration actions. This calls the action callables after resolving conflicts. For example: >>> from zope.configuration.config import ConfigurationMachine >>> output = [] >>> def f(*a, **k): ... output.append(('f', a, k)) >>> context = ConfigurationMachine() >>> context.actions = [ ... (1, f, (1,)), ... (1, f, (11,), {}, ('x', )), ... (2, f, (2,)), ... ] >>> context.execute_actions() >>> output [('f', (1,), {}), ('f', (2,), {})] If the action raises an error, we convert it to a `~.ConfigurationError`. >>> output = [] >>> def bad(): ... bad.xxx >>> context.actions = [ ... (1, f, (1,)), ... (1, f, (11,), {}, ('x', )), ... (2, f, (2,)), ... (3, bad, (), {}, (), 'oops') ... ] >>> context.execute_actions() Traceback (most recent call last): ... zope.configuration.config.ConfigurationExecutionError: oops AttributeError: 'function' object has no attribute 'xxx' Note that actions executed before the error still have an effect: >>> output [('f', (1,), {}), ('f', (2,), {})] If the exception was already a `~.ConfigurationError`, it is raised as-is with the action's ``info`` added. >>> def bad(): ... raise ConfigurationError("I'm bad") >>> context.actions = [ ... (1, f, (1,)), ... (1, f, (11,), {}, ('x', )), ... (2, f, (2,)), ... (3, bad, (), {}, (), 'oops') ... ] >>> context.execute_actions() Traceback (most recent call last): ... zope.configuration.exceptions.ConfigurationError: I'm bad oops """ pass_through_exceptions = self.pass_through_exceptions if testing: pass_through_exceptions = BaseException try: for action in resolveConflicts(self.actions): callable = action['callable'] if callable is None: continue args = action['args'] kw = action['kw'] info = action['info'] try: callable(*args, **kw) except ConfigurationError as ex: ex.add_details(info) raise except pass_through_exceptions: raise except Exception: # Wrap it up and raise. raise ConfigurationExecutionError(info, sys.exc_info()[1]) finally: if clear: del self.actions[:] class ConfigurationExecutionError(ConfigurationWrapperError): """ An error occurred during execution of a configuration action """ ############################################################################## # Stack items class IStackItem(Interface): """ Configuration machine stack items Stack items are created when a directive is being processed. A stack item is created for each directive use. """ def contained(name, data, info): """Begin processing a contained directive The data are a dictionary of attribute names mapped to unicode strings. The info argument is an object that can be converted to a string and that contains information about the directive. The begin method returns the next item to be placed on the stack. """ def finish(): """Finish processing a directive """ @implementer(IStackItem) class SimpleStackItem: """ Simple stack item A simple stack item can't have anything added after it. It can only be removed. It is used for simple directives and subdirectives, which can't contain other directives. It also defers any computation until the end of the directive has been reached. """ # XXX why this *argdata hack instead of schema, data? def __init__(self, context, handler, info, *argdata): newcontext = GroupingContextDecorator(context) newcontext.info = info self.context = newcontext self.handler = handler self.argdata = argdata def contained(self, name, data, info): raise ConfigurationError("Invalid directive %s" % str(name)) def finish(self): # We're going to use the context that was passed to us, which wasn't # created for the directive. We want to set it's info to the one # passed to us while we make the call, so we'll save the old one # and restore it. context = self.context args = toargs(context, *self.argdata) actions = self.handler(context, **args) if actions: # we allow the handler to return nothing for action in actions: if not isinstance(action, dict): action = expand_action(*action) # b/c context.action(**action) @implementer(IStackItem) class RootStackItem: """ A root stack item. """ def __init__(self, context): self.context = context def contained(self, name, data, info): """Handle a contained directive We have to compute a new stack item by getting a named adapter for the current context object. """ factory = self.context.factory(self.context, name) if factory is None: raise ConfigurationError("Invalid directive", name) adapter = factory(self.context, data, info) return adapter def finish(self): pass @implementer_if_needed(IStackItem) class GroupingStackItem(RootStackItem): """ Stack item for a grouping directive A grouping stack item is in the stack when a grouping directive is being processed. Grouping directives group other directives. Often, they just manage common data, but they may also take actions, either before or after contained directives are executed. A grouping stack item is created with a grouping directive definition, a configuration context, and directive data. To see how this works, let's look at an example: We need a context. We'll just use a configuration machine >>> from zope.configuration.config import GroupingStackItem >>> from zope.configuration.config import ConfigurationMachine >>> context = ConfigurationMachine() We need a callable to use in configuration actions. We'll use a convenient one from the tests: >>> from zope.configuration.tests.directives import f We need a handler for the grouping directive. This is a class that implements a context decorator. The decorator must also provide ``before`` and ``after`` methods that are called before and after any contained directives are processed. We'll typically subclass ``GroupingContextDecorator``, which provides context decoration, and default ``before`` and ``after`` methods. >>> from zope.configuration.config import GroupingContextDecorator >>> class SampleGrouping(GroupingContextDecorator): ... def before(self): ... self.action(('before', self.x, self.y), f) ... def after(self): ... self.action(('after'), f) We'll use our decorator to decorate our initial context, providing keyword arguments x and y: >>> dec = SampleGrouping(context, x=1, y=2) Note that the keyword arguments are made attributes of the decorator. Now we'll create the stack item. >>> item = GroupingStackItem(dec) We still haven't called the before action yet, which we can verify by looking at the context actions: >>> context.actions [] Subdirectives will get looked up as adapters of the context. We'll create a simple handler: >>> def simple(context, data, info): ... context.action(("simple", context.x, context.y, data), f) ... return info and register it with the context: >>> from zope.configuration.interfaces import IConfigurationContext >>> from zope.configuration.config import testns >>> context.register(IConfigurationContext, (testns, 'simple'), simple) This handler isn't really a propert handler, because it doesn't return a new context. It will do for this example. Now we'll call the contained method on the stack item: >>> item.contained((testns, 'simple'), {'z': 'zope'}, "someinfo") 'someinfo' We can verify thet the simple method was called by looking at the context actions. Note that the before method was called before handling the contained directive. >>> from pprint import PrettyPrinter >>> pprint = PrettyPrinter(width=60).pprint >>> pprint(context.actions) [{'args': (), 'callable': f, 'discriminator': ('before', 1, 2), 'includepath': (), 'info': '', 'kw': {}, 'order': 0}, {'args': (), 'callable': f, 'discriminator': ('simple', 1, 2, {'z': 'zope'}), 'includepath': (), 'info': '', 'kw': {}, 'order': 0}] Finally, we call finish, which calls the decorator after method: >>> item.finish() >>> pprint(context.actions) [{'args': (), 'callable': f, 'discriminator': ('before', 1, 2), 'includepath': (), 'info': '', 'kw': {}, 'order': 0}, {'args': (), 'callable': f, 'discriminator': ('simple', 1, 2, {'z': 'zope'}), 'includepath': (), 'info': '', 'kw': {}, 'order': 0}, {'args': (), 'callable': f, 'discriminator': 'after', 'includepath': (), 'info': '', 'kw': {}, 'order': 0}] If there were no nested directives: >>> context = ConfigurationMachine() >>> dec = SampleGrouping(context, x=1, y=2) >>> item = GroupingStackItem(dec) >>> item.finish() Then before will be when we call finish: >>> pprint(context.actions) [{'args': (), 'callable': f, 'discriminator': ('before', 1, 2), 'includepath': (), 'info': '', 'kw': {}, 'order': 0}, {'args': (), 'callable': f, 'discriminator': 'after', 'includepath': (), 'info': '', 'kw': {}, 'order': 0}] """ def __init__(self, context): super().__init__(context) def __callBefore(self): actions = self.context.before() if actions: for action in actions: if not isinstance(action, dict): action = expand_action(*action) self.context.action(**action) self.__callBefore = noop def contained(self, name, data, info): self.__callBefore() return RootStackItem.contained(self, name, data, info) def finish(self): self.__callBefore() actions = self.context.after() if actions: for action in actions: if not isinstance(action, dict): action = expand_action(*action) self.context.action(**action) def noop(): pass @implementer(IStackItem) class ComplexStackItem: """ Complex stack item A complex stack item is in the stack when a complex directive is being processed. It only allows subdirectives to be used. A complex stack item is created with a complex directive definition (IComplexDirectiveContext), a configuration context, and directive data. To see how this works, let's look at an example: We need a context. We'll just use a configuration machine >>> from zope.configuration.config import ConfigurationMachine >>> context = ConfigurationMachine() We need a callable to use in configuration actions. We'll use a convenient one from the tests: >>> from zope.configuration.tests.directives import f We need a handler for the complex directive. This is a class with a method for each subdirective: >>> class Handler(object): ... def __init__(self, context, x, y): ... self.context, self.x, self.y = context, x, y ... context.action('init', f) ... def sub(self, context, a, b): ... context.action(('sub', a, b), f) ... def __call__(self): ... self.context.action(('call', self.x, self.y), f) We need a complex directive definition: >>> from zope.interface import Interface >>> from zope.schema import TextLine >>> from zope.configuration.config import ComplexDirectiveDefinition >>> class Ixy(Interface): ... x = TextLine() ... y = TextLine() >>> definition = ComplexDirectiveDefinition( ... context, name="test", schema=Ixy, ... handler=Handler) >>> class Iab(Interface): ... a = TextLine() ... b = TextLine() >>> definition['sub'] = Iab, '' OK, now that we have the context, handler and definition, we're ready to use a stack item. >>> from zope.configuration.config import ComplexStackItem >>> item = ComplexStackItem( ... definition, context, {'x': u'xv', 'y': u'yv'}, 'foo') When we created the definition, the handler (factory) was called. >>> from pprint import PrettyPrinter >>> pprint = PrettyPrinter(width=60).pprint >>> pprint(context.actions) [{'args': (), 'callable': f, 'discriminator': 'init', 'includepath': (), 'info': 'foo', 'kw': {}, 'order': 0}] If a subdirective is provided, the ``contained`` method of the stack item is called. It will lookup the subdirective schema and call the corresponding method on the handler instance: >>> simple = item.contained(('somenamespace', 'sub'), ... {'a': u'av', 'b': u'bv'}, 'baz') >>> simple.finish() Note that the name passed to ``contained`` is a 2-part name, consisting of a namespace and a name within the namespace. >>> pprint(context.actions) [{'args': (), 'callable': f, 'discriminator': 'init', 'includepath': (), 'info': 'foo', 'kw': {}, 'order': 0}, {'args': (), 'callable': f, 'discriminator': ('sub', 'av', 'bv'), 'includepath': (), 'info': 'baz', 'kw': {}, 'order': 0}] The new stack item returned by contained is one that doesn't allow any more subdirectives, When all of the subdirectives have been provided, the ``finish`` method is called: >>> item.finish() The stack item will call the handler if it is callable. >>> pprint(context.actions) [{'args': (), 'callable': f, 'discriminator': 'init', 'includepath': (), 'info': 'foo', 'kw': {}, 'order': 0}, {'args': (), 'callable': f, 'discriminator': ('sub', 'av', 'bv'), 'includepath': (), 'info': 'baz', 'kw': {}, 'order': 0}, {'args': (), 'callable': f, 'discriminator': ('call', 'xv', 'yv'), 'includepath': (), 'info': 'foo', 'kw': {}, 'order': 0}] """ def __init__(self, meta, context, data, info): newcontext = GroupingContextDecorator(context) newcontext.info = info self.context = newcontext self.meta = meta # Call the handler contructor args = toargs(newcontext, meta.schema, data) self.handler = self.meta.handler(newcontext, **args) def contained(self, name, data, info): """Handle a subdirective """ # Look up the subdirective meta data on our meta object ns, name = name schema = self.meta.get(name) if schema is None: raise ConfigurationError("Invalid directive", name) schema = schema[0] # strip off info handler = getattr(self.handler, name) return SimpleStackItem(self.context, handler, info, schema, data) def finish(self): # when we're done, we call the handler, which might return more actions # Need to save and restore old info # XXX why not just use callable()? try: actions = self.handler() except AttributeError as v: if v.args[0] == '__call__': return # noncallable raise except TypeError: return # non callable if actions: # we allow the handler to return nothing for action in actions: if not isinstance(action, dict): action = expand_action(*action) self.context.action(**action) ############################################################################## # Helper classes @implementer(IConfigurationContext, IGroupingContext) class GroupingContextDecorator(ConfigurationContext): """Helper mix-in class for building grouping directives See the discussion (and test) in GroupingStackItem. """ def __init__(self, context, **kw): self.context = context for name, v in kw.items(): setattr(self, name, v) def __getattr__(self, name): v = getattr(self.context, name) # cache result in self setattr(self, name, v) return v def before(self): pass def after(self): pass ############################################################################## # Directive-definition class DirectiveSchema(GlobalInterface): """A field that contains a global variable value that must be a schema """ class IDirectivesInfo(Interface): """Schema for the ``directives`` directive """ namespace = URI( title="Namespace", description=( "The namespace in which directives' names " "will be defined"), ) class IDirectivesContext(IDirectivesInfo, IConfigurationContext): pass @implementer(IDirectivesContext) class DirectivesHandler(GroupingContextDecorator): """Handler for the directives directive This is just a grouping directive that adds a namespace attribute to the normal directive context. """ class IDirectiveInfo(Interface): """Information common to all directive definitions. """ name = TextLine( title="Directive name", description="The name of the directive being defined", ) schema = DirectiveSchema( title="Directive handler", description="The dotted name of the directive handler", ) class IFullInfo(IDirectiveInfo): """Information that all top-level directives (not subdirectives) have. """ handler = GlobalObject( title="Directive handler", description="The dotted name of the directive handler", ) usedIn = GlobalInterface( title="The directive types the directive can be used in", description=( "The interface of the directives that can contain " "the directive" ), default=IConfigurationContext, ) class IStandaloneDirectiveInfo(IDirectivesInfo, IFullInfo): """Info for full directives defined outside a directives directives """ def defineSimpleDirective(context, name, schema, handler, namespace='', usedIn=IConfigurationContext): """ Define a simple directive Define and register a factory that invokes the simple directive and returns a new stack item, which is always the same simple stack item. If the namespace is '*', the directive is registered for all namespaces. Example: >>> from zope.configuration.config import ConfigurationMachine >>> context = ConfigurationMachine() >>> from zope.interface import Interface >>> from zope.schema import TextLine >>> from zope.configuration.tests.directives import f >>> class Ixy(Interface): ... x = TextLine() ... y = TextLine() >>> def s(context, x, y): ... context.action(('s', x, y), f) >>> from zope.configuration.config import defineSimpleDirective >>> defineSimpleDirective(context, 's', Ixy, s, testns) >>> context((testns, "s"), x=u"vx", y=u"vy") >>> from pprint import PrettyPrinter >>> pprint = PrettyPrinter(width=60).pprint >>> pprint(context.actions) [{'args': (), 'callable': f, 'discriminator': ('s', 'vx', 'vy'), 'includepath': (), 'info': None, 'kw': {}, 'order': 0}] >>> context(('http://www.zope.com/t1', "s"), x=u"vx", y=u"vy") Traceback (most recent call last): ... ConfigurationError: ('Unknown directive', 'http://www.zope.com/t1', 's') >>> context = ConfigurationMachine() >>> defineSimpleDirective(context, 's', Ixy, s, "*") >>> context(('http://www.zope.com/t1', "s"), x=u"vx", y=u"vy") >>> pprint(context.actions) [{'args': (), 'callable': f, 'discriminator': ('s', 'vx', 'vy'), 'includepath': (), 'info': None, 'kw': {}, 'order': 0}] """ # noqa: E501 line too long namespace = namespace or context.namespace if namespace != '*': name = namespace, name def factory(context, data, info): return SimpleStackItem(context, handler, info, schema, data) factory.schema = schema context.register(usedIn, name, factory) context.document(name, schema, usedIn, handler, context.info) def defineGroupingDirective(context, name, schema, handler, namespace='', usedIn=IConfigurationContext): """ Define a grouping directive Define and register a factory that sets up a grouping directive. If the namespace is '*', the directive is registered for all namespaces. Example: >>> from zope.configuration.config import ConfigurationMachine >>> context = ConfigurationMachine() >>> from zope.interface import Interface >>> from zope.schema import TextLine >>> class Ixy(Interface): ... x = TextLine() ... y = TextLine() We won't bother creating a special grouping directive class. We'll just use :class:`GroupingContextDecorator`, which simply sets up a grouping context that has extra attributes defined by a schema: >>> from zope.configuration.config import defineGroupingDirective >>> from zope.configuration.config import GroupingContextDecorator >>> defineGroupingDirective(context, 'g', Ixy, ... GroupingContextDecorator, testns) >>> context.begin((testns, "g"), x=u"vx", y=u"vy") >>> context.stack[-1].context.x 'vx' >>> context.stack[-1].context.y 'vy' >>> context(('http://www.zope.com/t1', "g"), x=u"vx", y=u"vy") Traceback (most recent call last): ... ConfigurationError: ('Unknown directive', 'http://www.zope.com/t1', 'g') >>> context = ConfigurationMachine() >>> defineGroupingDirective(context, 'g', Ixy, ... GroupingContextDecorator, "*") >>> context.begin(('http://www.zope.com/t1', "g"), x=u"vx", y=u"vy") >>> context.stack[-1].context.x 'vx' >>> context.stack[-1].context.y 'vy' """ # noqa: E501 line too long namespace = namespace or context.namespace if namespace != '*': name = namespace, name def factory(context, data, info): args = toargs(context, schema, data) newcontext = handler(context, **args) newcontext.info = info return GroupingStackItem(newcontext) factory.schema = schema context.register(usedIn, name, factory) context.document(name, schema, usedIn, handler, context.info) class IComplexDirectiveContext(IFullInfo, IConfigurationContext): pass @implementer(IComplexDirectiveContext) class ComplexDirectiveDefinition(GroupingContextDecorator, dict): """Handler for defining complex directives See the description and tests for ComplexStackItem. """ def before(self): def factory(context, data, info): return ComplexStackItem(self, context, data, info) factory.schema = self.schema self.register(self.usedIn, (self.namespace, self.name), factory) self.document((self.namespace, self.name), self.schema, self.usedIn, self.handler, self.info) def subdirective(context, name, schema): context.document((context.namespace, name), schema, context.usedIn, getattr(context.handler, name, context.handler), context.info, context.context) context.context[name] = schema, context.info ############################################################################## # Features class IProvidesDirectiveInfo(Interface): """Information for a <meta:provides> directive""" feature = TextLine( title="Feature name", description="""The name of the feature being provided You can test available features with zcml:condition="have featurename". """, ) def provides(context, feature): """ Declare that a feature is provided in context. Example: >>> from zope.configuration.config import ConfigurationContext >>> from zope.configuration.config import provides >>> c = ConfigurationContext() >>> provides(c, 'apidoc') >>> c.hasFeature('apidoc') True Spaces are not allowed in feature names (this is reserved for providing many features with a single directive in the future). >>> provides(c, 'apidoc onlinehelp') Traceback (most recent call last): ... ValueError: Only one feature name allowed >>> c.hasFeature('apidoc onlinehelp') False """ if len(feature.split()) > 1: raise ValueError("Only one feature name allowed") context.provideFeature(feature) ############################################################################## # Argument conversion def toargs(context, schema, data): """ Marshal data to an argument dictionary using a schema Names that are python keywords have an underscore added as a suffix in the schema and in the argument list, but are used without the underscore in the data. The fields in the schema must all implement IFromUnicode. All of the items in the data must have corresponding fields in the schema unless the schema has a true tagged value named 'keyword_arguments'. Example: >>> from zope.configuration.config import toargs >>> from zope.schema import BytesLine >>> from zope.schema import Float >>> from zope.schema import Int >>> from zope.schema import TextLine >>> from zope.schema import URI >>> class schema(Interface): ... in_ = Int(constraint=lambda v: v > 0) ... f = Float() ... n = TextLine(min_length=1, default=u"rob") ... x = BytesLine(required=False) ... u = URI() >>> context = ConfigurationMachine() >>> from pprint import PrettyPrinter >>> pprint = PrettyPrinter(width=50).pprint >>> pprint(toargs(context, schema, ... {'in': u'1', 'f': u'1.2', 'n': u'bob', 'x': u'x.y.z', ... 'u': u'http://www.zope.org' })) {'f': 1.2, 'in_': 1, 'n': 'bob', 'u': 'http://www.zope.org', 'x': b'x.y.z'} If we have extra data, we'll get an error: >>> toargs(context, schema, ... {'in': u'1', 'f': u'1.2', 'n': u'bob', 'x': u'x.y.z', ... 'u': u'http://www.zope.org', 'a': u'1'}) Traceback (most recent call last): ... ConfigurationError: ('Unrecognized parameters:', 'a') Unless we set a tagged value to say that extra arguments are ok: >>> schema.setTaggedValue('keyword_arguments', True) >>> pprint(toargs(context, schema, ... {'in': u'1', 'f': u'1.2', 'n': u'bob', 'x': u'x.y.z', ... 'u': u'http://www.zope.org', 'a': u'1'})) {'a': '1', 'f': 1.2, 'in_': 1, 'n': 'bob', 'u': 'http://www.zope.org', 'x': b'x.y.z'} If we omit required data we get an error telling us what was omitted: >>> pprint(toargs(context, schema, ... {'in': u'1', 'f': u'1.2', 'n': u'bob', 'x': u'x.y.z'})) Traceback (most recent call last): ... ConfigurationError: ('Missing parameter:', 'u') Although we can omit not-required data: >>> pprint(toargs(context, schema, ... {'in': u'1', 'f': u'1.2', 'n': u'bob', ... 'u': u'http://www.zope.org', 'a': u'1'})) {'a': '1', 'f': 1.2, 'in_': 1, 'n': 'bob', 'u': 'http://www.zope.org'} And we can omit required fields if they have valid defaults (defaults that are valid values): >>> pprint(toargs(context, schema, ... {'in': u'1', 'f': u'1.2', ... 'u': u'http://www.zope.org', 'a': u'1'})) {'a': '1', 'f': 1.2, 'in_': 1, 'n': 'rob', 'u': 'http://www.zope.org'} We also get an error if any data was invalid: >>> pprint(toargs(context, schema, ... {'in': u'0', 'f': u'1.2', 'n': u'bob', 'x': u'x.y.z', ... 'u': u'http://www.zope.org', 'a': u'1'})) Traceback (most recent call last): ... ConfigurationError: ('Invalid value for', 'in', '0') """ data = dict(data) args = {} for name, field in schema.namesAndDescriptions(True): field = field.bind(context) n = name if n.endswith('_') and iskeyword(n[:-1]): n = n[:-1] s = data.get(n, data) if s is not data: s = str(s) del data[n] try: args[str(name)] = field.fromUnicode(s) except ValidationError as v: raise ConfigurationError( "Invalid value for %r" % (n)).add_details(v) elif field.required: # if the default is valid, we can use that: default = field.default try: field.validate(default) except ValidationError as v: raise ConfigurationError( f"Missing parameter: {n!r}").add_details(v) args[str(name)] = default if data: # we had data left over try: keyword_arguments = schema.getTaggedValue('keyword_arguments') except KeyError: keyword_arguments = False if not keyword_arguments: raise ConfigurationError("Unrecognized parameters:", *data) for name in data: args[str(name)] = data[name] return args ############################################################################## # Conflict resolution def expand_action(discriminator, callable=None, args=(), kw=None, includepath=(), info=None, order=0, **extra): if kw is None: kw = {} action = extra action.update( dict( discriminator=discriminator, callable=callable, args=args, kw=kw, includepath=includepath, info=info, order=order, ) ) return action def resolveConflicts(actions): """ Resolve conflicting actions. Given an actions list, identify and try to resolve conflicting actions. Actions conflict if they have the same non-None discriminator. Conflicting actions can be resolved if the include path of one of the actions is a prefix of the includepaths of the other conflicting actions and is unequal to the include paths in the other conflicting actions. """ # organize actions by discriminators unique = {} output = [] for i, action in enumerate(actions): if not isinstance(action, dict): # old-style tuple action action = expand_action(*action) # "order" is an integer grouping. Actions in a lower order will be # executed before actions in a higher order. Within an order, # actions are executed sequentially based on original action ordering # ("i"). order = action['order'] or 0 discriminator = action['discriminator'] # "ainfo" is a tuple of (order, i, action) where "order" is a # user-supplied grouping, "i" is an integer expressing the relative # position of this action in the action list being resolved, and # "action" is an action dictionary. The purpose of an ainfo is to # associate an "order" and an "i" with a particular action; "order" # and "i" exist for sorting purposes after conflict resolution. ainfo = (order, i, action) if discriminator is None: # The discriminator is None, so this action can never conflict. # We can add it directly to the result. output.append(ainfo) continue L = unique.setdefault(discriminator, []) L.append(ainfo) # Check for conflicts conflicts = {} for discriminator, ainfos in unique.items(): # We use (includepath, order, i) as a sort key because we need to # sort the actions by the paths so that the shortest path with a # given prefix comes first. The "first" action is the one with the # shortest include path. We break sorting ties using "order", then # "i". def bypath(ainfo): path, order, i = ainfo[2]['includepath'], ainfo[0], ainfo[1] return path, order, i ainfos.sort(key=bypath) ainfo, rest = ainfos[0], ainfos[1:] output.append(ainfo) _, _, action = ainfo basepath, baseinfo, discriminator = (action['includepath'], action['info'], action['discriminator']) for _, _, action in rest: includepath = action['includepath'] # Test whether path is a prefix of opath if (includepath[:len(basepath)] != basepath # not a prefix or includepath == basepath): L = conflicts.setdefault(discriminator, [baseinfo]) L.append(action['info']) if conflicts: raise ConfigurationConflictError(conflicts) # Sort conflict-resolved actions by (order, i) and return them. return [x[2] for x in sorted(output, key=operator.itemgetter(0, 1))] class ConfigurationConflictError(ConfigurationError): def __init__(self, conflicts): super().__init__() self._conflicts = conflicts def _with_details(self, opening, detail_formatter): r = ["Conflicting configuration actions"] for discriminator, infos in sorted(self._conflicts.items()): r.append(f" For: {discriminator}") for info in infos: for line in str(info).rstrip().split('\n'): r.append(" " + line) opening = "\n".join(r) return super()._with_details( opening, detail_formatter) ############################################################################## # Bootstap code def _bootstrap(context): # Set enough machinery to register other directives # Define the directive (simple directive) directive by calling it's # handler directly info = 'Manually registered in zope/configuration/config.py' context.info = info defineSimpleDirective( context, namespace=metans, name='directive', schema=IStandaloneDirectiveInfo, handler=defineSimpleDirective) context.info = '' # OK, now that we have that, we can use the machine to define the # other directives. This isn't the easiest way to proceed, but it lets # us eat our own dogfood. :) # Standalone groupingDirective context((metans, 'directive'), info, name='groupingDirective', namespace=metans, handler="zope.configuration.config.defineGroupingDirective", schema="zope.configuration.config.IStandaloneDirectiveInfo" ) # Now we can use the grouping directive to define the directives directive context((metans, 'groupingDirective'), info, name='directives', namespace=metans, handler="zope.configuration.config.DirectivesHandler", schema="zope.configuration.config.IDirectivesInfo" ) # directive and groupingDirective inside directives context((metans, 'directive'), info, name='directive', namespace=metans, usedIn="zope.configuration.config.IDirectivesContext", handler="zope.configuration.config.defineSimpleDirective", schema="zope.configuration.config.IFullInfo" ) context((metans, 'directive'), info, name='groupingDirective', namespace=metans, usedIn="zope.configuration.config.IDirectivesContext", handler="zope.configuration.config.defineGroupingDirective", schema="zope.configuration.config.IFullInfo" ) # Setup complex directive directive, both standalone, and in # directives directive context((metans, 'groupingDirective'), info, name='complexDirective', namespace=metans, handler="zope.configuration.config.ComplexDirectiveDefinition", schema="zope.configuration.config.IStandaloneDirectiveInfo" ) context((metans, 'groupingDirective'), info, name='complexDirective', namespace=metans, usedIn="zope.configuration.config.IDirectivesContext", handler="zope.configuration.config.ComplexDirectiveDefinition", schema="zope.configuration.config.IFullInfo" ) # Finally, setup subdirective directive context((metans, 'directive'), info, name='subdirective', namespace=metans, usedIn="zope.configuration.config.IComplexDirectiveContext", handler="zope.configuration.config.subdirective", schema="zope.configuration.config.IDirectiveInfo" ) # meta:provides context((metans, 'directive'), info, name='provides', namespace=metans, handler="zope.configuration.config.provides", schema="zope.configuration.config.IProvidesDirectiveInfo" )
zope.configuration
/zope.configuration-5.0-py3-none-any.whl/zope/configuration/config.py
config.py
__docformat__ = 'restructuredtext' import errno import io import logging import os import sys from glob import glob from xml.sax import SAXParseException from xml.sax import make_parser from xml.sax.handler import ContentHandler from xml.sax.handler import feature_namespaces from xml.sax.xmlreader import InputSource from zope.interface import Interface from zope.schema import NativeStringLine from zope.configuration.config import ConfigurationMachine from zope.configuration.config import GroupingContextDecorator from zope.configuration.config import GroupingStackItem from zope.configuration.config import defineGroupingDirective from zope.configuration.config import defineSimpleDirective from zope.configuration.config import resolveConflicts from zope.configuration.exceptions import ConfigurationError from zope.configuration.exceptions import ConfigurationWrapperError from zope.configuration.fields import GlobalObject from zope.configuration.zopeconfigure import IZopeConfigure from zope.configuration.zopeconfigure import ZopeConfigure __all__ = [ 'ParserInfo', 'ConfigurationHandler', 'processxmlfile', 'openInOrPlain', 'IInclude', 'include', 'exclude', 'includeOverrides', 'registerCommonDirectives', 'file', 'string', 'XMLConfig', 'xmlconfig', 'testxmlconfig', ] logger = logging.getLogger("config") ZCML_NAMESPACE = "http://namespaces.zope.org/zcml" ZCML_CONDITION = (ZCML_NAMESPACE, "condition") class ZopeXMLConfigurationError(ConfigurationWrapperError): """ Zope XML Configuration error These errors are wrappers for other errors. They include configuration info and the wrapped error type and value. Example >>> from zope.configuration.xmlconfig import ZopeXMLConfigurationError >>> v = ZopeXMLConfigurationError("blah", AttributeError("xxx")) >>> print(v) 'blah' AttributeError: xxx """ USE_INFO_REPR = True class ZopeSAXParseException(ConfigurationWrapperError): """ Sax Parser errors as a ConfigurationError. Example >>> from zope.configuration.xmlconfig import ZopeSAXParseException >>> v = ZopeSAXParseException( ... "info", Exception("foo.xml:12:3:Not well formed")) >>> print(v) info Exception: foo.xml:12:3:Not well formed """ class ParserInfo: r""" Information about a directive based on parser data This includes the directive location, as well as text data contained in the directive. Example >>> from zope.configuration.xmlconfig import ParserInfo >>> info = ParserInfo('tests//sample.zcml', 1, 0) >>> info File "tests//sample.zcml", line 1.0 >>> print(info) File "tests//sample.zcml", line 1.0 >>> info.characters("blah\n") >>> info.characters("blah") >>> info.text 'blah\nblah' >>> info.end(7, 0) >>> info File "tests//sample.zcml", line 1.0-7.0 >>> print(info) File "tests//sample.zcml", line 1.0-7.0 <configure xmlns='http://namespaces.zope.org/zope'> <!-- zope.configure --> <directives namespace="http://namespaces.zope.org/zope"> <directive name="hook" attributes="name implementation module" handler="zope.configuration.metaconfigure.hook" /> </directives> </configure> """ text = '' def __init__(self, file, line, column): self.file, self.line, self.column = file, line, column self.eline, self.ecolumn = line, column def end(self, line, column): self.eline, self.ecolumn = line, column def __repr__(self): if (self.line, self.column) == (self.eline, self.ecolumn): return 'File "{}", line {}.{}'.format( self.file, self.line, self.column) return 'File "{}", line {}.{}-{}.{}'.format( self.file, self.line, self.column, self.eline, self.ecolumn) def __str__(self): if (self.line, self.column) == (self.eline, self.ecolumn): return 'File "{}", line {}.{}'.format( self.file, self.line, self.column) file = self.file if file == 'tests//sample.zcml': # special case for testing file = os.path.join(os.path.dirname(__file__), 'tests', 'sample.zcml') try: with open(file) as f: lines = f.readlines()[self.line - 1:self.eline] except OSError: src = " Could not read source." else: ecolumn = self.ecolumn if lines[-1][ecolumn:ecolumn + 2] == '</': # pragma: no cover # We're pointing to the start of an end tag. Try to find # the end l_ = lines[-1].find('>', ecolumn) if l_ >= 0: lines[-1] = lines[-1][:l_ + 1] else: # pragma: no cover lines[-1] = lines[-1][:ecolumn + 1] column = self.column if lines[0][:column].strip(): # pragma: no cover # Remove text before start if it's noy whitespace lines[0] = lines[0][self.column:] pad = ' ' blank = '' try: src = blank.join([pad + line for line in lines]) except UnicodeDecodeError: # pragma: no cover # XXX: # I hope so most internation zcml will use UTF-8 as encoding # otherwise this code must be made more clever src = blank.join([pad + line.decode('utf-8') for line in lines]) # unicode won't be printable, at least on my console src = src.encode('ascii', 'replace') return f"{repr(self)}\n{src}" def characters(self, characters): self.text += characters class ConfigurationHandler(ContentHandler): """ Interface to the XML parser Translate parser events into calls into the configuration system. """ locator = None def __init__(self, context, testing=False): self.context = context self.testing = testing self.ignore_depth = 0 def setDocumentLocator(self, locator): self.locator = locator def characters(self, text): self.context.getInfo().characters(text) def _handle_exception(self, ex, info): if self.testing: raise if isinstance(ex, ConfigurationError): ex.add_details(repr(info)) raise raise ZopeXMLConfigurationError(info, ex) def startElementNS(self, name, qname, attrs): if self.ignore_depth: self.ignore_depth += 1 return data = {} for (ns, aname), value in attrs.items(): # NB: even though on CPython, 'ns' will be ``None`` always, # do not change the below to "if ns is None" because Jython's # sax parser generates attrs that have empty strings for # the namepace instead of ``None``. if not ns: aname = str(aname) data[aname] = value if (ns, aname) == ZCML_CONDITION: # need to process the expression to determine if we # use this element and it's descendents use = self.evaluateCondition(value) if not use: self.ignore_depth = 1 return info = ParserInfo( self.locator.getSystemId(), self.locator.getLineNumber(), self.locator.getColumnNumber(), ) try: self.context.begin(name, data, info) except Exception as ex: self._handle_exception(ex, info) self.context.setInfo(info) def evaluateCondition(self, expression): """ Evaluate a ZCML condition. ``expression`` is a string of the form "verb arguments". Currently the supported verbs are ``have``, ``not-have``, ``installed`` and ``not-installed``. The ``have`` and ``not-have`` verbs each take one argument: the name of a feature: >>> from zope.configuration.config import ConfigurationContext >>> from zope.configuration.xmlconfig import ConfigurationHandler >>> context = ConfigurationContext() >>> context.provideFeature('apidoc') >>> c = ConfigurationHandler(context, testing=True) >>> c.evaluateCondition("have apidoc") True >>> c.evaluateCondition("not-have apidoc") False >>> c.evaluateCondition("have onlinehelp") False >>> c.evaluateCondition("not-have onlinehelp") True Ill-formed expressions raise an error: >>> c.evaluateCondition("want apidoc") Traceback (most recent call last): ... ValueError: Invalid ZCML condition: 'want apidoc' >>> c.evaluateCondition("have x y") Traceback (most recent call last): ... ValueError: Only one feature allowed: 'have x y' >>> c.evaluateCondition("have") Traceback (most recent call last): ... ValueError: Feature name missing: 'have' The ``installed`` and ``not-installed`` verbs each take one argument: the dotted name of a pacakge. If the pacakge is found, in other words, can be imported, then the condition will return true / false: >>> context = ConfigurationContext() >>> c = ConfigurationHandler(context, testing=True) >>> c.evaluateCondition('installed zope.interface') True >>> c.evaluateCondition('not-installed zope.interface') False >>> c.evaluateCondition('installed zope.foo') False >>> c.evaluateCondition('not-installed zope.foo') True Ill-formed expressions raise an error: >>> c.evaluateCondition("installed foo bar") Traceback (most recent call last): ... ValueError: Only one package allowed: 'installed foo bar' >>> c.evaluateCondition("installed") Traceback (most recent call last): ... ValueError: Package name missing: 'installed' """ arguments = expression.split(None) verb = arguments.pop(0) if verb in ('have', 'not-have'): if not arguments: raise ValueError("Feature name missing: %r" % expression) if len(arguments) > 1: raise ValueError("Only one feature allowed: %r" % expression) if verb == 'have': return self.context.hasFeature(arguments[0]) elif verb == 'not-have': return not self.context.hasFeature(arguments[0]) elif verb in ('installed', 'not-installed'): if not arguments: raise ValueError("Package name missing: %r" % expression) if len(arguments) > 1: raise ValueError("Only one package allowed: %r" % expression) try: __import__(arguments[0]) installed = True except ImportError: installed = False if verb == 'installed': return installed elif verb == 'not-installed': return not installed else: raise ValueError("Invalid ZCML condition: %r" % expression) def endElementNS(self, name, qname): # If ignore_depth is set, this element will be ignored, even # if this this decrements ignore_depth to 0. if self.ignore_depth: self.ignore_depth -= 1 return info = self.context.getInfo() info.end( self.locator.getLineNumber(), self.locator.getColumnNumber(), ) try: self.context.end() except Exception as ex: self._handle_exception(ex, info) def processxmlfile(file, context, testing=False): """Process a configuration file See examples in tests/test_xmlconfig.py """ src = InputSource(getattr(file, 'name', '<string>')) src.setByteStream(file) parser = make_parser() parser.setContentHandler(ConfigurationHandler(context, testing=testing)) parser.setFeature(feature_namespaces, True) try: parser.parse(src) except SAXParseException: raise ZopeSAXParseException(file, sys.exc_info()[1]) def openInOrPlain(filename): """ Open a file, falling back to filename.in. If the requested file does not exist and filename.in does, fall back to filename.in. If opening the original filename fails for any other reason, allow the failure to propagate. For example, the tests/samplepackage directory has files: - configure.zcml - configure.zcml.in - foo.zcml.in If we open configure.zcml, we'll get that file: >>> import os >>> from zope.configuration.xmlconfig import __file__ >>> from zope.configuration.xmlconfig import openInOrPlain >>> here = os.path.dirname(__file__) >>> path = os.path.join( ... here, 'tests', 'samplepackage', 'configure.zcml') >>> f = openInOrPlain(path) >>> f.name[-14:] 'configure.zcml' >>> f.close() But if we open foo.zcml, we'll get foo.zcml.in, since there isn't a foo.zcml: >>> path = os.path.join(here, 'tests', 'samplepackage', 'foo.zcml') >>> f = openInOrPlain(path) >>> f.name[-11:] 'foo.zcml.in' >>> f.close() Make sure other IOErrors are re-raised. We need to do this in a try-except block because different errors are raised on Windows and on Linux. >>> try: ... f = openInOrPlain('.') ... except IOError: ... print("passed") ... else: ... print("failed") passed """ try: return open(filename) except OSError as e: code, msg = e.args if code == errno.ENOENT: fn = filename + ".in" if os.path.exists(fn): return open(fn) raise class IInclude(Interface): """The `include`, `includeOverrides` and `exclude` directives. These directives allows you to include or preserve including of another ZCML file in the configuration. This enables you to write configuration files in each package and then link them together. """ file = NativeStringLine( title="Configuration file name", description=( "The name of a configuration file to be included/" "excluded, relative to the directive containing the " "including configuration file." ), required=False, ) files = NativeStringLine( title="Configuration file name pattern", description=""" The names of multiple configuration files to be included/excluded, expressed as a file-name pattern, relative to the directive containing the including or excluding configuration file. The pattern can include: - ``*`` matches 0 or more characters - ``?`` matches a single character - ``[<seq>]`` matches any character in seq - ``[!<seq>]`` matches any character not in seq The file names are included in sorted order, where sorting is without regard to case. """, required=False, ) package = GlobalObject( title="Include or exclude package", description=""" Include or exclude the named file (or configure.zcml) from the directory of this package. """, required=False, ) def include(_context, file=None, package=None, files=None): """Include a zcml file """ if files: if file: raise ValueError("Must specify only one of file or files") elif not file: file = 'configure.zcml' # This is a tad tricky. We want to behave as a grouping directive. context = GroupingContextDecorator(_context) if package is not None: context.package = package context.basepath = None if files: paths = glob(context.path(files)) paths = sorted(zip([path.lower() for path in paths], paths)) paths = [path for (l, path) in paths] else: paths = [context.path(file)] for path in paths: if context.processFile(path): with openInOrPlain(path) as f: logger.debug("include %s", f.name) context.basepath = os.path.dirname(path) context.includepath = _context.includepath + (f.name, ) _context.stack.append(GroupingStackItem(context)) processxmlfile(f, context) assert _context.stack[-1].context is context _context.stack.pop() def exclude(_context, file=None, package=None, files=None): """Exclude a zcml file This directive should be used before any ZML that includes configuration you want to exclude. """ if files: if file: raise ValueError("Must specify only one of file or files") elif not file: file = 'configure.zcml' context = GroupingContextDecorator(_context) if package is not None: context.package = package context.basepath = None if files: paths = glob(context.path(files)) paths = sorted(zip([path.lower() for path in paths], paths)) paths = [path for (l, path) in paths] else: paths = [context.path(file)] for path in paths: # processFile returns a boolean indicating if the file has been # processed or not, it *also* marks the file as having been processed, # here the side effect is used to keep the given file from being # processed in the future context.processFile(path) def includeOverrides(_context, file=None, package=None, files=None): """Include zcml file containing overrides. The actions in the included file are added to the context as if they were in the including file directly. Conflicting actions added by the named *file* or *files* are resolved before this directive completes. .. caution:: If you do not specify a *file*, then the default file of ``configure.zcml`` will be used. A common use is to set *file* to ``overrides.zcml``. """ # We need to remember how many actions we had before nactions = len(_context.actions) # We'll give the new actions this include path includepath = _context.includepath # Now we'll include the file. We'll munge the actions after include(_context, file, package, files) # Now we'll grab the new actions, resolve conflicts, # and munge the includepath: newactions = [] for action in resolveConflicts(_context.actions[nactions:]): action['includepath'] = includepath newactions.append(action) _context.actions[nactions:] = newactions def registerCommonDirectives(context): # We have to use the direct definition functions to define # a directive for all namespaces. defineSimpleDirective( context, "include", IInclude, include, namespace="*") defineSimpleDirective( context, "exclude", IInclude, exclude, namespace="*") defineSimpleDirective( context, "includeOverrides", IInclude, includeOverrides, namespace="*") defineGroupingDirective( context, name="configure", namespace="*", schema=IZopeConfigure, handler=ZopeConfigure, ) def file(name, package=None, context=None, execute=True): """Execute a zcml file """ if context is None: context = ConfigurationMachine() registerCommonDirectives(context) context.package = package include(context, name, package) if execute: context.execute_actions() return context def string(s, context=None, name="<string>", execute=True): """Execute a zcml string """ if context is None: context = ConfigurationMachine() registerCommonDirectives(context) f = io.BytesIO(s) if isinstance(s, bytes) else io.StringIO(s) f.name = name processxmlfile(f, context) if execute: context.execute_actions() return context ############################################################################## # Backward compatability, mainly for tests _context = None def _clearContext(): global _context _context = ConfigurationMachine() registerCommonDirectives(_context) def _getContext(): global _context if _context is None: _clearContext() try: from zope.testing.cleanup import addCleanUp except ImportError: # pragma: no cover pass else: # pragma: no cover addCleanUp(_clearContext) del addCleanUp return _context class XMLConfig: """Provide high-level handling of configuration files. See examples in tests/text_xmlconfig.py """ def __init__(self, file_name, module=None): context = _getContext() include(context, file_name, module) self.context = context def __call__(self): self.context.execute_actions() def xmlconfig(file, testing=False): context = _getContext() processxmlfile(file, context, testing=testing) context.execute_actions(testing=testing) def testxmlconfig(file): """xmlconfig that doesn't raise configuration errors This is useful for testing, as it doesn't mask exception types. """ context = _getContext() processxmlfile(file, context, testing=True) context.execute_actions(testing=True)
zope.configuration
/zope.configuration-5.0-py3-none-any.whl/zope/configuration/xmlconfig.py
xmlconfig.py
"""Configuration-specific schema fields """ import os import sys import warnings from zope.interface import implementer from zope.schema import Bool as schema_Bool from zope.schema import DottedName from zope.schema import Field from zope.schema import InterfaceField from zope.schema import List from zope.schema import PythonIdentifier as schema_PythonIdentifier from zope.schema import Text from zope.schema import ValidationError from zope.schema.interfaces import IFromUnicode from zope.schema.interfaces import InvalidValue from zope.configuration._compat import implementer_if_needed from zope.configuration.exceptions import ConfigurationError from zope.configuration.interfaces import InvalidToken __all__ = [ 'Bool', 'GlobalObject', 'GlobalInterface', 'MessageID', 'Path', 'PythonIdentifier', 'Tokens', ] class PythonIdentifier(schema_PythonIdentifier): r""" This class is like `zope.schema.PythonIdentifier`. Let's look at an example: >>> from zope.configuration.fields import PythonIdentifier >>> class FauxContext(object): ... pass >>> context = FauxContext() >>> field = PythonIdentifier().bind(context) Let's test the fromUnicode method: >>> field.fromUnicode(u'foo') 'foo' >>> field.fromUnicode(u'foo3') 'foo3' >>> field.fromUnicode(u'_foo3') '_foo3' Now let's see whether validation works alright >>> values = (u'foo', u'foo3', u'foo_', u'_foo3', u'foo_3', u'foo3_') >>> for value in values: ... _ = field.fromUnicode(value) >>> from zope.schema import ValidationError >>> for value in (u'3foo', u'foo:', u'\\', u''): ... try: ... field.fromUnicode(value) ... except ValidationError: ... print('Validation Error ' + repr(value)) Validation Error '3foo' Validation Error 'foo:' Validation Error '\\' Validation Error '' .. versionchanged:: 4.2.0 Extend `zope.schema.PythonIdentifier`, which implies that `fromUnicode` validates the strings. """ def _validate(self, value): super()._validate(value) if not value: raise ValidationError(value).with_field_and_value(self, value) @implementer_if_needed(IFromUnicode) class GlobalObject(Field): """ An object that can be accessed as a module global. The special value ``*`` indicates a value of `None`; this is not validated against the *value_type*. """ _DOT_VALIDATOR = DottedName() def __init__(self, value_type=None, **kw): self.value_type = value_type super().__init__(**kw) def _validate(self, value): super()._validate(value) if self.value_type is not None: self.value_type.validate(value) def fromUnicode(self, value): r""" Find and return the module global at the path *value*. >>> d = {'x': 1, 'y': 42, 'z': 'zope'} >>> class fakeresolver(dict): ... def resolve(self, n): ... return self[n] >>> fake = fakeresolver(d) >>> from zope.schema import Int >>> from zope.configuration.fields import GlobalObject >>> g = GlobalObject(value_type=Int()) >>> gg = g.bind(fake) >>> gg.fromUnicode("x") 1 >>> gg.fromUnicode(" x \n ") 1 >>> gg.fromUnicode("y") 42 >>> gg.fromUnicode("z") Traceback (most recent call last): ... WrongType: ('zope', (<type 'int'>, <type 'long'>), '') >>> g = GlobalObject(constraint=lambda x: x%2 == 0) >>> gg = g.bind(fake) >>> gg.fromUnicode("x") Traceback (most recent call last): ... ConstraintNotSatisfied: 1 >>> gg.fromUnicode("y") 42 >>> g = GlobalObject() >>> gg = g.bind(fake) >>> print(gg.fromUnicode('*')) None """ name = str(value.strip()) # special case, mostly for interfaces if name == '*': return None try: # Leading dots are allowed here to indicate current # package, but not accepted by DottedName. Take care, # though, because a single dot is valid to resolve, but # not valid to pass to DottedName (as an empty string) to_validate = name.lstrip('.') if to_validate: self._DOT_VALIDATOR.validate(to_validate) except ValidationError as v: v.with_field_and_value(self, name) raise try: value = self.context.resolve(name) except ConfigurationError as v: raise ValidationError(v).with_field_and_value(self, name) self.validate(value) return value @implementer_if_needed(IFromUnicode) class GlobalInterface(GlobalObject): """ An interface that can be accessed from a module. Example: First, we need to set up a stub name resolver: >>> from zope.interface import Interface >>> class IFoo(Interface): ... pass >>> class Foo(object): ... pass >>> d = {'Foo': Foo, 'IFoo': IFoo} >>> class fakeresolver(dict): ... def resolve(self, n): ... return self[n] >>> fake = fakeresolver(d) Now verify constraints are checked correctly: >>> from zope.configuration.fields import GlobalInterface >>> g = GlobalInterface() >>> gg = g.bind(fake) >>> gg.fromUnicode('IFoo') is IFoo True >>> gg.fromUnicode(' IFoo ') is IFoo True >>> gg.fromUnicode('Foo') Traceback (most recent call last): ... NotAnInterface: (<class 'Foo'>, ... """ def __init__(self, **kw): super().__init__(InterfaceField(), **kw) @implementer(IFromUnicode) class Tokens(List): """ A list that can be read from a space-separated string. """ def fromUnicode(self, value): r""" Split the input string and convert it to *value_type*. Consider GlobalObject tokens: First, we need to set up a stub name resolver: >>> d = {'x': 1, 'y': 42, 'z': 'zope', 'x.y.x': 'foo'} >>> class fakeresolver(dict): ... def resolve(self, n): ... return self[n] >>> fake = fakeresolver(d) >>> from zope.configuration.fields import Tokens >>> from zope.configuration.fields import GlobalObject >>> g = Tokens(value_type=GlobalObject()) >>> gg = g.bind(fake) >>> gg.fromUnicode(" \n x y z \n") [1, 42, 'zope'] >>> from zope.schema import Int >>> g = Tokens(value_type= ... GlobalObject(value_type= ... Int(constraint=lambda x: x%2 == 0))) >>> gg = g.bind(fake) >>> gg.fromUnicode("x y") Traceback (most recent call last): ... InvalidToken: 1 in x y >>> gg.fromUnicode("z y") Traceback (most recent call last): ... InvalidToken: ('zope', (<type 'int'>, <type 'long'>), '') in z y >>> gg.fromUnicode("y y") [42, 42] """ value = value.strip() if value: vt = self.value_type.bind(self.context) values = [] for s in value.split(): try: v = vt.fromUnicode(s) except ValidationError as ex: raise InvalidToken( f"{ex} in {value!r}").with_field_and_value( self, s) else: values.append(v) else: values = [] self.validate(values) return values class PathProcessor: # Internal helper for manipulations on paths @classmethod def expand(cls, filename): # Perform the expansions we want to have done. Returns a # tuple: (path, needs_processing) If the second value is true, # further processing should be done (the path isn't fully # resolved); if false, the path should be used as is filename = filename.strip() # expanding a ~ at the front should generally result # in an absolute path. filename = os.path.expanduser(filename) filename = os.path.expandvars(filename) if os.path.isabs(filename): return os.path.normpath(filename), False return filename, True @implementer_if_needed(IFromUnicode) class Path(Text): """ A file path name, which may be input as a relative path Input paths are converted to absolute paths and normalized. """ def fromUnicode(self, value): r""" Convert the input path to a normalized, absolute path. Let's look at an example: First, we need a "context" for the field that has a path function for converting relative path to an absolute path. We'll be careful to do this in an operating system independent fashion. >>> from zope.configuration.fields import Path >>> class FauxContext(object): ... def path(self, p): ... return os.path.join(os.sep, 'faux', 'context', p) >>> context = FauxContext() >>> field = Path().bind(context) Lets try an absolute path first: >>> import os >>> p = os.path.join(os.sep, u'a', u'b') >>> n = field.fromUnicode(p) >>> n.split(os.sep) ['', 'a', 'b'] This should also work with extra spaces around the path: >>> p = " \n %s \n\n " % p >>> n = field.fromUnicode(p) >>> n.split(os.sep) ['', 'a', 'b'] Environment variables are expanded: >>> os.environ['path-test'] = '42' >>> with_env = os.path.join(os.sep, u'a', u'${path-test}') >>> n = field.fromUnicode(with_env) >>> n.split(os.sep) ['', 'a', '42'] Now try a relative path: >>> p = os.path.join(u'a', u'b') >>> n = field.fromUnicode(p) >>> n.split(os.sep) ['', 'faux', 'context', 'a', 'b'] The current user is expanded (these are implicitly relative paths): >>> old_home = os.environ.get('HOME') >>> os.environ['HOME'] = os.path.join(os.sep, 'HOME') >>> n = field.fromUnicode('~') >>> n.split(os.sep) ['', 'HOME'] >>> if old_home: ... os.environ['HOME'] = old_home ... else: ... del os.environ['HOME'] .. versionchanged:: 4.2.0 Start expanding home directories and environment variables. """ filename, needs_processing = PathProcessor.expand(value) if needs_processing: filename = self.context.path(filename) return filename @implementer_if_needed(IFromUnicode) class Bool(schema_Bool): """ A boolean value. Values may be input (in upper or lower case) as any of: - yes / no - y / n - true / false - t / f .. caution:: Do not confuse this with :class:`zope.schema.Bool`. That class will only parse ``"True"`` and ``"true"`` as `True` values. Any other value will silently be accepted as `False`. This class raises a validation error for unrecognized input. """ def fromUnicode(self, value): """ Convert the input string to a boolean. Example: >>> from zope.configuration.fields import Bool >>> Bool().fromUnicode(u"yes") True >>> Bool().fromUnicode(u"y") True >>> Bool().fromUnicode(u"true") True >>> Bool().fromUnicode(u"no") False >>> Bool().fromUnicode(u"surprise") Traceback (most recent call last): ... zope.schema._bootstrapinterfaces.InvalidValue """ value = value.lower() if value in ('1', 'true', 'yes', 't', 'y'): return True if value in ('0', 'false', 'no', 'f', 'n'): return False # Unlike the superclass, anything else is invalid. raise InvalidValue().with_field_and_value(self, value) @implementer_if_needed(IFromUnicode) class MessageID(Text): """ Text string that should be translated. When a string is converted to a message ID, it is also recorded in the context. """ __factories = {} def fromUnicode(self, value): """ Translate a string to a MessageID. >>> from zope.configuration.fields import MessageID >>> class Info(object): ... file = 'file location' ... line = 8 >>> class FauxContext(object): ... i18n_strings = {} ... info = Info() >>> context = FauxContext() >>> field = MessageID().bind(context) There is a fallback domain when no domain has been specified. Exchange the warn function so we can make test whether the warning has been issued >>> warned = None >>> def fakewarn(*args, **kw): ... global warned ... warned = args >>> import warnings >>> realwarn = warnings.warn >>> warnings.warn = fakewarn >>> i = field.fromUnicode(u"Hello world!") >>> i 'Hello world!' >>> i.domain 'untranslated' >>> warned ("You did not specify an i18n translation domain for the '' field in file location",) >>> warnings.warn = realwarn With the domain specified: >>> context.i18n_strings = {} >>> context.i18n_domain = 'testing' We can get a message id: >>> i = field.fromUnicode(u"Hello world!") >>> i 'Hello world!' >>> i.domain 'testing' In addition, the string has been registered with the context: >>> context.i18n_strings {'testing': {'Hello world!': [('file location', 8)]}} >>> i = field.fromUnicode(u"Foo Bar") >>> i = field.fromUnicode(u"Hello world!") >>> from pprint import PrettyPrinter >>> pprint=PrettyPrinter(width=70).pprint >>> pprint(context.i18n_strings) {'testing': {'Foo Bar': [('file location', 8)], 'Hello world!': [('file location', 8), ('file location', 8)]}} >>> from zope.i18nmessageid import Message >>> isinstance(list(context.i18n_strings['testing'].keys())[0], ... Message) True Explicit Message IDs >>> i = field.fromUnicode(u'[View-Permission] View') >>> i 'View-Permission' >>> i.default 'View' >>> i = field.fromUnicode(u'[] [Some] text') >>> i '[Some] text' >>> i.default is None True """ # noqa: E501 line too long context = self.context domain = getattr(context, 'i18n_domain', '') if not domain: domain = 'untranslated' warnings.warn( "You did not specify an i18n translation domain for the " "'%s' field in %s" % (self.getName(), context.info.file) ) if not isinstance(domain, str): # IZopeConfigure specifies i18n_domain as a BytesLine, but that's # wrong as the filesystem uses str, and hence # zope.i18n registers ITranslationDomain utilities with str names. # If we keep bytes, we can't find those utilities. enc = sys.getfilesystemencoding() or sys.getdefaultencoding() domain = domain.decode(enc) v = super().fromUnicode(value) # Check whether there is an explicit message is specified default = None if v.startswith('[]'): v = v[2:].lstrip() elif v.startswith('['): end = v.find(']') default = v[end + 2:] v = v[1:end] # Convert to a message id, importing the factory, if necessary factory = self.__factories.get(domain) if factory is None: import zope.i18nmessageid factory = zope.i18nmessageid.MessageFactory(domain) self.__factories[domain] = factory msgid = factory(v, default) # Record the string we got for the domain i18n_strings = context.i18n_strings strings = i18n_strings.get(domain) if strings is None: strings = i18n_strings[domain] = {} locations = strings.setdefault(msgid, []) locations.append((context.info.file, context.info.line)) return msgid
zope.configuration
/zope.configuration-5.0-py3-none-any.whl/zope/configuration/fields.py
fields.py
__docformat__ = 'restructuredtext' import zope.filerepresentation.interfaces from zope.component.interfaces import ISite from zope.interface import implementer from zope.security.proxy import removeSecurityProxy from zope.container.folder import Folder MARKER = object() def noop(container): """Adapt an `IContainer` to an `IWriteDirectory` by just returning it This "works" because `IContainer` and `IWriteDirectory` have the same methods, however, the output doesn't actually implement `IWriteDirectory`. """ return container @implementer(zope.filerepresentation.interfaces.IDirectoryFactory) class Cloner: """ `IContainer` to :class:`zope.filerepresentation.interfaces.IDirectoryFactory` adapter that clones. This adapter provides a factory that creates a new empty container of the same class as it's context. """ def __init__(self, context): self.context = context def __call__(self, name): # We remove the security proxy so we can actually call the # class and return an unproxied new object. (We can't use a # trusted adapter, because the result must be unproxied.) By # registering this adapter, one effectively gives permission # to clone the class. Don't use this for classes that have # exciting side effects as a result of instantiation. :) return removeSecurityProxy(self.context).__class__() class RootDirectoryFactory: def __init__(self, context): pass def __call__(self, name): return Folder() class ReadDirectory: """Adapter to provide a file-system rendition of folders.""" def __init__(self, context): self.context = context def keys(self): keys = self.context.keys() if ISite.providedBy(self.context): return list(keys) + ['++etc++site'] return keys def get(self, key, default=None): if key == '++etc++site' and ISite.providedBy(self.context): return self.context.getSiteManager() return self.context.get(key, default) def __iter__(self): return iter(self.keys()) def __getitem__(self, key): v = self.get(key, MARKER) if v is MARKER: raise KeyError(key) return v def values(self): return map(self.get, self.keys()) def __len__(self): l_ = len(self.context) if ISite.providedBy(self.context): l_ += 1 return l_ def items(self): get = self.get return [(key, get(key)) for key in self.keys()] def __contains__(self, key): return self.get(key) is not None
zope.container
/zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/directory.py
directory.py
"""Ordered container implementation. """ __docformat__ = 'restructuredtext' from persistent import Persistent from persistent.dict import PersistentDict from persistent.list import PersistentList from zope.interface import implementer from zope.container.contained import Contained from zope.container.contained import checkAndConvertName from zope.container.contained import notifyContainerModified from zope.container.contained import setitem from zope.container.contained import uncontained from zope.container.interfaces import IOrderedContainer @implementer(IOrderedContainer) class OrderedContainer(Persistent, Contained): """ `OrderedContainer` maintains entries' order as added and moved. >>> oc = OrderedContainer() >>> int(IOrderedContainer.providedBy(oc)) 1 >>> len(oc) 0 """ def __init__(self): self._data = PersistentDict() self._order = PersistentList() def keys(self): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> oc.keys() [] >>> oc['foo'] = 'bar' >>> oc.keys() ['foo'] >>> oc['baz'] = 'quux' >>> oc.keys() ['foo', 'baz'] >>> int(len(oc._order) == len(oc._data)) 1 """ return self._order[:] def __iter__(self): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> oc.keys() [] >>> oc['foo'] = 'bar' >>> oc['baz'] = 'quux' >>> [i for i in oc] ['foo', 'baz'] >>> int(len(oc._order) == len(oc._data)) 1 """ return iter(self.keys()) def __getitem__(self, key): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> oc['foo'] = 'bar' >>> oc['foo'] 'bar' """ return self._data[key] def get(self, key, default=None): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> oc['foo'] = 'bar' >>> oc.get('foo') 'bar' >>> oc.get('funky', 'No chance, dude.') 'No chance, dude.' """ return self._data.get(key, default) def values(self): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> oc.keys() [] >>> oc['foo'] = 'bar' >>> oc.values() ['bar'] >>> oc['baz'] = 'quux' >>> oc.values() ['bar', 'quux'] >>> int(len(oc._order) == len(oc._data)) 1 """ return [self._data[i] for i in self._order] def __len__(self): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> int(len(oc) == 0) 1 >>> oc['foo'] = 'bar' >>> int(len(oc) == 1) 1 """ return len(self._data) def items(self): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> oc.keys() [] >>> oc['foo'] = 'bar' >>> oc.items() [('foo', 'bar')] >>> oc['baz'] = 'quux' >>> oc.items() [('foo', 'bar'), ('baz', 'quux')] >>> int(len(oc._order) == len(oc._data)) 1 """ return [(i, self._data[i]) for i in self._order] def __contains__(self, key): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> oc['foo'] = 'bar' >>> int('foo' in oc) 1 >>> int('quux' in oc) 0 """ return key in self._data has_key = __contains__ def _setitemf(self, key, value): if key not in self._data: self._order.append(key) self._data[key] = value def __setitem__(self, key, object): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> oc.keys() [] >>> oc['foo'] = 'bar' >>> oc._order ['foo'] >>> oc['baz'] = 'quux' >>> oc._order ['foo', 'baz'] >>> int(len(oc._order) == len(oc._data)) 1 >>> oc['foo'] = 'baz' Traceback (most recent call last): ... KeyError: 'foo' >>> oc._order ['foo', 'baz'] """ # This function creates a lot of events that other code # listens to. None of them are fired (notified) though, before # _setitemf is called. At that point we need to be sure that # we have the key in _order too. setitem(self, self._setitemf, key, object) return key def __delitem__(self, key): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> oc.keys() [] >>> oc['foo'] = 'bar' >>> oc['baz'] = 'quux' >>> oc['zork'] = 'grue' >>> oc.items() [('foo', 'bar'), ('baz', 'quux'), ('zork', 'grue')] >>> int(len(oc._order) == len(oc._data)) 1 >>> del oc['baz'] >>> oc.items() [('foo', 'bar'), ('zork', 'grue')] >>> int(len(oc._order) == len(oc._data)) 1 """ uncontained(self._data[key], self, key) del self._data[key] self._order.remove(key) def updateOrder(self, order): """ See `IOrderedContainer`. >>> oc = OrderedContainer() >>> oc['foo'] = 'bar' >>> oc['baz'] = 'quux' >>> oc['zork'] = 'grue' >>> oc.keys() ['foo', 'baz', 'zork'] >>> oc.updateOrder(['baz', 'foo', 'zork']) >>> oc.keys() ['baz', 'foo', 'zork'] >>> oc.updateOrder(['baz', 'zork', 'foo']) >>> oc.keys() ['baz', 'zork', 'foo'] >>> oc.updateOrder(['baz', 'zork', 'foo']) >>> oc.keys() ['baz', 'zork', 'foo'] >>> oc.updateOrder(('zork', 'foo', 'baz')) >>> oc.keys() ['zork', 'foo', 'baz'] >>> oc.updateOrder(['baz', 'zork']) Traceback (most recent call last): ... ValueError: Incompatible key set. >>> oc.updateOrder(['foo', 'bar', 'baz', 'quux']) Traceback (most recent call last): ... ValueError: Incompatible key set. >>> oc.updateOrder(1) Traceback (most recent call last): ... TypeError: order must be a tuple or a list. >>> oc.updateOrder('bar') Traceback (most recent call last): ... TypeError: order must be a tuple or a list. >>> oc.updateOrder(['baz', 'zork', 'quux']) Traceback (most recent call last): ... ValueError: Incompatible key set. >>> del oc['baz'] >>> del oc['zork'] >>> del oc['foo'] >>> len(oc) 0 """ if not isinstance(order, (list, tuple)): raise TypeError('order must be a tuple or a list.') if len(order) != len(self._order): raise ValueError("Incompatible key set.") order = [checkAndConvertName(x) for x in order] if frozenset(order) != frozenset(self._order): raise ValueError("Incompatible key set.") if order == self._order: return self._order[:] = order notifyContainerModified(self)
zope.container
/zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/ordered.py
ordered.py
"""Container-related interfaces """ __docformat__ = 'restructuredtext' import zope.deferredimport from zope.interface import Interface from zope.interface import Invalid from zope.interface.common.mapping import IEnumerableMapping from zope.interface.common.mapping import IItemMapping from zope.interface.common.mapping import IReadMapping from zope.lifecycleevent.interfaces import IObjectModifiedEvent from zope.schema import Set from zope.container.i18n import ZopeMessageFactory as _ zope.deferredimport.initialize() zope.deferredimport.deprecated( "Some zope.container interfaces have been moved to" " zope.lifecycleevent.interfaces, please import form there.", IObjectAddedEvent='zope.lifecycleevent.interfaces:IObjectAddedEvent', IObjectMovedEvent='zope.lifecycleevent.interfaces:IObjectMovedEvent', IObjectRemovedEvent='zope.lifecycleevent.interfaces:IObjectRemovedEvent', ) zope.deferredimport.deprecated( "Some zope.container interfaces have been moved to" " zope.location.interfaces, please import form there.", IContained='zope.location.interfaces:IContained', ILocation='zope.location.interfaces:ILocation', ) class DuplicateIDError(KeyError): pass class ContainerError(Exception): """An error of a container with one of its components.""" class InvalidContainerType(Invalid, TypeError): """The type of a container is not valid.""" class InvalidItemType(Invalid, TypeError): """The type of an item is not valid.""" class InvalidType(Invalid, TypeError): """The type of an object is not valid.""" class IItemContainer(IItemMapping): """Minimal readable container.""" class ISimpleReadContainer(IItemContainer, IReadMapping): """Readable content containers.""" class IReadContainer(ISimpleReadContainer, IEnumerableMapping): """Readable containers that can be enumerated.""" class IWriteContainer(Interface): """An interface for the write aspects of a container.""" def __setitem__(name, object): """Add the given `object` to the container under the given name. Raises a ``TypeError`` if the key is not a unicode or ascii string. Raises a ``ValueError`` if the key is empty, or if the key contains a character which is not allowed in an object name. Raises a ``KeyError`` if the key violates a uniqueness constraint. The container might choose to add a different object than the one passed to this method. If the object doesn't implement `IContained`, then one of two things must be done: 1. If the object implements `ILocation`, then the `IContained` interface must be declared for the object. 2. Otherwise, a `ContainedProxy` is created for the object and stored. The object's `__parent__` and `__name__` attributes are set to the container and the given name. If the old parent was ``None``, then an `IObjectAddedEvent` is generated, otherwise, an `IObjectMovedEvent` is generated. An `IContainerModifiedEvent` is generated for the container. If the object replaces another object, then the old object is deleted before the new object is added, unless the container vetos the replacement by raising an exception. If the object's `__parent__` and `__name__` were already set to the container and the name, then no events are generated and no hooks. This allows advanced clients to take over event generation. """ def __delitem__(name): """Delete the named object from the container. Raises a ``KeyError`` if the object is not found. If the deleted object's `__parent__` and `__name__` match the container and given name, then an `IObjectRemovedEvent` is generated and the attributes are set to ``None``. If the object can be adapted to `IObjectMovedEvent`, then the adapter's `moveNotify` method is called with the event. Unless the object's `__parent__` and `__name__` attributes were initially ``None``, generate an `IContainerModifiedEvent` for the container. If the object's `__parent__` and `__name__` were already set to ``None``, then no events are generated. This allows advanced clients to take over event generation. """ class IItemWriteContainer(IWriteContainer, IItemContainer): """A write container that also supports minimal reads.""" class IContainer(IReadContainer, IWriteContainer): """Readable and writable content container.""" class IContentContainer(IContainer): """A container that is to be used as a content type.""" class IBTreeContainer(IContainer): """Container that supports BTree semantics for some methods.""" def items(key=None): """Return an iterator over the key-value pairs in the container. If ``None`` is passed as `key`, this method behaves as if no argument were passed; exactly as required for ``IContainer.items()``. If `key` is in the container, the first item provided by the iterator will correspond to that key. Otherwise, the first item will be for the key that would come next if `key` were in the container. """ def keys(key=None): """Return an iterator over the keys in the container. If ``None`` is passed as `key`, this method behaves as if no argument were passed; exactly as required for ``IContainer.keys()``. If `key` is in the container, the first key provided by the iterator will be that key. Otherwise, the first key will be the one that would come next if `key` were in the container. """ def values(key=None): """Return an iterator over the values in the container. If ``None`` is passed as `key`, this method behaves as if no argument were passed; exactly as required for ``IContainer.values()``. If `key` is in the container, the first value provided by the iterator will correspond to that key. Otherwise, the first value will be for the key that would come next if `key` were in the container. """ class IOrdered(Interface): """Objects whose contents are maintained in order.""" def updateOrder(order): """Revise the order of keys, replacing the current ordering. order is a list or a tuple containing the set of existing keys in the new order. `order` must contain ``len(keys())`` items and cannot contain duplicate keys. Raises ``TypeError`` if order is not a tuple or a list. Raises ``ValueError`` if order contains an invalid set of keys. """ class IOrderedContainer(IOrdered, IContainer): """Containers whose contents are maintained in order.""" class IContainerNamesContainer(IContainer): """Containers that always choose names for their items.""" class IReservedNames(Interface): """A sequence of names that are reserved for that container""" reservedNames = Set( title=_('Reserved Names'), description=_('Names that are not allowed for addable content'), required=True, ) class NameReserved(ValueError): __doc__ = _("""The name is reserved for this container""") ############################################################################## # Adding objects class UnaddableError(ContainerError): """An object cannot be added to a container.""" def __init__(self, container, obj, message=""): self.container = container self.obj = obj self.message = message and ": %s" % message def __str__(self): return ("%(obj)s cannot be added " "to %(container)s%(message)s" % self.__dict__) class INameChooser(Interface): def checkName(name, object): """Check whether an object name is valid. Raises a user error if the name is not valid. """ def chooseName(name, object): """Choose a unique valid name for the object. The given name and object may be taken into account when choosing the name. chooseName is expected to always choose a valid name (that would pass the checkName test) and never raise an error. """ ############################################################################## # Modifying containers class IContainerModifiedEvent(IObjectModifiedEvent): """The container has been modified. This event is specific to "containerness" modifications, which means addition, removal or reordering of sub-objects. """ ############################################################################## # Finding objects class IFind(Interface): """ Find support for containers. """ def find(id_filters=None, object_filters=None): """Find object that matches all filters in all sub-objects. This container itself is not included. """ class IObjectFindFilter(Interface): def matches(object): """Return True if the object matches the filter criteria.""" class IIdFindFilter(Interface): def matches(id): """Return True if the id matches the filter criteria."""
zope.container
/zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/interfaces.py
interfaces.py
import os import sys import types from zope.interface import classImplements from zope.interface import implementedBy def _c_optimizations_required(): """ Return a true value if the C optimizations are required. This uses the ``PURE_PYTHON`` variable as documented in `_use_c_impl`. """ pure_env = os.environ.get('PURE_PYTHON') require_c = pure_env == "0" return require_c def _c_optimizations_available(): """ Return the C optimization module, if available, otherwise a false value. If the optimizations are required but not available, this raises the ImportError. This does not say whether they should be used or not. """ catch = () if _c_optimizations_required() else (ImportError,) try: from zope.container import _zope_container_contained as c_opt return c_opt except catch: # pragma: no cover (they build everywhere) return False def _c_optimizations_ignored(): """ The opposite of `_c_optimizations_required`. """ pure_env = os.environ.get('PURE_PYTHON') return pure_env is not None and pure_env != "0" def _should_attempt_c_optimizations(): """ Return a true value if we should attempt to use the C optimizations. This takes into account whether we're on PyPy and the value of the ``PURE_PYTHON`` environment variable, as defined in `_use_c_impl`. """ is_pypy = hasattr(sys, 'pypy_version_info') if _c_optimizations_required(): return True if is_pypy: return False return not _c_optimizations_ignored() def use_c_impl(py_impl, name=None, globs=None): """ Decorator. Given an object implemented in Python, with a name like ``Foo``, import the corresponding C implementation from ``persistent.c<NAME>`` with the name ``Foo`` and use it instead (where ``NAME`` is the module name). This can also be used for constants and other things that do not have a name by passing the name as the second argument. Example:: @use_c_impl class Foo(object): ... GHOST = use_c_impl(12, 'GHOST') If the ``PURE_PYTHON`` environment variable is set to any value other than ``"0"``, or we're on PyPy, ignore the C implementation and return the Python version. If the C implementation cannot be imported, return the Python version. If ``PURE_PYTHON`` is set to 0, *require* the C implementation (let the ImportError propagate); note that PyPy can import the C implementation in this case (and all tests pass). In all cases, the Python version is kept available in the module globals with the name ``FooPy``. If the Python version is a class that implements interfaces, then the C version will be declared to also implement those interfaces. If the Python version is a class, then each function defined directly in that class will be replaced with a new version using globals that still use the original name of the class for the Python implementation. This lets the function bodies refer to the class using the name the class is defined with, as it would expect. (Only regular functions and static methods are handled.) However, it also means that mutating the module globals later on will not be visible to the methods of the class. In this example, ``Foo().method()`` will always return 1:: GLOBAL_OBJECT = 1 @use_c_impl class Foo(object): def method(self): super(Foo, self).method() return GLOBAL_OBJECT GLOBAL_OBJECT = 2 """ name = name or py_impl.__name__ globs = globs or sys._getframe( 1).f_globals # pylint:disable=protected-access def find_impl(): if not _should_attempt_c_optimizations(): return py_impl c_opts = _c_optimizations_available() if not c_opts: # pragma: no cover return py_impl __traceback_info__ = c_opts return getattr(c_opts, name) c_impl = find_impl() # Always make available by the FooPy name globs[name + 'Py'] = py_impl if c_impl is not py_impl and isinstance(py_impl, type): # Rebind the globals of all the functions to still see the # object under its original class name, so that references # in function bodies work as expected. py_attrs = vars(py_impl) new_globals = None for k, v in list(py_attrs.items()): static = isinstance(v, staticmethod) if static: # Often this is __new__ v = v.__func__ if not isinstance(v, types.FunctionType): continue if new_globals is None: new_globals = v.__globals__.copy() new_globals[py_impl.__name__] = py_impl v = types.FunctionType( v.__code__, new_globals, k, # name v.__defaults__, v.__closure__, ) if static: v = staticmethod(v) setattr(py_impl, k, v) # copy the interface declarations, being careful not # to redeclare interfaces already implemented (through # inheritance usually) implements = list(implementedBy(py_impl)) implemented_by_c = implementedBy(c_impl) implements = [ iface for iface in implements if not implemented_by_c.isOrExtends(iface) ] if implements: # pragma: no cover classImplements(c_impl, *implements) return c_impl
zope.container
/zope.container-5.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/zope/container/_util.py
_util.py