code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
__docformat__ = "reStructuredText" import argparse import base64 import os import os.path import sys import time import warnings from urllib import error as urllib2 from urllib import parse as urlparse import zope.testbrowser.browser import zope.testbrowser.wsgi from zope.app.apidoc import classregistry VERBOSITY_MAP = {1: 'ERROR', 2: 'WARNING', 3: 'INFO'} # A mapping of HTML elements that can contain links to the attribute that # actually contains the link, with the exception of standard <a> tags. urltags = { "area": "href", "base": "href", "frame": "src", "iframe": "src", "link": "href", "img": "src", "script": "src", } def getMaxWidth(): try: import curses except ImportError: # pragma: no cover pass else: try: curses.setupterm() cols = curses.tigetnum('cols') if cols > 0: return cols except curses.error: # pragma: no cover pass return 80 # pragma: no cover def cleanURL(url): """Clean a URL from parameters.""" if '?' in url: url = url.split('?')[0] if '#' in url: url = url.split('#')[0] fragments = list(urlparse.urlparse(url)) fragments[2] = os.path.normpath(fragments[2]) fragments[2].replace('//', '/') norm = urlparse.urlunparse(fragments) return norm def completeURL(url): """Add file to URL, if not provided.""" if url.endswith('/'): url += 'index.html' if '.' not in url.split('/')[-1]: url += '/index.html' fragments = list(urlparse.urlparse(url)) fragments[2] = os.path.normpath(fragments[2]) return urlparse.urlunparse(fragments) class Link: """A link in the page.""" def __init__(self, url, rootURL, referenceURL='None'): self.rootURL = rootURL self.referenceURL = referenceURL self.originalURL = url absolute_url = urlparse.urljoin(rootURL, url) self.url = completeURL(cleanURL(url)) self.absoluteURL = completeURL(cleanURL(absolute_url)) def isLocalURL(self): """Determine whether the passed in URL is local and accessible.""" # Javascript function call if self.url.startswith('javascript:'): return False # Mail Link if self.url.startswith('mailto:'): return False # External Link if self.url.startswith('http://') and \ not self.url.startswith(self.rootURL): return False return True def isApidocLink(self): # Make sure that only apidoc links are loaded allowed_prefixes = ((self.rootURL + '++apidoc++/'), (self.rootURL + '@@/')) return self.absoluteURL.startswith(allowed_prefixes) class OnlineBrowser(zope.testbrowser.browser.Browser): def setUserAndPassword(self, user, pw): """Specify the username and password to use for the retrieval.""" user_pw = user + ':' + pw if not isinstance(user_pw, bytes): user_pw = user_pw.encode('utf-8') encoded = base64.b64encode(user_pw).strip() if not isinstance(encoded, str): encoded = encoded.decode('ascii') self.addHeader("Authorization", 'Basic ' + encoded) @classmethod def begin(cls): return cls() def end(self): pass def setDebugMode(self, debug): handle = not debug self.addHeader('X-zope-handle-errors', str(handle)) class PublisherBrowser(zope.testbrowser.wsgi.Browser): old_appsetup_context = None target_package = None zcml_file = 'configure.zcml' def setUserAndPassword(self, user, pw): """Specify the username and password to use for the retrieval.""" self.addHeader('Authorization', 'Basic {}:{}'.format(user, pw)) @classmethod def begin(cls): from zope.app.appsetup import appsetup if cls.target_package: import importlib package = importlib.import_module(cls.target_package) from zope.app.apidoc.testing import _BrowserLayer APIDocLayer = _BrowserLayer( package, name="APIDocLayer", zcml_file=cls.zcml_file, features=['static-apidoc'], allowTearDown=True ) else: from zope.app.apidoc.testing import APIDocLayer APIDocLayer.setUp() APIDocLayer.testSetUp() self = cls() # Fix up path for tests. self.old_appsetup_context = appsetup.getConfigContext() setattr(appsetup, '__config_context', APIDocLayer.context) return self def end(self): from zope.app.appsetup import appsetup from zope.app.apidoc.testing import APIDocLayer APIDocLayer.testTearDown() APIDocLayer.tearDown() setattr(appsetup, '__config_context', self.old_appsetup_context) self.old_appsetup_context = None def setDebugMode(self, debug): self.handleErrors = not debug class ArbitraryLink(zope.testbrowser.browser.Link): attr_name = 'src' def __init__(self, elem, browser, base, attr_name=None): super().__init__(elem, browser, base) if attr_name: self.attr_name = attr_name @property def url(self): relurl = self._link[self.attr_name] return self.browser._absoluteUrl(relurl) class StaticAPIDocGenerator: """Static API doc Maker""" counter = 0 linkErrors = 0 htmlErrors = 0 otherErrors = 0 visited = () _old_ignore_modules = None _old_import_unknown_modules = None def __init__(self, options): self.options = options self.linkQueue = [] if self.options.ret_kind == 'webserver': # pragma: no cover self.browser = OnlineBrowser self.base_url = self.options.url if self.base_url[-1] != '/': self.base_url += '/' else: self.browser = PublisherBrowser self.base_url = 'http://localhost/' # the.package[:the_file.zcml] if self.options.ret_kind != 'publisher': target = self.options.ret_kind.split(':', 1) self.browser.target_package = target[0] if len(target) == 2 and target[1]: self.browser.zcml_file = target[1] for url in self.options.additional_urls + [self.options.startpage]: link = Link(url, self.base_url) self.linkQueue.append(link) self.rootDir = self.options.target_dir self.maxWidth = getMaxWidth() - 13 self.needNewLine = False def __enter__(self): if not os.path.exists(self.rootDir): os.makedirs(self.rootDir) self.browser = self.browser.begin() self.browser.setUserAndPassword(self.options.username, self.options.password) self.browser.setDebugMode(self.options.debug) self._old_ignore_modules = classregistry.IGNORE_MODULES classregistry.IGNORE_MODULES = set(self.options.ignore_modules) self._old_import_unknown_modules = ( classregistry.__import_unknown_modules__) if self.options.import_unknown_modules: classregistry.__import_unknown_modules__ = True def __exit__(self, *args): self.browser.end() classregistry.IGNORE_MODULES = self._old_ignore_modules classregistry.__import_unknown_modules__ = ( self._old_import_unknown_modules) def retrieve(self): """Start the retrieval of the apidoc.""" t0 = time.time() end_time = None if self.options.max_runtime: end_time = t0 + self.options.max_runtime self.visited = set() # Turn off deprecation warnings warnings.filterwarnings("ignore", category=DeprecationWarning) # Work through all links until there are no more to work on. self.sendMessage('Starting retrieval.') while self.linkQueue: link = self.linkQueue.pop() # Sometimes things are placed many times into the queue, for # example if the same link appears twice in a page. In those cases, # we can check at this point whether the URL has been already # handled. if link.absoluteURL not in self.visited: self.showProgress(link) self.processLink(link) if end_time and time.time() >= end_time: break t1 = time.time() self.sendMessage("Run time: %.3f sec" % (t1 - t0)) self.sendMessage("Links: %i" % self.counter) if self.linkQueue: self.sendMessage("Unprocessed links: %d" % len(self.linkQueue)) self.sendMessage("Link Retrieval Errors: %i" % self.linkErrors) self.sendMessage("HTML ParsingErrors: %i" % self.htmlErrors) def showProgress(self, link): self.counter += 1 if self.options.progress: url = link.absoluteURL[-(self.maxWidth):] sys.stdout.write('\r' + ' ' * (self.maxWidth + 13)) sys.stdout.write('\rLink %5d: %s' % (self.counter, url)) sys.stdout.flush() self.needNewLine = True def sendMessage(self, msg, verbosity=4): if self.options.verbosity >= verbosity: if self.needNewLine: sys.stdout.write('\n') sys.stdout.write(VERBOSITY_MAP.get(verbosity, 'INFO') + ': ') sys.stdout.write(msg) sys.stdout.write('\n') sys.stdout.flush() self.needNewLine = False def processLink(self, link): """Process a link.""" url = link.absoluteURL # Whatever will happen, we have looked at the URL self.visited.add(url) # Retrieve the content try: self.browser.open(link.absoluteURL) except urllib2.HTTPError as error: # Something went wrong with retrieving the page. self.linkErrors += 1 self.sendMessage( '%s (%i): %s' % (error.msg, error.code, link.absoluteURL), 2) self.sendMessage('+-> Reference: ' + link.referenceURL, 2) except (urllib2.URLError, ValueError): # We had a bad URL running the publisher browser self.linkErrors += 1 self.sendMessage('Bad URL: ' + link.absoluteURL, 2) self.sendMessage('+-> Reference: ' + link.referenceURL, 2) except BaseException: # This should never happen outside the debug mode. We really want # to catch all exceptions, so that we can investigate them. self.sendMessage('Bad URL: ' + link.absoluteURL, 2) self.sendMessage('+-> Reference: ' + link.referenceURL, 2) self.otherErrors += 1 if self.options.debug: # pragma: no cover import pdb pdb.set_trace() return self._handleOneResponse(link) def _handleDirForResponse(self, link): url = link.absoluteURL # Make sure the directory exists and get a file path. relativeURL = url.replace(self.base_url, '') segments = relativeURL.split('/') filename = segments.pop() dir_part = self.rootDir for segment in segments: dir_part = os.path.join(dir_part, segment) dir_part = os.path.normpath(dir_part) if not os.path.exists(dir_part): os.makedirs(dir_part) filepath = os.path.join(dir_part, filename) return filepath def _handleFindLinksForResponse(self, link): # Now retrieve all links and rewrite the html contents = self.browser.contents if not self.browser.isHtml: return contents url = link.absoluteURL html = self.browser._response.html # pylint:disable=protected-access baseUrl = self.browser._getBaseUrl() # pylint:disable=protected-access links = html.find_all('a') links = [zope.testbrowser.browser.Link(a, self.browser, baseUrl) for a in links] for tagname, attrname in urltags.items(): tags = html.find_all(tagname) tag_links = [ArbitraryLink(a, self.browser, baseUrl, attrname) for a in tags] links.extend(tag_links) mylinks = [] for link in links: try: mylinks.append(Link(link.url, self.base_url, url)) except KeyError: # Very occasionally we get a tag that doesn't have the expected # attribute. pass links = mylinks relativeURL = url.replace(self.base_url, '') segments = relativeURL.split('/') segments.pop() # filename for page_link in links: # Make sure we do not handle unwanted links. if (not page_link.isLocalURL() or not page_link.isApidocLink()): # pragma: no cover continue # Add link to the queue if page_link.absoluteURL not in self.visited: self.linkQueue.insert(0, page_link) # Rewrite URLs parts = ['..'] * len(segments) parts.append(page_link.absoluteURL.replace(self.base_url, '')) contents = contents.replace(page_link.originalURL, '/'.join(parts)) return contents def _handleOneResponse(self, link): # Get the response content filepath = self._handleDirForResponse(link) contents = self._handleFindLinksForResponse(link) # Write the data into the file if not isinstance(contents, bytes): contents = contents.encode('utf-8') try: with open(filepath, 'wb') as f: f.write(contents) except OSError: # pragma: no cover # The file already exists, so it is a duplicate and a bad one, # since the URL misses `index.hml`. ReST can produce strange URLs # that produce this problem, and we have little control over it. # In other words, since we don't specify to open the file # in exclusive creation, perhaps it refers to a # directory? Or the disk is getting full? pass ############################################################################### # Command-line UI def _create_arg_parser(): parser = argparse.ArgumentParser() parser.add_argument("target_dir", help="The directory to contain the output files") ###################################################################### # Retrieval retrieval = parser.add_argument_group( title="Retrieval", description="Options that deal with setting up the generator") ret_kind = retrieval.add_mutually_exclusive_group() ret_kind.add_argument( '--publisher', '-p', action="store_const", dest='ret_kind', const="publisher", default='publisher', help="""Use the publisher directly to retrieve the data. The program will bring up Zope 3 for you. This is the recommended option. """) ret_kind.add_argument( '--custom-publisher', '-c', dest='ret_kind', help="""Use the publisher directly to retrieve the data and specify a custom ZCML file to load in the form of the.package[:the_file.zcml]. The package name and ZCML filename relative to the package are separated by a colon. If the ZCML filename is omitted, `configure.zcml` is assumed. The specified ZCML file needs to include `<include package='zope.app.apidoc' file='static.zcml' condition='have static-apidoc' />` or something else equivalent to `site.zcml`. """ ) ret_kind.add_argument( '--webserver', '-w', action="store_const", dest='ret_kind', const="webserver", help="Use an external Web server that is connected to Zope 3." " This is not tested.") retrieval.add_argument( '--url', '-u', action="store", dest='url', default="http://localhost/", help="""The URL that will be used to retrieve the HTML pages. This option is meaningless if you are using the publisher as backend. Also, the value of this option should *not* include the `++apidoc++` namespace.""" ) retrieval.add_argument( '--startpage', '-s', action="store", dest='startpage', default='/++apidoc++/static.html', help="""The startpage specifies the path (after the URL) that is used as the starting point to retrieve the contents. This option can be very useful for debugging, since it allows you to select specific pages. """) retrieval.add_argument( '--username', '--user', action="store", dest='username', default="mgr", help="""Username to access the Web site.""" ) retrieval.add_argument( '--password', '--pwd', action="store", dest='password', default="mgrpw", help="""Password to access the Web site.""" ) retrieval.add_argument( '--add', '-a', action="append", dest='additional_urls', nargs="*", default=[ '/@@/varrow.png', '/@@/harrow.png', '/@@/tree_images/minus.png', '/@@/tree_images/plus.png', '/@@/tree_images/minus_vline.png', '/@@/tree_images/plus_vline.png', ], help="""Add an additional URL to the list of URLs to retrieve. Specifying those is sometimes necessary, if the links are hidden in cryptic Javascript code.""" ) retrieval.add_argument( '--ignore', '-i', action="append", dest='ignore_modules', nargs="*", default=['twisted', 'zope.app.twisted.ftp.test'], help="""Add modules that should be ignored during retrieval. That allows you to limit the scope of the generated API documentation.""" ) # XXX: How can this actually be turned off or disallowed? retrieval.add_argument( '--load-all', '-l', action="store_true", dest='import_unknown_modules', default=True, help="""Retrieve all referenced modules, even if they have not been imported during the startup process.""") retrieval.add_argument( '--max-runtime', action='store', type=int, default=0, help="""If given, the program will attempt to run for no longer than this many seconds, terminating after the time limit and leaving output unfinished. This is most helpful for tests.""" ) ###################################################################### # Reporting reporting = parser.add_argument_group( title="Reporting", description="Options that configure the user output information.") reporting.add_argument( '--verbosity', '-v', type=int, dest='verbosity', default=5, help="""Specifies the reporting detail level.""" ) reporting.add_argument( '--progress', '-b', action="store_true", dest='progress', default=True, help="""Output progress status.""" ) reporting.add_argument( '--debug', '-d', action="store_true", dest='debug', help="""Run in debug mode. This will allow you to use the debugger, if the publisher experienced an error.""") return parser # ##################################################################### # Command-line processing def get_options(args=None): # original_testrunner_args = args options = _create_arg_parser().parse_args(args) # options.original_testrunner_args = original_testrunner_args return options # Command-line UI # ##################################################################### def main(args=None, generator=StaticAPIDocGenerator): options = get_options(args) maker = generator(options) try: # Replace a few things to make this work better. # First, some scripts have names like __main__ and want to # peek at sys.argv; arguments for us will not be correct # for them, so we replace argv. Likewise, they may want to # exit, and we don't want them to do that. old_argv = sys.argv sys.argv = ['program', '--help'] old_exit = sys.exit def exit(_arg): pass sys.exit = exit with maker: maker.retrieve() return maker finally: sys.argv = old_argv sys.exit = old_exit if __name__ == '__main__': import logging logging.basicConfig() main() sys.exit(0)
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/static.py
static.py
================================ Component Inspection Utilities ================================ .. currentmodule:: zope.app.apidoc.component Once you have an interface, you really want to discover on how this interface interacts with other components in Zope 3. The functions in >>> from zope.app.apidoc import component provide you with utilities to make those discoveries. The functions are explained in detail in this document. Before we start though, we have to have some interfaces to work with: >>> from zope.interface import Interface >>> class IFoo(Interface): ... pass >>> class IBar(Interface): ... pass >>> class IFooBar(IFoo, IBar): ... pass >>> class IResult(Interface): ... pass >>> class ISpecialResult(IResult): ... pass :func:`getRequiredAdapters` =========================== This function returns adapter registrations for adapters that require the specified interface. So let's create some adapter registrations: >>> from zope.publisher.interfaces import IRequest >>> from zope import component as ztapi >>> ztapi.provideAdapter(adapts=(IFoo,), provides=IResult, factory=None) >>> ztapi.provideAdapter(adapts=(IFoo, IBar), provides=ISpecialResult, factory=None) >>> ztapi.provideAdapter(adapts=(IFoo, IRequest), provides=ISpecialResult, factory=None) >>> ztapi.provideHandler(adapts=(IFoo,), factory='stubFactory') >>> regs = list(component.getRequiredAdapters(IFoo)) >>> regs.sort() >>> regs [AdapterRegistration(<BaseGlobalComponents base>, [IFoo, IBar], ISpecialResult, '', None, ''), AdapterRegistration(<BaseGlobalComponents base>, [IFoo], IResult, '', None, ''), HandlerRegistration(<BaseGlobalComponents base>, [IFoo], '', 'stubFactory', '')] Note how the adapter requiring an :class:`zope.publisher.interfaces.IRequest` at the end of the required interfaces is neglected. This is because it is recognized as a view and views are not returned by default. But you can simply turn this flag on: >>> regs = list(component.getRequiredAdapters(IFoo, withViews=True)) >>> regs.sort() >>> regs [AdapterRegistration(<BaseGlobalComponents base>, [IFoo, IBar], ISpecialResult, '', None, ''), AdapterRegistration(<BaseGlobalComponents base>, [IFoo, IRequest], ISpecialResult, '', None, ''), AdapterRegistration(<BaseGlobalComponents base>, [IFoo], IResult, '', None, ''), HandlerRegistration(<BaseGlobalComponents base>, [IFoo], '', 'stubFactory', '')] The function will also pick up registrations that have required interfaces the specified interface extends: >>> regs = list(component.getRequiredAdapters(IFoo)) >>> regs.sort() >>> regs [AdapterRegistration(<BaseGlobalComponents base>, [IFoo, IBar], ISpecialResult, '', None, ''), AdapterRegistration(<BaseGlobalComponents base>, [IFoo], IResult, '', None, ''), HandlerRegistration(<BaseGlobalComponents base>, [IFoo], '', 'stubFactory', '')] And all of the required interfaces are considered, of course: >>> regs = list(component.getRequiredAdapters(IBar)) >>> regs.sort() >>> regs [AdapterRegistration(<BaseGlobalComponents base>, [IFoo, IBar], ISpecialResult, '', None, '')] :func:`getProvidedAdapters` =========================== Of course, we are also interested in the adapters that provide a certain interface. This function returns those adapter registrations, again ignoring views by default. >>> regs = list(component.getProvidedAdapters(ISpecialResult)) >>> regs.sort() >>> regs [AdapterRegistration(<BaseGlobalComponents base>, [IFoo, IBar], ISpecialResult, '', None, '')] And by specifying the ``withView`` flag, we get views as well: >>> regs = list(component.getProvidedAdapters(ISpecialResult, withViews=True)) >>> regs.sort() >>> regs [AdapterRegistration(<BaseGlobalComponents base>, [IFoo, IBar], ISpecialResult, '', None, ''), AdapterRegistration(<BaseGlobalComponents base>, [IFoo, IRequest], ISpecialResult, '', None, '')] We can of course also ask for adapters specifying ``IResult``: >>> regs = list(component.getProvidedAdapters(IResult, withViews=True)) >>> regs.sort() >>> regs [AdapterRegistration(<BaseGlobalComponents base>, [IFoo, IBar], ISpecialResult, '', None, ''), AdapterRegistration(<BaseGlobalComponents base>, [IFoo, IRequest], ISpecialResult, '', None, ''), AdapterRegistration(<BaseGlobalComponents base>, [IFoo], IResult, '', None, '')] :func:`getClasses` ================== This package comes with a little tool called the class registry (see :doc:`classregistry`). It provides a dictionary of all classes in the visible packages. This function utilizes the registry to retrieve all classes that implement the specified interface. Let's start by creating and registering some classes: >>> from zope.interface import implementer >>> from zope.app.apidoc.classregistry import classRegistry >>> @implementer(IFoo) ... class MyFoo(object): ... pass >>> classRegistry['MyFoo'] = MyFoo >>> @implementer(IBar) ... class MyBar(object): ... pass >>> classRegistry['MyBar'] = MyBar >>> @implementer(IFooBar) ... class MyFooBar(object): ... pass >>> classRegistry['MyFooBar'] = MyFooBar Let's now see whether what results we get: >>> classes = component.getClasses(IFooBar) >>> classes.sort() >>> classes [('MyFooBar', <class 'zope.app.apidoc.doctest.MyFooBar'>)] >>> classes = component.getClasses(IFoo) >>> classes.sort() >>> classes [('MyFoo', <class 'zope.app.apidoc.doctest.MyFoo'>), ('MyFooBar', <class 'zope.app.apidoc.doctest.MyFooBar'>)] :func:`getFactories` ==================== Return the factory registrations of the factories that will return objects providing this interface. Again, the first step is to create some factories: >>> from zope.component.factory import Factory >>> from zope.component.interfaces import IFactory >>> ztapi.provideUtility(Factory(MyFoo), IFactory, 'MyFoo') >>> ztapi.provideUtility(Factory(MyBar), IFactory, 'MyBar') >>> ztapi.provideUtility( ... Factory(MyFooBar, 'MyFooBar', 'My Foo Bar'), IFactory, 'MyFooBar') Let's see whether we will be able to get them: >>> regs = list(component.getFactories(IFooBar)) >>> regs.sort() >>> regs [UtilityRegistration(<BaseGlobalComponents base>, IFactory, 'MyFooBar', <Factory for <class 'zope.app.apidoc.doctest.MyFooBar'>>, None, '')] >>> regs = list(component.getFactories(IFoo)) >>> regs.sort() >>> regs [UtilityRegistration(<BaseGlobalComponents base>, IFactory, 'MyFoo', <Factory for <class 'zope.app.apidoc.doctest.MyFoo'>>, None, ''), UtilityRegistration(<BaseGlobalComponents base>, IFactory, 'MyFooBar', <Factory for <class 'zope.app.apidoc.doctest.MyFooBar'>>, None, '')] :func:`getUtilities` ==================== Return all utility registrations for utilities that provide the specified interface. As usual, we have to register some utilities first: >>> ztapi.provideUtility(MyFoo(), IFoo) >>> ztapi.provideUtility(MyBar(), IBar) >>> ztapi.provideUtility(MyFooBar(), IFooBar) Now let's have a look what we have: >>> regs = list(component.getUtilities(IFooBar)) >>> regs.sort() >>> regs [UtilityRegistration(<BaseGlobalComponents base>, IFooBar, '', <zope.app.apidoc.doctest.MyFooBar object at ...>, None, '')] >>> regs = list(component.getUtilities(IFoo)) >>> regs.sort() >>> regs [UtilityRegistration(<BaseGlobalComponents base>, IFoo, '', <zope.app.apidoc.doctest.MyFoo object at ...>, None, ''), UtilityRegistration(<BaseGlobalComponents base>, IFooBar, '', <zope.app.apidoc.doctest.MyFooBar object at ...>, None, '')] :func:`getRealFactory` ====================== During registration, factories are commonly masked by wrapper functions. Also, factories are sometimes also ``IFactory`` instances, which are not referencable, so that we would like to return the class. If the wrapper objects/functions play nice, then they provide a ``factory`` attribute that points to the next wrapper or the original factory. The task of this function is to remove all the factory wrappers and make sure that the returned factory is referencable. >>> class Factory(object): ... pass >>> def wrapper1(*args): ... return Factory(*args) >>> wrapper1.factory = Factory >>> def wrapper2(*args): ... return wrapper1(*args) >>> wrapper2.factory = wrapper1 So whether we pass in ``Factory``, >>> component.getRealFactory(Factory) <class 'zope.app.apidoc.doctest.Factory'> ``wrapper1``, >>> component.getRealFactory(wrapper1) <class 'zope.app.apidoc.doctest.Factory'> or ``wrapper2``, >>> component.getRealFactory(wrapper2) <class 'zope.app.apidoc.doctest.Factory'> the answer should always be the ``Factory`` class. Next we are going to pass in an instance, and again we should get our class aas a result: >>> factory = Factory() >>> component.getRealFactory(factory) <class 'zope.app.apidoc.doctest.Factory'> Even, if the factory instance is wrapped, we should get the factory class: >>> def wrapper3(*args): ... return factory(*args) >>> wrapper3.factory = factory >>> component.getRealFactory(wrapper3) <class 'zope.app.apidoc.doctest.Factory'> :func:`getInterfaceInfoDictionary` ================================== This function returns a small info dictionary for an interface. It only reports the module and the name. This is useful for cases when we only want to list interfaces in the context of other components, like adapters and utilities. >>> from pprint import pprint >>> pprint(component.getInterfaceInfoDictionary(IFoo), width=1) {'module': 'zope.app.apidoc.doctest', 'name': 'IFoo'} The functions using this function use it with little care and can also sometimes pass in ``None``. In these cases we want to return ``None``: >>> component.getInterfaceInfoDictionary(None) is None True It's also possible for this function to be passed a zope.interface.declarations.Implements instance. For instance, this function is sometimes used to analyze the required elements of an adapter registration: if an adapter or subscriber is registered against a class, then the required element will be an Implements instance. In this case, we currently believe that we want to return the module and name of the object that the Implements object references. This may change. >>> from zope.interface import implementedBy >>> pprint(component.getInterfaceInfoDictionary(implementedBy(MyFoo)), width=1) {'module': 'zope.app.apidoc.doctest', 'name': 'MyFoo'} :func:`getTypeInfoDictionary` ============================= This function returns the info dictionary of a type. >>> pprint(component.getTypeInfoDictionary(tuple), width=1) {'module': 'builtins', 'name': 'tuple', 'url': 'builtins/tuple'} :func:`getSpecificationInfoDictionary` ====================================== Thsi function returns an info dictionary for the given specification. A specification can either be an interface or class. If it is an interface, it simply returns the interface dictionary: >>> pprint(component.getSpecificationInfoDictionary(IFoo)) {'isInterface': True, 'isType': False, 'module': 'zope.app.apidoc.doctest', 'name': 'IFoo'} In addition to the usual interface infos, there are two flags indicating whether the specification was an interface or type. In our case it is an interface. Let's now look at the behavior when passing a type: >>> import zope.interface >>> tupleSpec = zope.interface.implementedBy(tuple) >>> pprint(component.getSpecificationInfoDictionary(tupleSpec)) {'isInterface': False, 'isType': True, 'module': 'builtins', 'name': 'tuple', 'url': 'builtins/tuple'} For the type, we simply reuse the type info dictionary function. :func:`getAdapterInfoDictionary` ================================ This function returns a page-template-friendly dictionary representing the data of an adapter registration in an output-friendly format. Let's first create an adapter registration: >>> @implementer(IResult) ... class MyResult(object): ... pass >>> from zope.interface.registry import AdapterRegistration >>> reg = AdapterRegistration(None, (IFoo, IBar), IResult, 'FooToResult', ... MyResult, 'doc info') And now get the info dictionary: >>> pprint(component.getAdapterInfoDictionary(reg), width=50) {'doc': 'doc info', 'factory': 'zope.app.apidoc.doctest.MyResult', 'factory_url': 'zope/app/apidoc/doctest/MyResult', 'name': 'FooToResult', 'provided': {'module': 'zope.app.apidoc.doctest', 'name': 'IResult'}, 'required': [{'isInterface': True, 'isType': False, 'module': 'zope.app.apidoc.doctest', 'name': 'IFoo'}, {'isInterface': True, 'isType': False, 'module': 'zope.app.apidoc.doctest', 'name': 'IBar'}], 'zcml': None} If the factory's path cannot be referenced, for example if a type has been created using the ``type()`` builtin function, then the URL of the factory will be ``None``: >>> MyResultType = type('MyResult2', (object,), {}) >>> from zope.interface import classImplements >>> classImplements(MyResultType, IResult) >>> reg = AdapterRegistration(None, (IFoo, IBar), IResult, 'FooToResult', ... MyResultType, 'doc info') >>> pprint(component.getAdapterInfoDictionary(reg), width=50) {'doc': 'doc info', 'factory': 'zope.app.apidoc.doctest.MyResult2', 'factory_url': None, 'name': 'FooToResult', 'provided': {'module': 'zope.app.apidoc.doctest', 'name': 'IResult'}, 'required': [{'isInterface': True, 'isType': False, 'module': 'zope.app.apidoc.doctest', 'name': 'IFoo'}, {'isInterface': True, 'isType': False, 'module': 'zope.app.apidoc.doctest', 'name': 'IBar'}], 'zcml': None} This function can also handle subscription registrations, which are pretty much like adapter registrations, except that they do not have a name. So let's see how the function handles subscriptions: >>> from zope.interface.registry import HandlerRegistration >>> reg = HandlerRegistration(None, (IFoo, IBar), '', MyResult, 'doc info') >>> pprint(component.getAdapterInfoDictionary(reg)) {'doc': 'doc info', 'factory': 'zope.app.apidoc.doctest.MyResult', 'factory_url': 'zope/app/apidoc/doctest/MyResult', 'name': '', 'provided': None, 'required': [{'isInterface': True, 'isType': False, 'module': 'zope.app.apidoc.doctest', 'name': 'IFoo'}, {'isInterface': True, 'isType': False, 'module': 'zope.app.apidoc.doctest', 'name': 'IBar'}], 'zcml': None} :func:`getFactoryInfoDictionary` ================================ This function returns a page-template-friendly dictionary representing the data of a factory (utility) registration in an output-friendly format. Luckily we have already registered some factories, so we just reuse their registrations: >>> pprint(component.getFactoryInfoDictionary( ... next(component.getFactories(IFooBar)))) {'description': '<p>My Foo Bar</p>\n', 'name': 'MyFooBar', 'title': 'MyFooBar', 'url': 'zope/app/apidoc/doctest/MyFooBar'} If the factory's path cannot be referenced, for example if a type has been created using the ``type()`` builtin function, then the URL of the factory will be ``None``: >>> class IMine(Interface): ... pass >>> class FactoryBase(object): ... def getInterfaces(self): return [IMine] >>> MyFactoryType = type('MyFactory', (FactoryBase,), {}) >>> from zope.interface import classImplements >>> classImplements(MyFactoryType, IFactory) >>> ztapi.provideUtility(MyFactoryType(), IFactory, 'MyFactory') >>> pprint(component.getFactoryInfoDictionary( ... next(component.getFactories(IMine))), width=50) {'description': '', 'name': 'MyFactory', 'title': '', 'url': None} :func:`getUtilityInfoDictionary` ================================ This function returns a page-template-friendly dictionary representing the data of a utility registration in an output-friendly format. Luckily we have already registered some utilities, so we just reuse their registrations: >>> pprint(component.getUtilityInfoDictionary( ... next(component.getUtilities(IFooBar)))) {'iface_id': 'zope.app.apidoc.doctest.IFooBar', 'name': '<i>no name</i>', 'path': 'zope.app.apidoc.doctest.MyFooBar', 'url': 'Code/zope/app/apidoc/doctest/MyFooBar', 'url_name': 'X19ub25hbWVfXw=='}
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/component.rst
component.rst
__docformat__ = 'restructuredtext' import inspect from zope.interface import Interface from zope.interface import providedBy from zope.interface.interfaces import IAttribute from zope.interface.interfaces import IElement from zope.interface.interfaces import IInterface from zope.interface.interfaces import IMethod from zope.interface.interfaces import ISpecification from zope.schema.interfaces import IField from zope.app.apidoc.utilities import getDocFormat from zope.app.apidoc.utilities import getPythonPath from zope.app.apidoc.utilities import renderText def getElements(iface, type=IElement): """Return a dictionary containing the elements in an interface. The type specifies whether we are looking for attributes or methods.""" items = {} for name in iface: attr = iface[name] if type.providedBy(attr): items[name] = attr return items def getFieldsInOrder(iface, _itemkey=lambda x: x[1].order): """Return a list of (name, field) tuples in native interface order.""" items = sorted(getElements(iface, IField).items(), key=_itemkey) return items def getAttributes(iface): """Returns a list of attributes specified in the interface.""" return [(name, attr) for name, attr in getElements(iface, IAttribute).items() if not (IField.providedBy(attr) or IMethod.providedBy(attr))] def getMethods(iface): """Returns a list of methods specified in the interface.""" return getElements(iface, IMethod).items() def getFields(iface): """Returns a list of fields specified in the interface.""" return getFieldsInOrder(iface) def getInterfaceTypes(iface): """Return a list of interface types that are specified for this interface. Note that you should only expect one type at a time. """ types = list(providedBy(iface).flattened()) # Remove interfaces provided by every interface instance types.remove(ISpecification) types.remove(IElement) types.remove(Interface) # Remove interface provided by every interface type types.remove(IInterface) return types def getFieldInterface(field): """Return the interface representing the field.""" name = field.__class__.__name__ field_iface = None ifaces = tuple(providedBy(field).flattened()) for iface in ifaces: # All field interfaces implement `IField`. In case the name match # below does not work, use the first `IField`-based interface found if field_iface is None and iface.extends(IField): field_iface = iface # Usually fields have interfaces with the same name (with an 'I') if iface.getName() == 'I' + name: return iface # If not even a `IField`-based interface was found, return the first # interface of the implemented interfaces list. return field_iface or ifaces[0] def _getDocFormat(attr): module = inspect.getmodule(attr.interface) return getDocFormat(module) def getAttributeInfoDictionary(attr, format=None): """Return a page-template-friendly information dictionary.""" format = format or _getDocFormat(attr) return {'name': attr.getName(), 'doc': renderText(attr.getDoc() or '', format=format)} def getMethodInfoDictionary(method, format=None): """Return a page-template-friendly information dictionary.""" format = format or _getDocFormat(method) return {'name': method.getName(), 'signature': method.getSignatureString(), 'doc': renderText(method.getDoc() or '', format=format)} def getFieldInfoDictionary(field, format=None): """Return a page-template-friendly information dictionary.""" format = format or _getDocFormat(field) info = {'name': field.getName(), 'required': field.required, 'required_string': field.required and 'required' or 'optional', 'default': repr(field.default), 'title': field.title} # Determine the interface of the field iface = getFieldInterface(field) info['iface'] = {'name': iface.getName(), 'id': getPythonPath(iface)} # Determine the field class class_ = field.__class__ info['class'] = {'name': class_.__name__, 'path': getPythonPath(class_).replace('.', '/')} # Render the field description info['description'] = renderText(field.description or '', format=format) return info
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/interface.py
interface.py
__docformat__ = 'restructuredtext' import inspect import os.path import re import sys import types import zope.i18nmessageid from zope.component import createObject from zope.component import getMultiAdapter from zope.container.interfaces import IReadContainer from zope.interface import implementedBy from zope.interface import implementer from zope.publisher.browser import TestRequest from zope.security.checker import Global from zope.security.checker import getCheckerForInstancesOf from zope.security.interfaces import INameBasedChecker from zope.security.proxy import isinstance from zope.security.proxy import removeSecurityProxy import zope.app from zope.app.apidoc.classregistry import IGNORE_MODULES from zope.app.apidoc.classregistry import safe_import _ = zope.i18nmessageid.MessageFactory("zope") _remove_html_overhead = re.compile( r'(?sm)^<html.*<body.*?>\n(.*)</body>\n</html>\n') space_re = re.compile(r'\n^( *)\S', re.M) _marker = object() def relativizePath(path): """Convert the path to a relative form.""" matching_paths = [p for p in sys.path if path.startswith(p)] if not matching_paths: # pragma: no cover return path longest_matching_path = max(matching_paths, key=len) common_prefix = os.path.commonprefix([longest_matching_path, path]) return path.replace(common_prefix, 'Zope3') if common_prefix else path def truncateSysPath(path): """Remove the system path prefix from the path.""" matching_paths = [p for p in sys.path if path.startswith(p)] if not matching_paths: # pragma: no cover return path longest_matching_path = max(matching_paths, key=len) common_prefix = os.path.commonprefix([longest_matching_path, path]) return path.replace(common_prefix, '')[1:] if common_prefix else path @implementer(IReadContainer) class ReadContainerBase: """Base for :class:`zope.container.interfaces.IReadContainer` objects.""" __parent__ = None __name__ = None def __repr__(self): if self.__name__ is None: return super().__repr__() c = type(self) return "<{}.{} '{}' at 0x{:x}>".format( c.__module__, c.__name__, self.__name__, id(self)) def get(self, key, default=None): raise NotImplementedError() def items(self): raise NotImplementedError() def __getitem__(self, key): default = object() obj = self.get(key, default) if obj is default: raise KeyError(key) return obj def __contains__(self, key): return self.get(key) is not None def keys(self): return [k for k, _v in self.items()] def __iter__(self): return iter(self.values()) def values(self): return [v for _k, v in self.items()] def __len__(self): return len(self.items()) class DocumentationModuleBase(ReadContainerBase): """Support for implementing a documentation module.""" def withParentAndName(self, parent, name): "Subclasses need to override this if they are stateful." located = type(self)() located.__parent__ = parent located.__name__ = name return located def getPythonPath(obj): """Return the path of the object in standard Python notation. This method should try very hard to return a string, even if it is not a valid Python path. """ if obj is None: return None # Even methods like `__module__` are not allowed to be # accessed (which is probably not a bad idea). So, we remove the security # proxies for this check. naked = removeSecurityProxy(obj) qname = '' if isinstance(getattr(naked, '__qualname__', None), str): # Return just the class name, if `__qualname__` is a string: qname = naked.__qualname__ qname = qname.split('.')[0] if isinstance(naked, types.MethodType): naked = type(naked.__self__) module = getattr(naked, '__module__', _marker) if module is _marker: return naked.__name__ return '{}.{}'.format(module, qname or naked.__name__) def isReferencable(path): """Return whether the Python path is referencable.""" # Sometimes no path exists, so make a simple check first; example: None if path is None: return False # There are certain paths that we do not want to reference, most often # because they are outside the scope of this documentation for exclude_name in IGNORE_MODULES: if path.startswith(exclude_name): return False split_path = path.rsplit('.', 1) if len(split_path) == 2: module_name, obj_name = split_path else: module_name, obj_name = split_path[0], None # Do not allow private attributes to be accessible if (obj_name is not None and obj_name.startswith('_') and not (obj_name.startswith('__') and obj_name.endswith('__'))): return False module = safe_import(module_name) if module is None: return False # If the module imported correctly and no name is provided, then we are # all good. if obj_name is None: return True obj = getattr(module, obj_name, _marker) if obj is _marker: return False # Detect singeltons; those are not referencable in apidoc (yet) if hasattr(obj, '__class__') and getPythonPath(obj.__class__) == path: return False return True def _evalId(id): if isinstance(id, Global): id = id.__name__ if id == 'CheckerPublic': id = 'zope.Public' return id def getPermissionIds(name, checker=_marker, klass=_marker): """Get the permissions of an attribute.""" assert (klass is _marker) != (checker is _marker) entry = {} if klass is not _marker: checker = getCheckerForInstancesOf(klass) if checker is not None and INameBasedChecker.providedBy(checker): entry['read_perm'] = _evalId(checker.permission_id(name)) \ or _('n/a') entry['write_perm'] = _evalId(checker.setattr_permission_id(name)) \ or _('n/a') else: entry['read_perm'] = entry['write_perm'] = None return entry def _checkFunctionType(func): if not callable(func): raise TypeError( "func must be a function or method not a %s (%r)" % (type(func), func)) def getFunctionSignature(func, ignore_self=False): _checkFunctionType(func) result = str(inspect.signature(func)) if ignore_self and result.startswith("(self"): result = result.replace("(self)", "()").replace("(self, ", '(') return result def getPublicAttributes(obj): """Return a list of public attribute names.""" attrs = [] for attr in dir(obj): if attr.startswith('_'): continue try: getattr(obj, attr) except AttributeError: continue attrs.append(attr) return attrs def getInterfaceForAttribute(name, interfaces=_marker, klass=_marker, asPath=True): """Determine the interface in which an attribute is defined.""" if (interfaces is _marker) and (klass is _marker): raise ValueError("need to specify interfaces or klass") if (interfaces is not _marker) and (klass is not _marker): raise ValueError("must specify only one of interfaces and klass") if interfaces is _marker: direct_interfaces = list(implementedBy(klass)) interfaces = {} for interface in direct_interfaces: interfaces[interface] = 1 for base in interface.getBases(): interfaces[base] = 1 interfaces = interfaces.keys() for interface in interfaces: if name in interface.names(): if asPath: return getPythonPath(interface) return interface return None def columnize(entries, columns=3): """Place a list of entries into columns.""" if len(entries) % columns == 0: per_col = len(entries) // columns last_full_col = columns else: per_col = len(entries) // columns + 1 last_full_col = len(entries) % columns columns = [] col = [] in_col = 0 for entry in entries: if in_col < per_col - int(len(columns) + 1 > last_full_col): col.append(entry) in_col += 1 else: columns.append(col) col = [entry] in_col = 1 if col: columns.append(col) return columns _format_dict = { 'plaintext': 'zope.source.plaintext', 'structuredtext': 'zope.source.stx', 'restructuredtext': 'zope.source.rest' } def getDocFormat(module): """Convert a module's __docformat__ specification to a renderer source id""" format = getattr(module, '__docformat__', 'restructuredtext').lower() # The format can also contain the language, so just get the first part format = format.split(' ')[0] return _format_dict.get(format, 'zope.source.rest') def dedentString(text): """Dedent the docstring, so that docutils can correctly render it.""" dedent = min([len(match) for match in space_re.findall(text)] or [0]) return re.compile('\n {%i}' % dedent, re.M).sub('\n', text) def renderText(text, module=None, format=None, dedent=True): # dedent is ignored, we always dedent if not text: return '' if module is not None: if isinstance(module, str): module = sys.modules.get(module, None) if format is None: format = getDocFormat(module) if format is None: format = 'zope.source.rest' assert format in _format_dict.values() if isinstance(text, bytes): text = text.decode('utf-8', 'replace') try: text = dedentString(text) except TypeError as e: return 'Failed to render non-text ({!r}): {}'.format(text, e) source = createObject(format, text) renderer = getMultiAdapter((source, TestRequest())) return renderer.render()
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/utilities.py
utilities.py
==================== The Class Registry ==================== .. currentmodule:: zope.app.apidoc.classregistry This :class:`little registry <ClassRegistry>` allows us to quickly query a complete list of classes that are defined and used by Zope 3. The prime feature of the class is the :meth:`ClassRegistry.getClassesThatImplement` method that returns all classes that implement the passed interface. Another method, :meth:`ClassRegistry.getSubclassesOf` returns all registered subclassess of the given class. :class:`ClassRegistry` ====================== The class registry, subclassing the dictionary type, can be instantiated like any other dictionary: >>> from zope.app.apidoc.classregistry import ClassRegistry >>> reg = ClassRegistry() Let's now add a couple of classes to registry. The classes should implement some interfaces, so that we can test all methods on the class registry: >>> from zope.interface import Interface, implementer >>> class IA(Interface): ... pass >>> class IB(IA): ... pass >>> class IC(Interface): ... pass >>> class ID(Interface): ... pass >>> @implementer(IA) ... class A(object): ... pass >>> reg['A'] = A >>> @implementer(IB) ... class B: ... pass >>> reg['B'] = B >>> @implementer(IC) ... class C(object): ... pass >>> reg['C'] = C >>> class A2(A): ... pass >>> reg['A2'] = A2 Since the registry is just a dictionary, we can ask for all its keys, which are the names of the classes: >>> names = sorted(reg.keys()) >>> names ['A', 'A2', 'B', 'C'] >>> reg['A'] is A True There are two API methods specific to the class registry: :meth:`ClassRegistry.getClassesThatImplement` --------------------------------------------- This method returns all classes that implement the specified interface: >>> from pprint import pprint >>> pprint(reg.getClassesThatImplement(IA)) [('A', <class 'zope.app.apidoc.doctest.A'>), ('A2', <class 'zope.app.apidoc.doctest.A2'>), ('B', <class 'zope.app.apidoc.doctest.B'>)] >>> pprint(reg.getClassesThatImplement(IB)) [('B', <class 'zope.app.apidoc.doctest.B'>)] >>> pprint(reg.getClassesThatImplement(IC)) [('C', <class 'zope.app.apidoc.doctest.C'>)] >>> pprint(reg.getClassesThatImplement(ID)) [] :meth:`ClassRegistry.getSubclassesOf` ------------------------------------- This method will find all classes that inherit the specified class: >>> pprint(reg.getSubclassesOf(A)) [('A2', <class '...A2'>)] >>> pprint(reg.getSubclassesOf(B)) [] Safe Imports ============ Using the :func:`safe_import` function we can quickly look up modules by minimizing import calls. >>> from zope.app.apidoc import classregistry >>> from zope.app.apidoc.classregistry import safe_import First we try to find the path in ``sys.modules``, since this lookup is much more efficient than importing it. If it was not found, we go back and try to import the path. For security reasons, importing new modules is disabled by default, unless the global ``__import_unknown_modules__`` variable is set to true. If that also fails, we return the `default` value. Here are some examples:: >>> import sys >>> 'zope.app' in sys.modules True >>> safe_import('zope.app') is sys.modules['zope.app'] True >>> safe_import('weirdname') is None True For this example, we'll create a dummy module: >>> import os >>> import tempfile >>> dir = tempfile.mkdtemp() >>> filename = os.path.join(dir, 'testmodule.py') >>> sys.path.insert(0, dir) >>> with open(filename, 'w') as f: ... _ = f.write('# dummy module\n') The temporary module is not already imported: >>> module_name = 'testmodule' >>> module_name in sys.modules False When we try ``safe_import()`` now, we will still get the `default` value, because importing new modules is disabled by default: >>> safe_import(module_name) is None True But once we activate the ``__import_unknown_modules__`` hook, the module should be imported: >>> classregistry.__import_unknown_modules__ = True >>> safe_import(module_name).__name__ == module_name True >>> module_name in sys.modules True Now clean up the temporary module, just to play nice: >>> del sys.modules[module_name] Importing some code we cannot control, such as twisted, might raise errors when imported without having a certain environment. In those cases, the safe import should prevent the error from penetrating: >>> with open(os.path.join(dir, 'alwaysfail.py'), 'w') as f: ... _ = f.write('raise ValueError\n') >>> sys.path.insert(0, dir) >>> safe_import('alwaysfail') is None True Let's clean up the python path and temporary files: >>> del sys.path[0] >>> import shutil >>> shutil.rmtree(dir) Another method to explicitely turning off the import of certain modules is to declare that they should be ignored. For example, if we tell the class registry to ignore ``zope.app``, >>> classregistry.IGNORE_MODULES.append('zope.app') then we cannot import it anymore, even though we know it is available: >>> safe_import('zope.app') is None True Note that all sub-packages are also unavailable: >>> safe_import('zope.app.apidoc') is None True We also need to play nice concerning variables and have to reset the module globals: >>> classregistry.IGNORE_MODULES.pop() 'zope.app' >>> classregistry.__import_unknown_modules__ = False
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/classregistry.rst
classregistry.rst
__docformat__ = 'restructuredtext' import zope.component from zope.interface import implementer from zope.location.interfaces import ILocation from zope.publisher.browser import applySkin from zope.app.apidoc.interfaces import IDocumentationModule from zope.app.apidoc.utilities import ReadContainerBase @implementer(ILocation) class APIDocumentation(ReadContainerBase): """ The collection of all API documentation. This documentation is implemented using a simply :class:`~zope.container.interfaces.IReadContainer`. The items of the container are all registered utilities for :class:`~zope.app.apidoc.interfaces.IDocumentationModule`. """ def __init__(self, parent, name): self.__parent__ = parent self.__name__ = name # We must always be careful to return copies that are located beneath us. # We can't return the original because they're expected to be shared in # memory and mutating their parentage causes issues with crossing ZODB # connections and even circular parentage. Returning a # :class:`~.LocationProxy` doesn't work because URLs the utility wants to # generate can't find a parent. def get(self, key, default=None): """ Look up an ``IDocumentationModule`` utility with the given name. If found, a copy of the utility with this object as its parent, created by :meth:`~zope.app.apidoc.interfaces.IDocumentationModule.withParentAndName`, will be returned. """ # noqa: E501 line too long utility = zope.component.queryUtility( IDocumentationModule, key, default) if utility is not default: utility = utility.withParentAndName(self, key) return utility def items(self): """ Return a sorted list of `(name, utility)` pairs for all registered :class:`~.IDocumentationModule` objects. Each utility returned will be a child of this object created with :meth:`~zope.app.apidoc.interfaces.IDocumentationModule.withParentAndName`. """ items = sorted(zope.component.getUtilitiesFor(IDocumentationModule)) return [(key, value.withParentAndName(self, key)) for key, value in items] class apidocNamespace: """Used to traverse to an API Documentation. Instantiating this object with a request will apply the :class:`zope.app.apidoc.browser.skin.APIDOC` skin automatically. """ def __init__(self, ob, request=None): if request: from zope.app.apidoc.browser.skin import APIDOC applySkin(request, APIDOC) self.context = ob def traverse(self, name, ignore): return handleNamespace(self.context, name) def handleNamespace(ob, name): """Used to traverse to an API Documentation.""" return APIDocumentation(ob, '++apidoc++' + name)
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/apidoc.py
apidoc.py
from zope.browserresource.icon import IconViewFactory from zope.component import getGlobalSiteManager from zope.i18nmessageid import ZopeMessageFactory as _ from zope.interface import Interface from zope.publisher.interfaces import IRequest from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.ftp import IFTPRequest from zope.publisher.interfaces.http import IHTTPRequest from zope.publisher.interfaces.xmlrpc import IXMLRPCRequest from zope.app.apidoc.component import getInterfaceInfoDictionary from zope.app.apidoc.component import getParserInfoInfoDictionary from zope.app.apidoc.utilities import getPermissionIds from zope.app.apidoc.utilities import getPythonPath from zope.app.apidoc.utilities import relativizePath SPECIFIC_INTERFACE_LEVEL = 1 EXTENDED_INTERFACE_LEVEL = 2 GENERIC_INTERFACE_LEVEL = 4 BROWSER_DIRECTIVES_MODULE = 'zope.app.publisher.browser.viewmeta' XMLRPC_DIRECTIVES_MODULE = 'zope.app.publisher.xmlrpc.metaconfigure' JSONRPC_DIRECTIVES_MODULE = 'jsonserver.metaconfigure' def getViewFactoryData(factory): """Squeeze some useful information out of the view factory""" info = {'path': None, 'url': None, 'template': None, 'resource': None, 'referencable': True} # Always determine the most basic factory # Commonly, factories are wrapped to provide security or location, for # example. If those wrappers play nice, then they provide a `factory` # attribute, that points to the original factory. while hasattr(factory, 'factory'): factory = factory.factory if getattr(factory, '__name__', '').startswith('SimpleViewClass'): # In the case of a SimpleView, the base is really what we are # interested in. Usually the first listed class is the interesting one. base = factory.__bases__[0] info['path'] = base.__module__ + '.' + base.__name__ info['template'] = relativizePath(factory.index.filename) info['template_obj'] = factory.index # Basic Type is a factory elif isinstance(factory, (str, float, int, list, tuple)): info['referencable'] = False elif factory.__module__ is not None: if factory.__module__.startswith(BROWSER_DIRECTIVES_MODULE): info['path'] = getPythonPath(factory.__bases__[0]) # XML-RPC view factory, generated during registration elif (factory.__module__.startswith(XMLRPC_DIRECTIVES_MODULE) # JSON-RPC view factory, generated during registration # This is needed for the 3rd party jsonserver implementation # TODO: See issue http://www.zope.org/Collectors/Zope3-dev/504, # ri or factory.__module__.startswith(JSONRPC_DIRECTIVES_MODULE)): # Those factories are method publisher and security wrapped info['path'] = getPythonPath(factory.__bases__[0].__bases__[0]) if not info['path'] and not hasattr(factory, '__name__'): # A factory that is a class instance; since we cannot reference # instances, reference the class. info['path'] = getPythonPath(factory.__class__) if not info['path']: # Either a simple class-based factory, or not. It doesn't # matter. We have tried our best; just get the Python path as # good as you can. info['path'] = getPythonPath(factory) if info['referencable']: info['url'] = info['path'].replace('.', '/') if isinstance(factory, IconViewFactory): info['resource'] = factory.rname return info def getPresentationType(iface): """Get the presentation type from a layer interface.""" # Note that the order of the requests matters here, since we want to # inspect the most specific one first. For example, IBrowserRequest is also # an IHTTPRequest. for kind in [IBrowserRequest, IXMLRPCRequest, IHTTPRequest, IFTPRequest]: if iface.isOrExtends(kind): return kind return iface def getViews(iface, type=IRequest): """Get all view registrations for a particular interface.""" gsm = getGlobalSiteManager() for reg in gsm.registeredAdapters(): if (reg.required and reg.required[-1] is not None and reg.required[-1].isOrExtends(type)): for required_iface in reg.required[:-1]: if required_iface is None or iface.isOrExtends(required_iface): yield reg def filterViewRegistrations(regs, iface, level=SPECIFIC_INTERFACE_LEVEL): """Return only those registrations that match the specifed level""" for reg in regs: if level & GENERIC_INTERFACE_LEVEL: for required_iface in reg.required[:-1]: if required_iface in (Interface, None): yield reg continue if level & EXTENDED_INTERFACE_LEVEL: for required_iface in reg.required[:-1]: if required_iface is not Interface and \ iface.extends(required_iface): yield reg continue if level & SPECIFIC_INTERFACE_LEVEL: for required_iface in reg.required[:-1]: if required_iface is iface: yield reg continue def getViewInfoDictionary(reg): """Build up an information dictionary for a view registration.""" # get configuration info if isinstance(reg.info, str): doc = reg.info zcml = None else: doc = None zcml = getParserInfoInfoDictionary(reg.info) info = {'name': str(reg.name) or _('<i>no name</i>'), 'type': getPythonPath(getPresentationType(reg.required[-1])), 'factory': getViewFactoryData(reg.factory), 'required': [getInterfaceInfoDictionary(iface) for iface in reg.required], 'provided': getInterfaceInfoDictionary(reg.provided), 'doc': doc, 'zcml': zcml } # Educated guess of the attribute name info.update(getPermissionIds('publishTraverse', klass=reg.factory)) return info
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/presentation.py
presentation.py
================================== Utilities Menu and Details Views ================================== .. currentmodule:: zope.app.apidoc.utilitymodule.browser :class:`Menu` ============= This is a class that helps building the menu. The ``menu_macros`` expect the menu view class to have the :meth:`Menu.getMenuTitle` and :meth:`Menu.getMenuLink` methods implemented. ``node`` is a :class:`zope.app.tree.node.Node` instance. Let's start by creating the menu: >>> from zope.app.apidoc.utilitymodule.browser import Menu >>> menu = Menu() then we need a Utility module instance and add context and request to menu: >>> from zope.publisher.browser import TestRequest >>> module = apidoc.get('Utility') >>> request = TestRequest() >>> menu.context = module >>> menu.request = request Now we want to get the menu title and link for a utility interface. To do that we first have to create a utility interface >>> from zope.app.apidoc.tests import Root >>> from zope.app.apidoc.utilitymodule.utilitymodule import UtilityInterface >>> uiface = UtilityInterface(Root(), 'foo.bar.iface', None) and then wrap it in a node: >>> from zope.app.tree.node import Node >>> node = Node(uiface) You can now get the title and link from the menu: >>> menu.getMenuTitle(node) 'iface' >>> menu.getMenuLink(node) 'http://127.0.0.1/++apidoc++/Interface/foo.bar.iface/index.html' Next, let's get the menu title and link for a utility with a name. We first have to create a utility registration >>> foobar_reg = type( ... 'RegistrationStub', (), ... {'name': 'FooBar', 'provided': None, ... 'component': None, 'info': ''})() which is then wrapped in a :class:`~zope.app.apidoc.utilitymodule.utilitymodule.Utility` documentation class and then in a node: >>> from zope.app.apidoc.utilitymodule.utilitymodule import Utility >>> util = Utility(uiface, foobar_reg) >>> node = Node(util) We can now ask the menu to give us the tile and link for the utility: >>> menu.getMenuTitle(node) 'FooBar' >>> menu.getMenuLink(node) 'http://127.0.0.1/++apidoc++/Utility/foo.bar.iface/Rm9vQmFy/index.html' Finally, we get menu title and link for a utility without a name: >>> from zope.app.apidoc.utilitymodule.utilitymodule import NONAME >>> noname_reg = type( ... 'RegistrationStub', (), ... {'name': NONAME, 'provided': None, ... 'component': None, 'info': ''})() >>> util = Utility(uiface, noname_reg) >>> node = Node(util) >>> menu.getMenuTitle(node) 'no name' >>> menu.getMenuLink(node) 'http://127.0.0.1/++apidoc++/Utility/foo.bar.iface/X19ub25hbWVfXw==/index.html' :class:`UtilityDetails` ======================= This class provides presentation-ready data about a particular utility. :meth:`UtilityDetails.getName` ------------------------------ Get the name of the utility. >>> from zope.app.apidoc.utilitymodule.browser import UtilityDetails >>> details = UtilityDetails() >>> details.context = Utility(None, foobar_reg) >>> details.getName() 'FooBar' Return the string ``no name``, if the utility has no name. >>> details.context = Utility(None, noname_reg) >>> details.getName() 'no name' :meth:`UtilityDetails.getInterface` ----------------------------------- Return the interface details view for the interface the utility provides. Let's start by creating the utility interface and building a utility registration: >>> from zope.interface import Interface >>> class IBlah(Interface): ... pass >>> blah_reg = type( ... 'RegistrationStub', (), ... {'name': 'Blah', 'provided': IBlah, ... 'component': None, 'info': ''})() Then we wrap the registration in the utility documentation class and create the details view: >>> details = UtilityDetails() >>> details.context = Utility(None, blah_reg) >>> details.request = None Now that we have the details view, we can look up the interface's detail view and get the id (for example): >>> iface = details.getInterface() >>> iface.getId() 'builtins.IBlah' :meth:`UtilityDetails.getComponent` ----------------------------------- Return the Python path and a code browser URL path of the implementation class. This time around we create the utility class and put it into a utility registration: >>> class Foo(object): ... pass >>> foo_reg = type( ... 'RegistrationStub', (), ... {'name': '', 'provided': Interface, 'component': Foo(), 'info': ''})() Then we create a utility documentation class and its details view: >>> details = UtilityDetails() >>> details.context = Utility(Interface, foo_reg) Now we can get the component information: >>> from pprint import pprint >>> pprint(details.getComponent(), width=1) {'path': 'builtins.Foo', 'url': None}
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/utilitymodule/browser.rst
browser.rst
__docformat__ = 'restructuredtext' import base64 import binascii import zope.component from zope.i18nmessageid import ZopeMessageFactory as _ from zope.interface import implementer from zope.location.interfaces import ILocation from zope.app.apidoc.interfaces import IDocumentationModule from zope.app.apidoc.utilities import DocumentationModuleBase from zope.app.apidoc.utilities import ReadContainerBase from zope.app.apidoc.utilities import getPythonPath # Constant used when the utility has no name NONAME = '__noname__' def encodeName(name): """Encode the name in URL safe base 64.""" name = base64.urlsafe_b64encode(name.encode('utf-8')) if not isinstance(name, str): name = name.decode('ascii') return name def decodeName(name): """Decode the name as encoded by :func:`encodeName`.""" try: to_decode = name if not isinstance(to_decode, bytes): to_decode = to_decode.encode("ascii") return base64.urlsafe_b64decode(to_decode).decode('utf-8') except (binascii.Error, TypeError): # Someone probably passed a non-encoded name, so let's accept that. return name @implementer(ILocation) class Utility: """Representation of a utility for the API Documentation""" def __init__(self, parent, reg): """Initialize Utility object.""" self.__parent__ = parent self.__name__ = encodeName(reg.name or NONAME) self.name = reg.name or NONAME self.registration = reg self.interface = reg.provided self.component = reg.component self.doc = reg.info @implementer(ILocation) class UtilityInterface(ReadContainerBase): """Representation of an interface a utility provides.""" def __init__(self, parent, name, interface): self.__parent__ = parent self.__name__ = name self.interface = interface def get(self, key, default=None): """See zope.container.interfaces.IReadContainer""" sm = zope.component.getGlobalSiteManager() key = decodeName(key) if key == NONAME: key = '' utils = [Utility(self, reg) for reg in sm.registeredUtilities() if reg.name == key and reg.provided == self.interface] return utils[0] if utils else default def items(self): """See zope.container.interfaces.IReadContainer""" sm = zope.component.getGlobalSiteManager() items = [(encodeName(reg.name or NONAME), Utility(self, reg)) for reg in sm.registeredUtilities() if self.interface == reg.provided] return sorted(items) @implementer(IDocumentationModule) class UtilityModule(DocumentationModuleBase): """ Represent the Documentation of all Interfaces. The items of the container are all utility interfaces registered in the site manager. """ #: Title. title = _('Utilities') #: Description. description = _(""" Utilities are also nicely registered in a site manager, so that it is easy to create a listing of available utilities. A utility is identified by the providing interface and a name, which can be empty. The menu provides you with a list of interfaces that utilities provide and as sub-items the names of the various implementations. Again, the documentation of a utility lists all the attributes/fields and methods the utility provides and provides a link to the implementation. """) def get(self, key, default=None): parts = key.split('.') try: mod = __import__('.'.join(parts[:-1]), {}, {}, ('*',)) except ImportError: return default else: return UtilityInterface( self, key, getattr(mod, parts[-1], default)) def items(self): # Use a list of site managers, since we want to support multiple bases smlist = [zope.component.getSiteManager()] seen = [] ifaces = {} while smlist: # Get the next site manager sm = smlist.pop() # If we have already looked at this site manager, then skip it if sm in seen: # pragma: no cover continue # Add the current site manager to the list of seen ones seen.append(sm) # Add the bases of the current site manager to the list of site # managers to be processed smlist += list(sm.__bases__) for reg in sm.registeredUtilities(): path = getPythonPath(reg.provided) ifaces[path] = UtilityInterface(self, path, reg.provided) items = sorted(ifaces.items(), key=lambda x: x[0].split('.')[-1]) return items
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/utilitymodule/utilitymodule.py
utilitymodule.py
==================================== The Utilities Documentation Module ==================================== .. currentmodule:: zope.app.apidoc.utilitymodule.utilitymodule This documentation module organizes all registered utilities by their provided interface and then by the name of the utility. :class:`UtilityModule` ====================== This class represents the documentation of all utility interfaces. The items of the container are all :class:`UtilityInterface` instances. Let's start by creating a utility documentation module: >>> from zope.app.apidoc.utilitymodule.utilitymodule import UtilityModule >>> module = UtilityModule() To make the documentation module useful, we have to register a utility, so why not the documentation module itself? >>> from zope.app.apidoc.interfaces import IDocumentationModule >>> from zope import component as ztapi >>> ztapi.provideUtility(module, IDocumentationModule, 'Utility') Now we can get a single utility interface by path: >>> module.get('zope.app.apidoc.interfaces.IDocumentationModule') <zope.app.apidoc.utilitymodule.utilitymodule.UtilityInterface ...> and list all available interfaces: >>> module.items() [... ('zope.app.apidoc.interfaces.IDocumentationModule', <zope.app.apidoc.utilitymodule.utilitymodule.UtilityInterface ...>), ... ('zope.security.interfaces.IPermission', <zope.app.apidoc.utilitymodule.utilitymodule.UtilityInterface ...>), ...] :class:`UtilityInterface` ========================= Representation of an interface a utility provides. First we create a utility interface documentation instance: >>> from zope.app.apidoc.utilitymodule.utilitymodule import UtilityInterface >>> ut_iface = UtilityInterface( ... module, ... 'zope.app.apidoc.interfaces.IDocumentationModule', ... IDocumentationModule) Now we can get the utility: >>> ut_iface.get('Utility').component <zope.app.apidoc.utilitymodule.utilitymodule.UtilityModule object at ...> Unnamed utilities are special, since they can be looked up in different ways: >>> ztapi.provideUtility(module, IDocumentationModule, '') >>> ut_iface.get('').component <zope.app.apidoc.utilitymodule.utilitymodule.UtilityModule object at ...> >>> from zope.app.apidoc.utilitymodule.utilitymodule import NONAME >>> ut_iface.get(NONAME).component <zope.app.apidoc.utilitymodule.utilitymodule.UtilityModule object at ...> If you try to get a non-existent utility, ``None`` is returned: >>> ut_iface.get('foo') is None True You can get a list of available utilities as well, of course: >>> ut_iface.items() [... ('VXRpbGl0eQ==', <...apidoc.utilitymodule.utilitymodule.Utility ...>), ('X19ub25hbWVfXw==', <...apidoc.utilitymodule.utilitymodule.Utility ...>)] Bu what are those strange names? Since utility names can be any string, it is hard to deal with them in a URL. Thus the system will advertise and use the names in their ``BASE64`` encoded form. However, because it is easier in the Python API to use the real utility names, utilities can be looked up in their original form as well. Encoding and Decoding Names =========================== The utility names are en- and decoded using two helper methods: >>> from zope.app.apidoc.utilitymodule.utilitymodule import encodeName >>> from zope.app.apidoc.utilitymodule.utilitymodule import decodeName Round trips of :func:`encoding <encodeName>` and :func:`decoding <decodeName>` should be possible: >>> encoded = encodeName('Some Utility') >>> encoded 'U29tZSBVdGlsaXR5' >>> decodeName(encoded) 'Some Utility' If a string is not encoded, the decoding process will simply return the original string: >>> decodeName('Some Utility') 'Some Utility'
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/utilitymodule/README.rst
README.rst
__docformat__ = 'restructuredtext' from zope.location import LocationProxy from zope.security.proxy import isinstance from zope.security.proxy import removeSecurityProxy from zope.traversing.api import getName from zope.traversing.api import getParent from zope.app.apidoc.browser.utilities import findAPIDocumentationRootURL from zope.app.apidoc.component import getUtilityInfoDictionary from zope.app.apidoc.ifacemodule.browser import InterfaceDetails from zope.app.apidoc.utilities import getPythonPath from zope.app.apidoc.utilitymodule.utilitymodule import NONAME from zope.app.apidoc.utilitymodule.utilitymodule import Utility from zope.app.apidoc.utilitymodule.utilitymodule import UtilityInterface class UtilityDetails: """Utility Details View.""" context = None request = None def getAPIDocRootURL(self): return findAPIDocumentationRootURL(self.context, self.request) def getName(self): """Get the name of the utility.""" name = self.context.name if name == NONAME: return 'no name' return name def getInterface(self): """Return the interface the utility provides.""" schema = LocationProxy(self.context.interface, self.context, getPythonPath(self.context.interface)) details = InterfaceDetails(schema, self.request) return details def getComponent(self): """Return the python path of the implementation class.""" # Remove proxy here, so that we can determine the type correctly naked = removeSecurityProxy(self.context.registration) result = getUtilityInfoDictionary(naked) return {'path': result['path'], 'url': result['url']} class Menu: """Menu View Helper Class""" context = None request = None def getMenuTitle(self, node): """Return the title of the node that is displayed in the menu.""" obj = node.context if isinstance(obj, UtilityInterface): return getName(obj).split('.')[-1] if obj.name == NONAME: return 'no name' return obj.name def getMenuLink(self, node): """Return the HTML link of the node that is displayed in the menu.""" obj = node.context apidoc_url = findAPIDocumentationRootURL(self.context, self.request) if isinstance(obj, Utility): iface = getParent(obj) return '{}/Utility/{}/{}/index.html'.format( apidoc_url, getName(iface), getName(obj)) if isinstance(obj, UtilityInterface): return '{}/Interface/{}/index.html'.format( apidoc_url, getName(obj))
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/utilitymodule/browser.py
browser.py
======================= Generic API Doc Views ======================= Get a browser started: >>> from zope.testbrowser.wsgi import Browser >>> browser = Browser() >>> browser.addHeader('Authorization', 'Basic mgr:mgrpw') Not Found View ============== The `APIDOC` skin defines a custom not found view, since it fits the look and feel better and does not have all the O-wrap clutter: >>> # work around for https://github.com/python/cpython/issues/90113 >>> browser.handleErrors = False >>> browser.raiseHttpErrors = False >>> browser.open('http://localhost/++apidoc++/non-existent/') Traceback (most recent call last): ... zope.publisher.interfaces.NotFound: ... >>> browser.handleErrors = True >>> browser.raiseHttpErrors = True >>> try: ... browser.open('http://localhost/++apidoc++/non-existent/') ... except Exception: ... pass >>> print(browser.contents) <... <h1 class="details-header"> Page Not Found </h1> <BLANKLINE> <p> While broken links occur occassionally, they are considered bugs. Please report any broken link to <a href="mailto:[email protected]">[email protected]</a>. </p> ... Preferences =========== The ``APIDOC`` skin also does the same for editing preference groups: >>> browser.open('http://localhost/++preferences++apidoc/InterfaceDetails/apidocIndex.html') >>> print(browser.contents) <... <div class="documentation"><p>Preferences for API Docs' Interface Details Screen</p> ...
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/browser/README.rst
README.rst
function switchDisplay(id) { if(document.getElementById) { // DOM var element = document.getElementById(id); } else { if(document.all) { // Proprietary DOM var element = document.all[id]; } else { // Create an object to prevent errors further on var element = new Object(); } } if(!element) { /* The page has not loaded or the browser claims to support document.getElementById or document.all but cannot actually use either */ return; } // Reference the style ... if (element.style) { style = element.style; } if (typeof(style.display) == 'undefined' && !( window.ScriptEngine && ScriptEngine().indexOf('InScript') + 1 ) ) { //The browser does not allow us to change the display style //Alert something sensible (not what I have here ...) window.alert( 'Your browser does not support this' ); return; } // Change the display style if (style.display == 'none') { style.display = ''; switchImage(id, 'harrow.png', 'varrow.png'); } else { style.display = 'none' switchImage(id, 'varrow.png', 'harrow.png'); } } function switchImage(id, oldname, newname) { if(document.getElementById) { // DOM var element = document.getElementById(id+'.arrow'); } else { // Proprietary DOM var element = document.all[id+'.arrow']; } element.src = element.src.replace(oldname, newname); } /* search in list of hrefs to avoid requests to the backend */ var found_sets = new Array(); // init a global array that holds lists for // found elements function getSearchResult(searchtext) { if (searchtext.length == 0) found_sets = new Array(); var searchindex = searchtext.length - 1; // process backspace i.e search string gets shorter if (found_sets.length > searchindex) { rubbish = found_sets.pop(); var idlist = found_sets[searchindex]; for (var n = 0 ; n < idlist.length ; n++) { element = document.getElementById(idlist[n]); element.style.display='block'; } return; } var reslist = document.getElementById('resultlist'); var children = reslist.getElementsByTagName('div') //reslist.childNodes; var element; var subelement; var refelement; var comparetext; var compareresult; var resultarray = new Array(); var itemcount = 0; for (var n = 0 ; n < children.length ; n++) { element = children[n]; // get one div element element.style.display='none' ; // reset visibility subelement = element.getElementsByTagName('a'); // get list of a subelements refelement = subelement[0]; // get one a element comparetext = refelement.firstChild.nodeValue; // get textnode of a element compareresult = comparetext.search(searchtext); if (compareresult != -1) {element.style.display='block'; resultarray[itemcount] = element.getAttribute("id"); itemcount = itemcount + 1; } } found_sets[searchindex] = resultarray; } function simplegetSearchResult(searchtext) { var searchindex = searchtext.length - 1; var reslist = document.getElementById('resultlist'); var children = reslist.getElementsByTagName('div') //reslist.childNodes; var element; var subelement; var refelement; var comparetext; var compareresult; for (var n = 0 ; n < children.length ; n++) { element = children[n]; // get one div element element.style.display='none' // reset visibility subelement = element.getElementsByTagName('a'); // get list of a subelements refelement = subelement[0]; // get one a element comparetext = refelement.firstChild.nodeValue; // get textnode of a element compareresult = comparetext.search(searchtext); if (compareresult != -1) {element.style.display='block';} } } /* Do tree collapsing and expanding by setting table row elements style display to none or block and set the images appropriate */ function treeClick(treeid) { var prent = document.getElementById(treeid).parentNode; var children = prent.getElementsByTagName('tr'); var found = 0; var action = "block"; var treeiddepth = 0; for (var n = 0; n < children.length; n++) { var element = children[n]; if (found==1) { if ( treeiddepth < element.getAttribute("treedepth") ) { element.style.display = action; var elid = element.getAttribute("id"); if (document.getElementById("i"+elid) != null) { var subimg = document.getElementById("i"+elid) if (action=="none" && subimg.src.search('minus') != -1) { subimg.src = subimg.src.replace('minus', 'plus'); } if (action=="block" && subimg.src.search('plus') != -1) { subimg.src = subimg.src.replace('plus', 'minus'); } } } else { return; } } if (element.getAttribute("id")==treeid) { found = 1; treeiddepth = element.getAttribute("treedepth") var img = document.getElementById("i"+treeid); if (img.src.search('minus') != -1) { img.src = img.src.replace('minus', 'plus'); action="none"; } else { img.src = img.src.replace('plus', 'minus'); action="block"; } } } }
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/browser/utilities.js
utilities.js
========================================= API doc when developer mode is disabled ========================================= The API docs should not be exposed to anybody as they allow introspection of code and files on the file system that should not be exposed through the web. In this test case, the developer mode was disabled, so we will only see a page informing the user that the API docs are disabled. We do this as we changed the default during the release of Zope 3.3 and many developers will still assume that their instances are running in developer mode, while they aren't. >>> from zope.testbrowser.wsgi import Browser >>> browser = Browser() >>> browser.handleErrors = False >>> browser.addHeader('Authorization', 'Basic mgr:mgrpw') >>> browser.open("http://localhost/++apidoc++") >>> browser.contents '...API documentation is disabled...'
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/browser/nodevmode.rst
nodevmode.rst
__docformat__ = 'restructuredtext' from zope.component import getUtilitiesFor from zope.component import queryUtility from zope.i18nmessageid import ZopeMessageFactory as _ from zope.interface import implementer from zope.interface.interfaces import IInterface from zope.location import LocationProxy from zope.location.interfaces import ILocation from zope.app.apidoc.interfaces import IDocumentationModule from zope.app.apidoc.utilities import DocumentationModuleBase from zope.app.apidoc.utilities import ReadContainerBase @implementer(ILocation) class TypeInterface(ReadContainerBase): """Representation of the special type interface. Demonstration:: >>> from zope.interface import Interface >>> class IFoo(Interface): ... pass >>> class IDerivedFoo(IFoo): ... pass >>> from zope import component as ztapi >>> ztapi.provideUtility(IDerivedFoo, IFoo, 'Foo') >>> typeiface = TypeInterface(IFoo, None, None) >>> typeiface.interface <InterfaceClass zope.app.apidoc.typemodule.type.IFoo> >>> typeiface.get('Foo').__class__ <class 'zope.interface.interface.InterfaceClass'> >>> typeiface.items() [('Foo', <InterfaceClass zope.app.apidoc.typemodule.type.IDerivedFoo>)] """ def __init__(self, interface, parent, name): self.__parent__ = parent self.__name__ = name self.interface = interface def get(self, key, default=None): """See zope.container.interfaces.IReadContainer""" return LocationProxy( queryUtility(self.interface, key, default=default), self, key) def items(self): """See zope.container.interfaces.IReadContainer""" results = [(name, LocationProxy(iface, self, name)) for name, iface in getUtilitiesFor(self.interface)] results.sort(key=lambda x: (x[1].getName(), x[0])) return results @implementer(IDocumentationModule) class TypeModule(DocumentationModuleBase): r"""Represent the Documentation of all interface types. Demonstration:: >>> class IFoo(IInterface): ... pass >>> from zope import component as ztapi >>> ztapi.provideUtility(IFoo, IInterface, 'IFoo') >>> module = TypeModule() >>> type = module.get('IFoo') >>> type.interface <InterfaceClass zope.app.apidoc.typemodule.type.IFoo> >>> [type.interface for name, type in module.items()] [<InterfaceClass zope.app.apidoc.typemodule.type.IFoo>] """ #: Title title = _('Interface Types') #: Description description = _(""" Here you can see all registered interface types. When you open the subtree of a specific interface type, you can see all the interfaces that provide this type. This can be very useful in cases where you want to determine all content type interfaces, for example. """) def get(self, key, default=None): return TypeInterface( queryUtility(IInterface, key, default=default), self, key) def items(self): results = [(name, TypeInterface(iface, self, name)) for name, iface in getUtilitiesFor(IInterface) if iface.extends(IInterface)] results.sort(key=lambda x: x[1].interface.getName()) return results
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/typemodule/type.py
type.py
from zope.testing.cleanup import addCleanUp __docformat__ = 'restructuredtext' import zope.component from zope.i18nmessageid import ZopeMessageFactory as _ from zope.interface import implementer from zope.app.apidoc.classregistry import safe_import from zope.app.apidoc.codemodule.interfaces import IAPIDocRootModule from zope.app.apidoc.codemodule.module import Module from zope.app.apidoc.interfaces import IDocumentationModule @implementer(IDocumentationModule) class CodeModule(Module): """Represent the code browser documentation root""" #: The title. title = _('Code Browser') #: The description. description = _(""" This module allows you to get an overview of the modules and classes defined in the Zope 3 framework and its supporting packages. There are two methods to navigate through the modules to find the classes you are interested in. The first method is to type in some part of the Python path of the class and the module will look in the class registry for matches. The menu will then return with a list of these matches. The second method is to click on the "Browse Zope Source" link. In the main window, you will see a directory listing with the root Zope 3 modules. You can click on the module names to discover their content. If a class is found, it is represented as a bold entry in the list. The documentation contents of a class provides you with an incredible amount of information. Not only does it tell you about its base classes, implemented interfaces, attributes and methods, but it also lists the interface that requires a method or attribute to be implemented and the permissions required to access it. """) def __init__(self): """Initialize object.""" super().__init__(None, '', None, False) self.__isSetup = False def setup(self): """Setup module and class tree.""" if self.__isSetup: return self.__isSetup = True self._children = {} for name, mod in zope.component.getUtilitiesFor(IAPIDocRootModule): module = safe_import(mod) if module is not None: self._children[name] = Module(self, name, module) # And the builtins are always available, since that's the # most common root module linked to from docs. builtin_module = safe_import('builtins') assert builtin_module is not None builtin_module = Module(self, builtin_module.__name__, builtin_module) self._children['builtins'] = builtin_module def withParentAndName(self, parent, name): located = type(self)() located.__parent__ = parent located.__name__ = name self.setup() located._children = {name: module.withParentAndName(located, name) for name, module in self._children.items()} located.__isSetup = True return located def getDocString(self): return _('Zope 3 root.') def getFileName(self): return '' def getPath(self): return '' def isPackage(self): return True def get(self, key, default=None): self.setup() return super().get(key, default) def items(self): self.setup() return super().items() def _cleanUp(): from zope.component import getGlobalSiteManager code = getGlobalSiteManager().queryUtility( IDocumentationModule, name='Code') if code is not None: code.__init__() addCleanUp(_cleanUp)
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/codemodule.py
codemodule.py
"""ZCML File Representation """ __docformat__ = "reStructuredText" import copy from xml.sax import make_parser from xml.sax.handler import feature_namespaces from xml.sax.xmlreader import InputSource import zope.app.appsetup.appsetup from zope.cachedescriptors.property import Lazy from zope.configuration import config from zope.configuration import xmlconfig from zope.interface import directlyProvides from zope.interface import implementer from zope.location.interfaces import ILocation from zope.app.apidoc.codemodule.interfaces import IDirective from zope.app.apidoc.codemodule.interfaces import IRootDirective from zope.app.apidoc.codemodule.interfaces import IZCMLFile class MyConfigHandler(xmlconfig.ConfigurationHandler): """Special configuration handler to generate an XML tree.""" def __init__(self, context): super().__init__(context) self.rootElement = self.currentElement = None self.prefixes = {} def startPrefixMapping(self, prefix, uri): self.prefixes[uri] = prefix def evaluateCondition(self, expression): # We always want to process/show all ZCML directives. # The exception needs to be `installed` that evaluates to False; # if we can't load the package, we can't process the file arguments = expression.split(None) verb = arguments.pop(0) if verb in ('installed', 'not-installed'): return super().evaluateCondition(expression) return True def startElementNS(self, name, qname, attrs): # The last stack item is parent of the stack item that we are about to # create stackitem = self.context.stack[-1] super().startElementNS(name, qname, attrs) # Get the parser info from the correct context info = self.context.stack[-1].context.info # complex stack items behave a bit different than the other ones, so # we need to handle it separately if isinstance(stackitem, config.ComplexStackItem): schema = stackitem.meta.get(name[1])[0] else: schema = stackitem.context.factory(stackitem.context, name).schema # Now we have all the necessary information to create the directive element = Directive(name, schema, attrs, stackitem.context, info, self.prefixes) # Now we place the directive into the XML directive tree. if self.rootElement is None: self.rootElement = element else: self.currentElement.subs.append(element) element.__parent__ = self.currentElement self.currentElement = element def endElementNS(self, name, qname): super().endElementNS(name, qname) self.currentElement = self.currentElement.__parent__ @implementer(IDirective) class Directive: """Representation of a ZCML directive.""" def __init__(self, name, schema, attrs, context, info, prefixes): self.name = name self.schema = schema self.attrs = attrs self.context = context self.info = info self.__parent__ = None self.subs = [] self.prefixes = prefixes def __repr__(self): return '<Directive %s>' % str(self.name) @implementer(ILocation, IZCMLFile) class ZCMLFile: """Representation of an entire ZCML file.""" def __init__(self, filename, package, parent, name): # Retrieve the directive registry self.filename = filename self.package = package self.__parent__ = parent self.__name__ = name def withParentAndName(self, parent, name): located = type(self)(self.filename, self.package, parent, name) # We don't copy the root element; let it parse again if needed, instead # of trying to recurse through all the children and copy them. return located @Lazy def rootElement(self): # Get the context that was originally generated during startup and # create a new context using its registrations real_context = zope.app.appsetup.appsetup.getConfigContext() context = config.ConfigurationMachine() context._registry = copy.copy(real_context._registry) context._features = copy.copy(real_context._features) context.package = self.package # Shut up i18n domain complaints context.i18n_domain = 'zope' # Since we want to use a custom configuration handler, we need to # instantiate the parser object ourselves parser = make_parser() handler = MyConfigHandler(context) parser.setContentHandler(handler) parser.setFeature(feature_namespaces, True) # Now open the file file = open(self.filename) src = InputSource(getattr(file, 'name', '<string>')) src.setByteStream(file) # and parse it parser.parse(src) # Finally we retrieve the root element, have it provide a special root # directive interface and give it a location, so that we can do local # lookups. root = handler.rootElement directlyProvides(root, IRootDirective) root.__parent__ = self return root
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/zcml.py
zcml.py
__docformat__ = "reStructuredText" import zope.interface import zope.schema from zope.container.interfaces import IReadContainer from zope.i18nmessageid import ZopeMessageFactory as _ class IAPIDocRootModule(zope.interface.Interface): """Marker interface for utilities that represent class browser root modules. The utilities will be simple strings, representing the modules Python dotted name. """ class IModuleDocumentation(IReadContainer): """Representation of a Python module for documentation. The items of the container are sub-modules and classes. """ def getDocString(): """Return the doc string of the module.""" def getFileName(): """Return the file name of the module.""" def getPath(): """Return the Python path of the module.""" def isPackage(): """Return true if this module is a Python package.""" def getDeclaration(): """Return the interfaces provided by the module. The returned value provides zope.interface.interfaces.IDeclaration. To get the list of interfaces, iterate over the returned value. The list will be empty if the module does not provide any interfaces. """ class IClassDocumentation(zope.interface.Interface): """Representation of a class or type for documentation.""" def getDocString(): """Return the doc string of the class.""" def getPath(): """Return the Python path of the class.""" def getBases(): """Return the base classes of the class.""" def getKnownSubclasses(): """Return the known subclasses classes of the class.""" def getInterfaces(): """Return the interfaces the class implements.""" def getAttributes(): """Return a list of 3-tuple attribute information. The first entry of the 3-tuple is the name of the attribute, the second is the attribute object itself. The third entry is the interface in which the attribute is defined. Note that only public attributes are returned, meaning only attributes that do not start with an '_'-character. """ def getMethods(): """Return a list of 3-tuple method information. The first entry of the 3-tuple is the name of the method, the second is the method object itself. The third entry is the interface in which the method is defined. Note that only public methods are returned, meaning only methods that do not start with an '_'-character. """ def getMethodDescriptors(): """Return a list of 3-tuple method descriptor information. The first entry of the 3-tuple is the name of the method, the second is the method descriptor object itself. The third entry is the interface in which the method is defined. Note that only public methods are returned, meaning only method descriptors that do not start with an '_'-character. """ def getSecurityChecker(): """Return the security checker for this class. Since 99% of the time we are dealing with name-based security checkers, we can look up the get/set permission required for a particular class attribute/method. """ def getConstructor(): """Return the __init__ method, or None if there isn't one.""" class IFunctionDocumentation(zope.interface.Interface): """Representation of a function for documentation.""" def getDocString(): """Return the doc string of the function.""" def getPath(): """Return the Python path of the function.""" def getSignature(): """Return the signature of the function as a string.""" def getAttributes(): """Return a list of 2-tuple attribute information. The first entry of the 2-tuple is the name of the attribute, the second is the attribute object itself. """ class IDirective(zope.interface.Interface): """Representation of a directive in IZCMLFile.""" name = zope.schema.Tuple( title='Name', description='Name of the directive in the form (Namespace. Name)', required=True) schema = zope.schema.Field( title='Schema', description='Schema describing the directive attributes', required=True) attrs = zope.schema.Field( title='Attributes', description="SAX parser representation of the directive's attributes", required=True) context = zope.schema.Field( title='Configuration Context', description='Configuration context while the directive was parsed.', required=True) prefixes = zope.schema.Dict( title='Prefixes', description='Mapping from namespace URIs to prefixes.', required=True) info = zope.schema.Field( title='Info', description='ParserInfo objects containing line and column info.', required=True) __parent__ = zope.schema.Field( title='Parent', description='Parent Directive', required=True) subs = zope.schema.List( title='Sub-Directives', description='List of sub-directives', required=True) class IRootDirective(IDirective): """Marker interface""" class IZCMLFile(zope.interface.Interface): """ZCML File Object This is the main object that will manage the configuration of one particular ZCML configuration file. """ filename = zope.schema.BytesLine( title=_('Configuration Filename'), description=_('Path to the configuration file'), required=True) package = zope.schema.BytesLine( title=_('Configuration Package'), description=_( '''Specifies the package from which the configuration file will be executed. If you do not specify the package, then the configuration cannot be fully validated and improper ZCML files might be written.''' ), required=False) rootElement = zope.schema.Field( title=_("XML Root Element"), description=_("XML element representing the configuration root."), required=True) class ITextFile(zope.interface.Interface): """Text file object""" path = zope.schema.BytesLine( title=_('Path'), description=_('Path to the text file'), required=True) def getContent(): """Return the content of the text file, in unicode"""
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/interfaces.py
interfaces.py
========================================== Code Module specific `apidoc` Directives ========================================== The ``apidoc:rootModule`` Directive =================================== The ``rootModule`` directive allows you to register a third party Python package with apidoc's code browser. Before we can register a new root module, we need to load the metaconfiguration: >>> from zope.configuration import xmlconfig >>> import zope.app.apidoc.codemodule >>> context = xmlconfig.file('meta.zcml', zope.app.apidoc.codemodule) Now we can run the directive. First, let's make sure that no root modules have been registered yet: >>> from zope.component import getUtilitiesFor >>> from zope.app.apidoc.codemodule.interfaces import IAPIDocRootModule >>> list(getUtilitiesFor(IAPIDocRootModule)) [] Now run the registration code: >>> context = xmlconfig.string(''' ... <configure ... xmlns="http://namespaces.zope.org/apidoc"> ... <rootModule module="zope" /> ... </configure>''', context) and the root module is available: >>> list(getUtilitiesFor(IAPIDocRootModule)) [('zope', 'zope')] The ``apidoc:importModule`` Directive ===================================== The ``importModule`` directive allows you to set the ``__import_unknown_modules__`` flag of the class registry. When this flag is set to false, paths will only be looked up in :data:`sys.modules`. When set true, and the :data:`sys.modules` lookup fails, the import function of the class registry tries to import the path. The hook was provided for security reasons, since uncontrolled importing of modules in a running application is considered a security hole. By default the flag is set to false (of course, this depends on the order in which tests are run and what ZCML has been configured or if this was manually changed, so we can't really rely on the default here): >>> from zope.app.apidoc import classregistry >>> classregistry.__import_unknown_modules__ = False We can now use the directive to set it to true: >>> context = xmlconfig.string(''' ... <configure ... xmlns="http://namespaces.zope.org/apidoc"> ... <moduleImport allow="true" /> ... </configure>''', context) >>> classregistry.__import_unknown_modules__ True We can also set it back to false of course: >>> context = xmlconfig.string(''' ... <configure ... xmlns="http://namespaces.zope.org/apidoc"> ... <moduleImport allow="false" /> ... </configure>''', context) >>> classregistry.__import_unknown_modules__ False
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/directives.rst
directives.rst
__docformat__ = 'restructuredtext' from inspect import isfunction from inspect import ismethoddescriptor from zope.interface import implementedBy from zope.interface import implementer from zope.location.interfaces import ILocation from zope.security.checker import getCheckerForInstancesOf from zope.app.apidoc.classregistry import classRegistry from zope.app.apidoc.codemodule.interfaces import IClassDocumentation from zope.app.apidoc.utilities import getInterfaceForAttribute from zope.app.apidoc.utilities import getPublicAttributes @implementer(ILocation, IClassDocumentation) class Class: """This class represents a class declared in the module.""" def __init__(self, module, name, klass): self.__parent__ = module self.__name__ = name self.__klass = klass # Setup interfaces that are implemented by this class. self.__interfaces = tuple(implementedBy(klass)) self.__all_ifaces = tuple(implementedBy(klass).flattened()) # Register the class with the global class registry. classRegistry[self.getPath()] = klass def getPath(self): """See :class:`~zope.app.apidoc.codemodule.interfaces.IClassDocumentation`.""" # noqa: E501 line too long return self.__parent__.getPath() + '.' + self.__name__ def getDocString(self): """See :class:`~zope.app.apidoc.codemodule.interfaces.IClassDocumentation`.""" # noqa: E501 line too long return self.__klass.__doc__ def getBases(self): """See :class:`~zope.app.apidoc.codemodule.interfaces.IClassDocumentation`.""" # noqa: E501 line too long return self.__klass.__bases__ def getKnownSubclasses(self): """See :class:`~zope.app.apidoc.codemodule.interfaces.IClassDocumentation`.""" # noqa: E501 line too long return [k for n, k in classRegistry.getSubclassesOf(self.__klass)] def getInterfaces(self): """See :class:`~zope.app.apidoc.codemodule.interfaces.IClassDocumentation`.""" # noqa: E501 line too long return self.__interfaces def _iterAllAttributes(self): for name in getPublicAttributes(self.__klass): iface = getInterfaceForAttribute( name, self.__all_ifaces, asPath=False) yield name, getattr(self.__klass, name), iface def getAttributes(self): """See :class:`~zope.app.apidoc.codemodule.interfaces.IClassDocumentation`.""" # noqa: E501 line too long return [(name, obj, iface) for name, obj, iface in self._iterAllAttributes() if not isfunction(obj) and not ismethoddescriptor(obj)] def getMethods(self): """See :class:`~zope.app.apidoc.codemodule.interfaces.IClassDocumentation`.""" # noqa: E501 line too long return [(name, obj, iface) for name, obj, iface in self._iterAllAttributes() if isfunction(obj)] def getMethodDescriptors(self): return [(name, obj, iface) for name, obj, iface in self._iterAllAttributes() if ismethoddescriptor(obj)] def getSecurityChecker(self): """See :class:`~zope.app.apidoc.codemodule.interfaces.IClassDocumentation`.""" # noqa: E501 line too long return getCheckerForInstancesOf(self.__klass) def getConstructor(self): """See :class:`~zope.app.apidoc.codemodule.interfaces.IClassDocumentation`.""" # noqa: E501 line too long init = getattr(self.__klass, '__init__', None) if callable(init): return init
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/class_.py
class_.py
__docformat__ = 'restructuredtext' import os import types from zope.cachedescriptors.property import Lazy from zope.hookable import hookable from zope.interface import implementer from zope.interface import providedBy from zope.interface.interface import InterfaceClass from zope.location import LocationProxy from zope.location.interfaces import ILocation from zope.proxy import getProxiedObject import zope from zope.app.apidoc.classregistry import safe_import from zope.app.apidoc.codemodule.class_ import Class from zope.app.apidoc.codemodule.function import Function from zope.app.apidoc.codemodule.interfaces import IModuleDocumentation from zope.app.apidoc.codemodule.text import TextFile from zope.app.apidoc.codemodule.zcml import ZCMLFile from zope.app.apidoc.utilities import ReadContainerBase # Ignore these files, since they are not necessary or cannot be imported # correctly. IGNORE_FILES = frozenset(( 'tests', 'tests.py', 'ftests', 'ftests.py', 'CVS', '.svn', '.git', 'gadfly', 'setup.py', 'introspection.py', 'Mount.py', '__main__.py', )) @implementer(ILocation, IModuleDocumentation) class Module(ReadContainerBase): """This class represents a Python module.""" _package = False _children = None def __init__(self, parent, name, module, setup=True): """Initialize object.""" self.__parent__ = parent self.__name__ = name self._module = module self._children = {} if setup: self.__setup() def __setup_package(self): # Detect packages # __file__ can be None, especially with namespace packages on # Python 3.7 module_file = getattr(self._module, '__file__', None) or '' module_path = getattr(self._module, '__path__', None) if module_file.endswith( ('__init__.py', '__init__.pyc', '__init__.pyo')): self._package = True else: # Detect namespace packages with implicit namespace packages: # "When the module is a package, its # __package__ value should be set to its __name__. When # the module is not a package, __package__ should be set # to the empty string for top-level modules, or for # submodules, to the parent package's " pkg_name = self._module.__package__ self._package = pkg_name and self._module.__name__ == pkg_name if not self._package: return for mod_dir in module_path: # TODO: If we are dealing with eggs, we will not have a # directory right away. For now we just ignore zipped eggs; # later we want to unzip it. if not os.path.isdir(mod_dir): continue for mod_file in os.listdir(mod_dir): if mod_file in IGNORE_FILES or mod_file in self._children: continue path = os.path.join(mod_dir, mod_file) if os.path.isdir(path) and '__init__.py' in os.listdir(path): # subpackage # XXX Implicit packages don't have __init__.py fullname = self._module.__name__ + '.' + mod_file module = safe_import(fullname) if module is not None: self._children[mod_file] = Module( self, mod_file, module) elif os.path.isfile(path): if mod_file.endswith( '.py') and not mod_file.startswith('__init__'): # module name = mod_file[:-3] fullname = self._module.__name__ + '.' + name module = safe_import(fullname) if module is not None: self._children[name] = Module(self, name, module) elif mod_file.endswith('.zcml'): self._children[mod_file] = ZCMLFile(path, self._module, self, mod_file) elif mod_file.endswith(('.txt', '.rst')): self._children[mod_file] = TextFile( path, mod_file, self) def __setup_classes_and_functions(self): # List the classes and functions in module, if any are available. module_decl = self.getDeclaration() ifaces = list(module_decl) if ifaces: # The module has an interface declaration. Yay! names = set() for iface in ifaces: names.update(iface.names()) else: names = getattr(self._module, '__all__', None) if names is None: # The module doesn't declare its interface. Boo! # Guess what names to document, avoiding aliases and names # imported from other modules. names = set() for name, attr in self._module.__dict__.items(): if isinstance(attr, hookable): attr = attr.implementation attr_module = getattr(attr, '__module__', None) if attr_module != self._module.__name__: continue if getattr(attr, '__name__', None) != name: continue names.add(name) # If there is something the same name beneath, then module should # have priority. names = set(names) - set(self._children) for name in names: attr = getattr(self._module, name, None) if attr is None: continue if isinstance(attr, hookable): attr = attr.implementation if isinstance(attr, type): self._children[name] = Class(self, name, attr) elif isinstance(attr, InterfaceClass): self._children[name] = LocationProxy(attr, self, name) elif isinstance(attr, types.FunctionType): doc = attr.__doc__ if not doc: f = module_decl.get(name) doc = getattr(f, '__doc__', None) self._children[name] = Function(self, name, attr, doc=doc) def __setup(self): """Setup the module sub-tree.""" self.__setup_package() zope.deprecation.__show__.off() try: self.__setup_classes_and_functions() finally: zope.deprecation.__show__.on() def withParentAndName(self, parent, name): located = _LazyModule(self, parent, name, self._module) # Our module tree can be very large, but typically during any one # traversal we're only going to need one specific branch. So # initializing it lazily the first time one specific level's _children # is accessed has a *major* performance benefit. # A plain @Lazy attribute won't work since we need to copy from self; # we use a subclass, with the provisio that it can be the *only* # subclass return located def getDocString(self): """See IModuleDocumentation.""" return self._module.__doc__ def getFileName(self): """See IModuleDocumentation.""" return self._module.__file__ def getPath(self): """See IModuleDocumentation.""" return self._module.__name__ def isPackage(self): """See IModuleDocumentation.""" return self._package def getDeclaration(self): """See IModuleDocumentation.""" return providedBy(self._module) def get(self, key, default=None): """See zope.container.interfaces.IReadContainer.""" obj = self._children.get(key, default) if obj is not default: return obj if self.getPath(): # Look for a nested module we didn't previously discover. # Note that when path is empty, that means we are the global # module (CodeModule) and if we get here, we're asking to find # a module outside of the registered root modules. We don't # look for those things. # A common case for this to come up is 'menus' for the 'zope.app' # module. The 'menus' module is dynamically generated through ZCML. path = self.getPath() + '.' + key obj = safe_import(path) if obj is not None: self._children[key] = child = Module(self, key, obj) # Caching this in _children may be pointless, we were # most likely a copy using withParentAndName in the # first place. return child # Maybe it is a simple attribute of the module obj = getattr(self._module, key, default) if obj is not default: obj = LocationProxy(obj, self, key) return obj def items(self): """See zope.container.interfaces.IReadContainer.""" # Only publicize public objects, even though we do keep track of # private ones return [(name, value) for name, value in self._children.items() if not name.startswith('_')] def __repr__(self): return '<Module {!r} name {!r} parent {!r} at 0x{:x}>'.format( self._module, self.__name__, self.__parent__, id(self) ) class _LazyModule(Module): copy_from = None def __init__(self, copy_from, parent, name, module): Module.__init__(self, parent, name, module, False) del self._children # get our @Lazy back self._copy_from = copy_from @Lazy def _children(self): new_children = {} for x in self._copy_from._children.values(): try: new_child = x.withParentAndName(self, x.__name__) except AttributeError: if isinstance(x, LocationProxy): new_child = LocationProxy( getProxiedObject(x), self, x.__name__) else: new_child = LocationProxy(x, self, x.__name__) new_children[x.__name__] = new_child return new_children
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/module.py
module.py
====================================== Code Browser Presentation Components ====================================== .. currentmodule:: zope.app.apidoc.codemodule.browser This document describes the API of the views complementing the various code browser documentation components. The views can be found in >>> from zope.app.apidoc.codemodule import browser We will also need the code browser documentation module: >>> cm = apidoc.get('Code') The ``zope`` package is already registered and available with the code module. Module Details ============== The module details are easily created, since we can just use the traversal process to get a module documentation object: >>> from zope.traversing.api import traverse >>> _context = traverse(cm, 'zope/app/apidoc/codemodule/codemodule') >>> from zope.publisher.browser import TestRequest >>> details = browser.module.ModuleDetails(_context, TestRequest()) :meth:`module.ModuleDetails.getDoc` ----------------------------------- Get the doc string of the module formatted in STX or ReST. >>> print(details.getDoc().strip()) <p>Code Documentation Module</p> <p>This module is able to take a dotted name of any class and display documentation for it.</p> Module data ----------- Return info objects for all classes in this module. >>> from pprint import pprint >>> pprint(details.getClasses()) [{'doc': 'Represent the code browser documentation root', 'name': 'CodeModule', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app/apidoc/codemodule/codemodule/CodeModule'}] This module doesn't contain anything else. >>> pprint(details.getInterfaces()) [] >>> pprint(details.getModules()) [] >>> pprint(details.getModuleInterfaces()) [] >>> pprint(details.getTextFiles()) [] >>> pprint(details.getZCMLFiles()) [] >>> pprint(details.getFunctions()) [] :func:`utilities.getBreadCrumbs` -------------------------------- Create breadcrumbs for the module path. We cannot reuse the the system's bread crumbs, since they go all the way up to the root, but we just want to go to the root module. >>> from zope.app.apidoc.codemodule.browser import utilities >>> bc = utilities.CodeBreadCrumbs() >>> bc.context = details.context >>> bc.request = details.request >>> pprint(bc(), width=1) [{'name': '[top]', 'url': 'http://127.0.0.1/++apidoc++/Code'}, {'name': 'zope', 'url': 'http://127.0.0.1/++apidoc++/Code/zope'}, {'name': 'app', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app'}, {'name': 'apidoc', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app/apidoc'}, {'name': 'codemodule', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app/apidoc/codemodule'}, {'name': 'codemodule', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app/apidoc/codemodule/codemodule'}] Module Details With Interfaces ------------------------------ Let's also look at a module that defines interfaces: >>> _context = traverse(cm, 'zope/app/apidoc/interfaces') >>> details = browser.module.ModuleDetails(_context, TestRequest()) >>> pprint(details.getInterfaces()) [{'doc': 'Zope 3 API Documentation Module', 'name': 'IDocumentationModule', 'path': 'zope.app.apidoc.interfaces.IDocumentationModule', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app/apidoc/interfaces/IDocumentationModule'}] Module Details With Implementation ---------------------------------- Let's also look at a module that implements an interface itself: >>> _context = traverse(cm, 'zope/lifecycleevent') >>> details = browser.module.ModuleDetails(_context, TestRequest()) >>> pprint(details.getModuleInterfaces()) [{'name': 'IZopeLifecycleEvent', 'path': 'zope.lifecycleevent.interfaces.IZopeLifecycleEvent'}] Class Details ============= The class details are easily created, since we can just use the traversal process to get a class documentation object: >>> details = browser.class_.ClassDetails() >>> details.context = traverse( ... cm, 'zope/app/apidoc/codemodule/codemodule/CodeModule') >>> details.request = TestRequest() Now that we have the details class we can just access the various methods: :meth:`class_.ClassDetails.getBases` ------------------------------------ Get all bases of this class. >>> pprint(details.getBases()) [{'path': 'zope.app.apidoc.codemodule.module.Module', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app/apidoc/codemodule/module/Module'}] :meth:`class_.ClassDetails.getKnownSubclasses` ---------------------------------------------- Get all known subclasses of this class. >>> details.getKnownSubclasses() [] :meth:`class_.ClassDetails._listClasses` ---------------------------------------- Prepare a list of classes for presentation. >>> import zope.app.apidoc.apidoc >>> import zope.app.apidoc.codemodule.codemodule >>> pprint(details._listClasses([ ... zope.app.apidoc.apidoc.APIDocumentation, ... zope.app.apidoc.codemodule.codemodule.Module])) [{'path': 'zope.app.apidoc.apidoc.APIDocumentation', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app/apidoc/apidoc/APIDocumentation'}, {'path': 'zope.app.apidoc.codemodule.module.Module', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app/apidoc/codemodule/module/Module'}] :meth:`class_.ClassDetails.getBaseURL` -------------------------------------- Return the URL for the API Documentation Tool. Note that the following output is a bit different than usual, since we have not setup all path elements. >>> details.getBaseURL() 'http://127.0.0.1/++apidoc++' :meth:`class_.ClassDetails.getInterfaces` ----------------------------------------- Get all implemented interfaces (as paths) of this class. >>> pprint(details.getInterfaces()) [{'path': 'zope.app.apidoc.interfaces.IDocumentationModule', 'url': 'zope.app.apidoc.interfaces.IDocumentationModule'}, {'path': 'zope.location.interfaces.ILocation', 'url': 'zope.location.interfaces.ILocation'}, {'path': 'zope.app.apidoc.codemodule.interfaces.IModuleDocumentation', 'url': 'zope.app.apidoc.codemodule.interfaces.IModuleDocumentation'}, {'path': 'zope.container.interfaces.IReadContainer', 'url': 'zope.container.interfaces.IReadContainer'}] :meth:`class_.ClassDetails.getConstructor` ------------------------------------------ Get info about the class' __init__ method, which is its constructor. >>> pprint(details.getConstructor()) {'doc': '<p>Initialize object.</p>\n', 'signature': '()'} :meth:`class_.ClassDetails.getAttributes` ----------------------------------------- Get all attributes of this class. >>> pprint(details.getAttributes()[1]) {'interface': {'path': 'zope.app.apidoc.interfaces.IDocumentationModule', 'url': 'zope.app.apidoc.interfaces.IDocumentationModule'}, 'name': 'title', 'read_perm': 'zope.Public', 'type': 'Message', 'type_link': 'zope/i18nmessageid/message/Message', 'value': "'Code Browser'", 'write_perm': 'n/a'} :meth:`class_.ClassDetails.getMethods` -------------------------------------- Get all methods of this class. >>> pprint(details.getMethods()[-3:-1]) [{'doc': '<p>Setup module and class tree.</p>\n', 'interface': None, 'name': 'setup', 'read_perm': 'n/a', 'signature': '()', 'write_perm': 'n/a'}, {'doc': '', 'interface': {'path': 'zope.interface.common.mapping.IEnumerableMapping', 'url': 'zope.interface.common.mapping.IEnumerableMapping'}, 'name': 'values', 'read_perm': 'zope.Public', 'signature': '()', 'write_perm': 'n/a'}] :meth:`class_.ClassDetails.getDoc` ---------------------------------- Get the doc string of the class STX formatted. >>> print(details.getDoc()[:-1]) <p>Represent the code browser documentation root</p> Function Details ================ This is the same deal as before, use the path to generate the function documentation component: >>> details = browser.function.FunctionDetails() >>> details.context = traverse(cm, ... 'zope/app/apidoc/codemodule/browser/tests/foo') >>> details.request = TestRequest() Here are the methods: :meth:`function.FunctionDetails.getDocString` --------------------------------------------- Get the doc string of the function in a rendered format. >>> details.getDocString() '<p>This is the foo function.</p>\n' :meth:`function.FunctionDetails.getAttributes` ---------------------------------------------- Get all attributes of this function. >>> attr = details.getAttributes()[0] >>> pprint(attr) {'name': 'deprecated', 'type': 'bool', 'type_link': 'builtins/bool', 'value': 'True'} :meth:`function.FunctionDetails.getBaseURL` ------------------------------------------- Return the URL for the API Documentation Tool. >>> details.getBaseURL() 'http://127.0.0.1/++apidoc++' Text File Details ================= This is the same deal as before, use the path to generate the :class:`text file documentation component <text.TextFileDetails>`: >>> details = browser.text.TextFileDetails() >>> details.context = traverse(cm, ... 'zope/app/apidoc/codemodule/README.rst') >>> details.request = TestRequest() Here are the methods: :meth:`text.TextFileDetails.renderedContent` -------------------------------------------- Render the file content to HTML. >>> print(details.renderedContent()[:48]) <h1 class="title">Code Documentation Module</h1> ZCML File and Directive Details =============================== The ZCML :class:`file details <zcml.DirectiveDetails>` are a bit different, since there is no view class for ZCML files, just a template. The template then uses the directive details to provide all the view content: >>> details = browser.zcml.DirectiveDetails() >>> zcml = traverse(cm, 'zope/app/apidoc/codemodule/configure.zcml') >>> details.context = zcml.rootElement >>> details.request = TestRequest() >>> details.__parent__ = details.context Here are the methods for the directive details: :meth:`zcml.DirectiveDetails.fullTagName` ----------------------------------------- Return the name of the directive, including prefix, if applicable. >>> details.fullTagName() 'configure' :meth:`zcml.DirectiveDetails.line` ---------------------------------- Return the line (as a string) at which this directive starts. >>> details.line() '1' :meth:`zcml.DirectiveDetails.highlight` --------------------------------------- It is possible to highlight a directive by passing the `line` variable as a request variable. If the value of `line` matches the output of `line()`, this method returns 'highlight' and otherwise ''. 'highlight' is a CSS class that places a colored box around the directive. >>> details.highlight() '' >>> details.request = TestRequest(line='1') >>> details.highlight() 'highlight' :meth:`zcml.DirectiveDetails.url` --------------------------------- Returns the URL of the directive docuemntation in the ZCML documentation module. >>> details.url() 'http://127.0.0.1/++apidoc++/ZCML/ALL/configure/index.html' :meth:`zcml.DirectiveDetails.objectURL` --------------------------------------- This method converts the string value of the field to an object and then crafts a documentation URL for it: >>> from zope.configuration.fields import GlobalObject >>> field = GlobalObject() >>> details.objectURL('.interfaces.IZCMLFile', field, '') 'http://127.0.0.1/++apidoc++/Interface/zope.app.apidoc.codemodule.interfaces.IZCMLFile/index.html' >>> details.objectURL('.zcml.ZCMLFile', field, '') '/zope/app/apidoc/codemodule/zcml/ZCMLFile/index.html' :meth:`zcml.DirectiveDetails.attributes` ---------------------------------------- Returns a list of info dictionaries representing all the attributes in the directive. If the directive is the root directive, all namespace declarations will be listed too. >>> pprint(details.attributes()) [{'name': 'xmlns', 'url': None, 'value': 'http://namespaces.zope.org/zope', 'values': []}, {'name': 'xmlns:apidoc', 'url': None, 'value': 'http://namespaces.zope.org/apidoc', 'values': []}, {'name': 'xmlns:browser', 'url': None, 'value': 'http://namespaces.zope.org/browser', 'values': []}] >>> details.context = details.context.subs[0] >>> pprint(details.attributes()) [{'name': 'class', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app/apidoc/codemodule/module/Module/index.html', 'value': '.module.Module', 'values': []}] :meth:`zcml.DirectiveDetails.hasSubDirectives` ---------------------------------------------- Returns `True`, if the directive has subdirectives; otherwise `False` is returned. >>> details.hasSubDirectives() True :meth:`zcml.DirectiveDetails.getElements` ----------------------------------------- Returns a list of all sub-directives: >>> details.getElements() [<Directive ('http://namespaces.zope.org/zope', 'allow')>] Other Examples -------------- Let's look at sub-directive that has a namespace: >>> details = browser.zcml.DirectiveDetails() >>> zcml = traverse(cm, 'zope/app/apidoc/ftesting-base.zcml') >>> browser_directive = [x for x in zcml.rootElement.subs if x.name[0].endswith('browser')][0] >>> details.context = browser_directive >>> details.request = TestRequest() >>> details.fullTagName() 'browser:menu' The exact URL will vary depending on what ZCML has been loaded. >>> details.url() 'http://127.0.0.1/++apidoc++/.../menu/index.html' Now one that has some tokens: >>> details = browser.zcml.DirectiveDetails() >>> zcml = traverse(cm, 'zope/app/apidoc/enabled.zcml') >>> adapter_directive = [x for x in zcml.rootElement.subs if x.name[1] == 'adapter'][0] >>> details.context = adapter_directive >>> details.__parent__ = details.context >>> details.request = TestRequest() >>> pprint(details.attributes()) [{'name': 'factory', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/app/apidoc/apidoc/apidocNamespace/index.html', 'value': '.apidoc.apidocNamespace', 'values': []}, {'name': 'provides', 'url': 'http://127.0.0.1/++apidoc++/Interface/zope.traversing.interfaces.ITraversable/index.html', 'value': 'zope.traversing.interfaces.ITraversable', 'values': []}, {'name': 'for', 'url': None, 'value': '*', 'values': []}, {'name': 'name', 'url': None, 'value': 'apidoc', 'values': []}] Now one with *multiple* tokens: >>> details = browser.zcml.DirectiveDetails() >>> zcml = traverse(cm, 'zope/traversing/configure.zcml') >>> adapter_directive = [x for x in zcml.rootElement.subs if x.name[1] == 'adapter'] >>> adapter_directive = [x for x in adapter_directive if ' ' in x.attrs[(None, 'for')]][0] >>> details.context = adapter_directive >>> details.__parent__ = details.context >>> details.request = TestRequest() >>> pprint(details.attributes()) [{'name': 'factory', 'url': 'http://127.0.0.1/++apidoc++/Code/zope/traversing/namespace/etc/index.html', 'value': 'zope.traversing.namespace.etc', 'values': []}, {'name': 'provides', 'url': 'http://127.0.0.1/++apidoc++/Interface/zope.traversing.interfaces.ITraversable/index.html', 'value': 'zope.traversing.interfaces.ITraversable', 'values': []}, {'name': 'for', 'url': None, 'value': '* zope.publisher.interfaces.IRequest', 'values': [{'url': None, 'value': '*'}, {'url': 'http://127.0.0.1/++apidoc++/Interface/zope.publisher.interfaces.IRequest/index.html', 'value': 'zope.publisher.interfaces.IRequest'}]}, {'name': 'name', 'url': None, 'value': 'etc', 'values': []}] And now one that is subdirectives: >>> details = browser.zcml.DirectiveDetails() >>> zcml = traverse(cm, 'zope/app/apidoc/browser/configure.zcml') >>> adapter_directive = [x for x in zcml.rootElement.subs if x.name[1] == 'pages'][0] >>> details.context = adapter_directive.subs[0] >>> details.__parent__ = details.context >>> details.request = TestRequest() >>> details.url() 'http://127.0.0.1/++apidoc++/.../pages/index.html#page' The Introspector ================ There are several tools that are used to support the :mod:`introspector`. >>> from zope.app.apidoc.codemodule.browser import introspector .. currentmodule:: zope.app.apidoc.codemodule.browser.introspector :func:`getTypeLink` ------------------- This little helper function returns the path to the type class: >>> from zope.app.apidoc.apidoc import APIDocumentation >>> introspector.getTypeLink(APIDocumentation) 'zope/app/apidoc/apidoc/APIDocumentation' >>> introspector.getTypeLink(dict) 'builtins/dict' >>> introspector.getTypeLink(type(None)) is None True ``++annotations++`` Namespace ----------------------------- This :func:`namespace <annotationsNamespace>` is used to traverse into the annotations of an object. >>> import zope.interface >>> from zope.annotation.interfaces import IAttributeAnnotatable >>> @zope.interface.implementer(IAttributeAnnotatable) ... class Sample(object): ... pass >>> sample = Sample() >>> sample.__annotations__ = {'zope.my.namespace': 'Hello there!'} >>> ns = introspector.annotationsNamespace(sample) >>> ns.traverse('zope.my.namespace', None) 'Hello there!' >>> ns.traverse('zope.my.unknown', None) Traceback (most recent call last): ... KeyError: 'zope.my.unknown' Mapping ``++items++`` namespace ------------------------------- This :func:`namespace <mappingItemsNamespace>` allows us to traverse the items of any mapping: >>> ns = introspector.mappingItemsNamespace({'mykey': 'myvalue'}) >>> ns.traverse('mykey', None) 'myvalue' >>> ns.traverse('unknown', None) Traceback (most recent call last): ... KeyError: 'unknown' Sequence ``++items++`` namespace -------------------------------- This :func:`namespace <sequenceItemsNamespace>` allows us to traverse the items of any sequence: >>> ns = introspector.sequenceItemsNamespace(['value1', 'value2']) >>> ns.traverse('0', None) 'value1' >>> ns.traverse('2', None) Traceback (most recent call last): ... IndexError: list index out of range >>> ns.traverse('text', None) Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: 'text' Introspector View ----------------- The main contents of the introspector view comes from the :class:`introspector view class <Introspector>`. In the following section we are going to demonstrate the methods used to collect the data. First we need to create an object though; let's use a root folder: >>> rootFolder <...Folder object at ...> Now we instantiate the view >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> inspect = introspector.Introspector(rootFolder, request) so that we can start looking at the methods. First we should note that the class documentation view is directly available: >>> inspect.klassView <zope.browserpage.simpleviewclass.SimpleViewClass from ...> >>> inspect.klassView.context <zope.app.apidoc.codemodule.class_.Class object at ...> You can get the parent of the inspected object, which is ``None`` for the root folder: >>> inspect.parent() is None True You can also get the base URL of the request: >>> inspect.getBaseURL() 'http://127.0.0.1/++apidoc++' Next you can get a list of all directly provided interfaces: >>> ifaces = inspect.getDirectlyProvidedInterfaces() >>> sorted(ifaces) ['zope.component.interfaces.ISite', 'zope.site.interfaces.IRootFolder'] The ``getProvidedInterfaces()`` and ``getBases()`` method simply forwards its request to the class documentation view. Thus the next method is ``getAttributes()``, which collects all sorts of useful information about the object's attributes: >>> pprint(list(inspect.getAttributes())) [{'interface': None, 'name': 'data', 'read_perm': 'n/a', 'type': 'OOBTree', 'type_link': 'BTrees/OOBTree/OOBTree', 'value': '<BTrees.OOBTree.OOBTree object at ...>', 'value_linkable': True, 'write_perm': 'n/a'}] Of course, the methods are listed as well: >>> pprint(list(inspect.getMethods())) [... {'doc': '', 'interface': 'zope.component.interfaces.IPossibleSite', 'name': 'getSiteManager', 'read_perm': 'zope.Public', 'signature': '()', 'write_perm': 'n/a'}, ... {'doc': '', 'interface': 'zope.container.interfaces.IBTreeContainer', 'name': 'keys', 'read_perm': 'zope.View', 'signature': '(key=None)', 'write_perm': 'n/a'}, {'doc': '', 'interface': 'zope.component.interfaces.IPossibleSite', 'name': 'setSiteManager', 'read_perm': 'zope.ManageServices', 'signature': '(sm)', 'write_perm': 'n/a'}, ...] The final methods deal with inspecting the objects data further. For exmaple, if we inspect a sequence, >>> from persistent.list import PersistentList >>> list = PersistentList(['one', 'two']) >>> from zope.interface.common.sequence import IExtendedReadSequence >>> zope.interface.directlyProvides(list, IExtendedReadSequence) >>> inspect2 = introspector.Introspector(list, request) we can first determine whether it really is a sequence >>> inspect2.isSequence() True and then get the sequence items: >>> pprint(inspect2.getSequenceItems()) [{'index': 0, 'value': "'one'", 'value_type': 'str', 'value_type_link': 'builtins/str'}, {'index': 1, 'value': "'two'", 'value_type': 'str', 'value_type_link': 'builtins/str'}] Similar functionality exists for a mapping. But we first have to add an item: >>> rootFolder['list'] = list Now let's have a look: >>> inspect.isMapping() True >>> pprint(inspect.getMappingItems()) [... {'key': 'list', 'key_string': "'list'", 'value': "['one', 'two']", 'value_type': 'ContainedProxy', 'value_type_link': 'zope/container/contained/ContainedProxy'}, ...] The final two methods doeal with the introspection of the annotations. If an object is annotatable, >>> inspect.isAnnotatable() True then we can get an annotation mapping: >>> rootFolder.__annotations__ = {'my.list': list} >>> pprint(inspect.getAnnotationsInfo()) [{'key': 'my.list', 'key_string': "'my.list'", 'value': "['one', 'two']", 'value_type': 'PersistentList', 'value_type_link': 'persistent/list/PersistentList'}] And that's it. Fur some browser-based demonstration see :doc:`codemodule_browser_introspector`.
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/browser/README.rst
README.rst
__docformat__ = "reStructuredText" from zope.configuration.fields import GlobalInterface from zope.configuration.fields import GlobalObject from zope.configuration.fields import Tokens from zope.interface.interfaces import IInterface from zope.schema import getFieldNamesInOrder from zope.security.proxy import isinstance from zope.security.proxy import removeSecurityProxy from zope.traversing.api import getParent from zope.traversing.browser import absoluteURL from zope.app.apidoc.browser.utilities import findAPIDocumentationRoot from zope.app.apidoc.browser.utilities import findAPIDocumentationRootURL from zope.app.apidoc.codemodule.interfaces import IRootDirective from zope.app.apidoc.interfaces import IDocumentationModule from zope.app.apidoc.utilities import getPythonPath from zope.app.apidoc.utilities import isReferencable from zope.app.apidoc.zcmlmodule import quoteNS def findDocModule(obj): if IDocumentationModule.providedBy(obj): return obj return findDocModule(getParent(obj)) def _compareAttrs(x, nameOrder): if x['name'] in nameOrder: valueX = nameOrder.index(x['name']) else: valueX = 999999 return valueX class DirectiveDetails: """Details about ZCML directives.""" context = None request = None def fullTagName(self): context = removeSecurityProxy(self.context) ns, name = context.name if context.prefixes.get(ns): return '{}:{}'.format(context.prefixes[ns], name) return name def line(self): return str(removeSecurityProxy(self.context).info.line) def highlight(self): if self.request.get('line') == self.line(): return 'highlight' return '' def url(self): directive = removeSecurityProxy(self.context) subDirective = None # Sub-directives are not directly documented, so use parent parent = getParent(directive) if not (IRootDirective.providedBy(parent) or IRootDirective.providedBy(directive)): subDirective = directive directive = parent ns, name = directive.name # Sometimes ns is `None`, especially in the slug files, where no # namespaces are used. ns = quoteNS(ns or 'ALL') zcml = findAPIDocumentationRoot(self.context, self.request)['ZCML'] if name not in zcml[ns]: ns = 'ALL' link = '{}/ZCML/{}/{}/index.html'.format( findAPIDocumentationRootURL(self.context, self.request), ns, name) if subDirective: link += '#' + subDirective.name[1] return link def objectURL(self, value, field, rootURL): naked = removeSecurityProxy(self.context) bound = field.bind(naked.context) obj = bound.fromUnicode(value) if obj is None: return try: isInterface = IInterface.providedBy(obj) except (AttributeError, TypeError): # pragma: no cover # probably an object that does not like to play nice with the CA isInterface = False # The object might be an instance; in this case get a link to the class if not hasattr(obj, '__name__'): # pragma: no cover obj = getattr(obj, '__class__') path = getPythonPath(obj) if isInterface: apidoc_url = findAPIDocumentationRootURL( self.context, self.request) return '{}/Interface/{}/index.html'.format(apidoc_url, path) if isReferencable(path): return rootURL + '/%s/index.html' % (path.replace('.', '/')) def attributes(self): context = removeSecurityProxy(self.context) attrs = [{'name': (ns and context.prefixes[ns] + ':' or '') + name, 'value': value, 'url': None, 'values': []} for (ns, name), value in context.attrs.items()] names = context.schema.names(True) rootURL = absoluteURL(findDocModule(self), self.request) for attr in attrs: name = ( attr['name'] if attr['name'] in names else attr['name'] + '_') field = context.schema.get(name) if isinstance(field, (GlobalObject, GlobalInterface)): attr['url'] = self.objectURL(attr['value'], field, rootURL) elif isinstance(field, Tokens): field = field.value_type values = attr['value'].strip().split() if len(values) == 1: attr['value'] = values[0] attr['url'] = self.objectURL(values[0], field, rootURL) else: for value in values: if isinstance(field, (GlobalObject, GlobalInterface)): url = self.objectURL(value, field, rootURL) else: # pragma: no cover break attr['values'].append({'value': value, 'url': url}) # Make sure that the attributes are in the same order they are defined # in the schema. fieldNames = getFieldNamesInOrder(context.schema) fieldNames = [name.endswith('_') and name[:-1] or name for name in fieldNames] attrs.sort(key=lambda x: _compareAttrs(x, fieldNames)) if not IRootDirective.providedBy(context): return attrs xmlns = [] for uri, prefix in context.prefixes.items(): name = ':' + prefix if prefix else '' xmlns.append({'name': 'xmlns' + name, 'value': uri, 'url': None, 'values': []}) xmlns.sort(key=lambda x: x['name']) return xmlns + attrs def hasSubDirectives(self): return len(removeSecurityProxy(self.context).subs) != 0 def getElements(self): context = removeSecurityProxy(self.context) return context.subs
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/browser/zcml.py
zcml.py
__docformat__ = 'restructuredtext' import inspect from zope.proxy import removeAllProxies from zope.security.proxy import removeSecurityProxy from zope.traversing.api import getParent from zope.traversing.api import traverse from zope.traversing.browser import absoluteURL from zope.traversing.interfaces import TraversalError from zope.app.apidoc.browser.utilities import findAPIDocumentationRoot from zope.app.apidoc.utilities import getFunctionSignature from zope.app.apidoc.utilities import getPermissionIds from zope.app.apidoc.utilities import getPythonPath from zope.app.apidoc.utilities import isReferencable from zope.app.apidoc.utilities import renderText def getTypeLink(type, _NoneType=type(None)): if type is _NoneType: return None path = getPythonPath(type) return path.replace('.', '/') if isReferencable(path) else None def getInterfaceInfo(iface): if iface is None: return None path = getPythonPath(iface) return {'path': path, 'url': isReferencable(path) and path or None} class ClassDetails: """Represents the details of the class.""" context = None request = None def getBases(self): """Get all bases of this class.""" return self._listClasses(self.context.getBases()) def getKnownSubclasses(self): """Get all known subclasses of this class.""" entries = self._listClasses(self.context.getKnownSubclasses()) entries.sort(key=lambda x: x['path']) return entries def _getCodeModule(self): apidoc = findAPIDocumentationRoot(self.context) return apidoc['Code'] def _listClasses(self, classes): """Prepare a list of classes for presentation.""" info = [] codeModule = self._getCodeModule() for cls in classes: # We need to removeAllProxies because the security checkers for # zope.container.contained.ContainedProxy and # zope.app.i18n.messagecatalog.MessageCatalog prevent us from # accessing __name__ and __module__. unwrapped_cls = removeAllProxies(cls) path = getPythonPath(unwrapped_cls) url = None try: klass = traverse(codeModule, path.replace('.', '/')) url = absoluteURL(klass, self.request) except TraversalError: # If one of the classes is implemented in C, we will not # be able to find it. # Likewise, if we are attempting to get a root module that # was not a registered root, the CodeModule will not be able to # find it either. pass info.append({'path': path or None, 'url': url}) return info def getBaseURL(self): """Return the URL for the API Documentation Tool.""" m = self._getCodeModule() return absoluteURL(getParent(m), self.request) def getInterfaces(self): """Get all implemented interfaces (as paths) of this class.""" return [getInterfaceInfo(iface) for iface in self.context.getInterfaces()] def getAttributes(self): """Get all attributes of this class.""" attrs = [] # remove the security proxy, so that `attr` is not proxied. We could # unproxy `attr` for each turn, but that would be less efficient. # # `getPermissionIds()` also expects the class's security checker not # to be proxied. klass = removeSecurityProxy(self.context) for name, attr, iface in klass.getAttributes(): entry = {'name': name, 'value': repr(attr), 'type': type(attr).__name__, 'type_link': getTypeLink(type(attr)), 'interface': getInterfaceInfo(iface)} entry.update(getPermissionIds(name, klass.getSecurityChecker())) attrs.append(entry) return attrs def getMethods(self): """Get all methods of this class.""" methods = [] # remove the security proxy, so that `attr` is not proxied. We could # unproxy `attr` for each turn, but that would be less efficient. # # `getPermissionIds()` also expects the class's security checker not # to be proxied. klass = removeSecurityProxy(self.context) for name, attr, iface in klass.getMethodDescriptors(): entry = {'name': name, 'signature': "(...)", 'doc': renderText(attr.__doc__ or '', inspect.getmodule(attr)), 'interface': getInterfaceInfo(iface)} entry.update(getPermissionIds(name, klass.getSecurityChecker())) methods.append(entry) for name, attr, iface in klass.getMethods(): entry = {'name': name, 'signature': getFunctionSignature(attr, ignore_self=True), 'doc': renderText(attr.__doc__ or '', inspect.getmodule(attr)), 'interface': getInterfaceInfo(iface)} entry.update(getPermissionIds(name, klass.getSecurityChecker())) methods.append(entry) return methods def getDoc(self): """Get the doc string of the class STX formatted.""" return renderText(self.context.getDocString() or '', getParent(self.context).getPath()) def getConstructor(self): """Get info about the constructor, or None if there isn't one.""" attr = self.context.getConstructor() if attr is not None: attr = removeSecurityProxy(attr) return { 'signature': getFunctionSignature(attr, ignore_self=True), 'doc': renderText(attr.__doc__ or '', inspect.getmodule(attr)), }
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/browser/class_.py
class_.py
__docformat__ = 'restructuredtext' import operator from zope.security.proxy import removeSecurityProxy from zope.traversing.api import traverse from zope.traversing.browser import absoluteURL from zope.app.apidoc.browser.utilities import findAPIDocumentationRoot from zope.app.apidoc.classregistry import classRegistry _pathgetter = operator.itemgetter("path") class Menu: """Menu for the Class Documentation Module. The menu allows for looking for classes by partial names. See `findClasses()` for the simple search implementation. """ context = None request = None def findClasses(self): """Find the classes that match a partial path. Examples:: Setup the view. >>> from zope.app.apidoc.codemodule.browser.menu import Menu >>> from zope.publisher.browser import TestRequest >>> menu = Menu() (In the following line flake8 sees a NameError, but the test passes.) >>> menu.context = apidoc['Code'] # noqa: F821 undefined name Testing the method with various inputs. >>> menu.request = TestRequest(form={'path': 'menu'}) >>> info = menu.findClasses() >>> from pprint import pprint >>> pprint(info) [{'path': 'zope.app.apidoc.codemodule.browser.menu.Menu', 'url': 'http://.../zope/app/apidoc/codemodule/browser/menu/Menu/'}, {'path': 'zope.app.apidoc.ifacemodule.menu.Menu', 'url': 'http://...Code/zope/app/apidoc/ifacemodule/menu/Menu/'}...] >>> menu.request = TestRequest(form={'path': 'illegal name'}) >>> info = menu.findClasses() >>> pprint(info) [] """ path = self.request.get('path', None) if path is None: return [] classModule = findAPIDocumentationRoot(self.context)['Code'] removeSecurityProxy(classModule).setup() found = [p for p in classRegistry if path in p] results = [] for p in found: klass = traverse(classModule, p.replace('.', '/')) results.append({ 'path': p, 'url': absoluteURL(klass, self.request) + '/' }) results.sort(key=_pathgetter) return results def findAllClasses(self): """Find all classes Examples:: Setup the view. >>> from zope.app.apidoc.codemodule.browser.menu import Menu >>> from zope.publisher.browser import TestRequest >>> menu = Menu() (In the following line flake8 sees a NameError, but the test passes.) >>> menu.context = apidoc['Code'] # noqa: F821 undefined name Make sure we're registered. >>> traverse(menu.context, ... 'zope/app/apidoc/codemodule/browser/menu/Menu') <zope.app.apidoc.codemodule.class_.Class object at ...> Testing the method with various inputs. >>> menu.request = TestRequest(form={'path': 'Foo'}) >>> info = menu.findAllClasses() >>> info = [x for x in info ... if x['path'] ... == 'zope.app.apidoc.codemodule.browser.menu.Menu'] >>> len(info) 1 """ classModule = findAPIDocumentationRoot(self.context)['Code'] removeSecurityProxy(classModule).setup() # run setup if not yet done results = [] counter = 0 # Traversing can potentially change the registry: for p in list(classRegistry): klass = traverse(classModule, p.replace('.', '/')) results.append({ 'path': p, 'url': absoluteURL(klass, self.request), 'counter': counter }) counter += 1 results.sort(key=_pathgetter) return results
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/browser/menu.py
menu.py
__docformat__ = 'restructuredtext' import inspect import zope.interface import zope.security.proxy from zope.interface import directlyProvidedBy from zope.interface import directlyProvides from zope.location import location from zope.publisher.browser import BrowserView from zope.traversing.api import getParent from zope.traversing.api import traverse from zope.traversing.interfaces import IContainmentRoot from zope.traversing.interfaces import IPhysicallyLocatable from zope import annotation from zope.app import apidoc def getTypeLink(type_): if isinstance(None, type_): return None path = apidoc.utilities.getPythonPath(type_) importable = apidoc.utilities.isReferencable(path) return path.replace('.', '/') if importable else None class annotationsNamespace: """Used to traverse to the annotations of an object.""" def __init__(self, ob, request=None): self.context = ob def traverse(self, name, ignore): # This is pretty unsafe and one of the reasons why the introspector is # only available in dev-mode. naked = zope.security.proxy.removeSecurityProxy(self.context) annotations = annotation.interfaces.IAnnotations(naked) obj = annotations[name] if name else annotations if not IPhysicallyLocatable(obj, False): obj = location.LocationProxy( obj, self.context, '++annotations++' + name) return obj class sequenceItemsNamespace: """Used to traverse to the values of a sequence.""" def __init__(self, ob, request=None): self.context = ob def traverse(self, name, ignore): obj = self.context[int(name)] if not IPhysicallyLocatable(obj, False): obj = location.LocationProxy(obj, self.context, '++items++' + name) return obj class mappingItemsNamespace: """Used to traverse to the values of a mapping. Important: This might seem like overkill, but we do not know that (1) every mapping has a traverser and (2) whether the location is available. A location might not be available, if we have a mapping in the annotations, for example. """ def __init__(self, ob, request=None): self.context = ob def traverse(self, name, ignore): obj = self.context[name] if not IPhysicallyLocatable(obj, False): obj = location.LocationProxy(obj, self.context, '++items++' + name) return obj # Small hack to simulate a traversal root. @zope.interface.implementer(IContainmentRoot) class TraversalRoot: pass class Introspector(BrowserView): """Introspector browser view""" def __init__(self, context, request): super().__init__(context, request) path = apidoc.utilities.getPythonPath( context.__class__).replace('.', '/') # the ++apidoc++ namespace overrides the skin, so make sure we can get # it back. direct = list(directlyProvidedBy(request)) self.klassView = traverse( TraversalRoot(), '/++apidoc++/Code/%s/@@index.html' % path, request=request) directlyProvides(request, direct) def parent(self): return getParent(self.context) def getBaseURL(self): return self.klassView.getBaseURL() def getDirectlyProvidedInterfaces(self): # Getting the directly provided interfaces works only on naked objects obj = zope.security.proxy.removeSecurityProxy(self.context) return [apidoc.utilities.getPythonPath(iface) for iface in zope.interface.directlyProvidedBy(obj)] def getProvidedInterfaces(self): return self.klassView.getInterfaces() def getBases(self): return self.klassView.getBases() def getAttributes(self): # remove the security proxy, so that `attr` is not proxied. We could # unproxy `attr` for each turn, but that would be less efficient. # # `getPermissionIds()` also expects the class's security checker not # to be proxied. klass = zope.security.proxy.removeSecurityProxy(self.klassView.context) obj = zope.security.proxy.removeSecurityProxy(self.context) for name in apidoc.utilities.getPublicAttributes(obj): value = getattr(obj, name) if inspect.ismethod(value) or inspect.ismethoddescriptor(value): # Because getPublicAttributes(obj) loops through # dir(obj) which is more or less obj.__dict__, and # when obj is an instance (and not a class), its # __dict__ tends not to have methods in it, so this condition # should typically not be taken. continue # pragma: no cover entry = { 'name': name, 'value': repr(value), 'value_linkable': IPhysicallyLocatable(value, False) and True, 'type': type(value).__name__, 'type_link': getTypeLink(type(value)), 'interface': apidoc.utilities.getInterfaceForAttribute( name, klass._Class__all_ifaces) } entry.update(apidoc.utilities.getPermissionIds( name, klass.getSecurityChecker())) yield entry def getMethods(self): # remove the security proxy, so that `attr` is not proxied. We could # unproxy `attr` for each turn, but that would be less efficient. # # `getPermissionIds()` also expects the class's security checker not # to be proxied. klass = zope.security.proxy.removeSecurityProxy(self.klassView.context) obj = zope.security.proxy.removeSecurityProxy(self.context) for name in apidoc.utilities.getPublicAttributes(obj): val = getattr(obj, name) if not (inspect.ismethod(val) or inspect.ismethoddescriptor(val)): continue signature = apidoc.utilities.getFunctionSignature(val) entry = { 'name': name, 'signature': signature, 'doc': apidoc.utilities.renderText( val.__doc__ or '', getParent(self.klassView.context).getPath()), 'interface': apidoc.utilities.getInterfaceForAttribute( name, klass._Class__all_ifaces)} entry.update(apidoc.utilities.getPermissionIds( name, klass.getSecurityChecker())) yield entry def isSequence(self): return zope.interface.common.sequence.IExtendedReadSequence.providedBy( self.context) def getSequenceItems(self): ann = [] # Make the object naked, so that we can inspect the value types. naked = zope.security.proxy.removeSecurityProxy(self.context) for index in range(0, len(self.context)): value = naked[index] ann.append({ 'index': index, 'value': repr(value), 'value_type': type(value).__name__, 'value_type_link': getTypeLink(type(value)) }) return ann def isMapping(self): return zope.interface.common.mapping.IEnumerableMapping.providedBy( self.context) def getMappingItems(self): ann = [] # Make the object naked, so that we can inspect the value types. naked = zope.security.proxy.removeSecurityProxy(self.context) for key, value in naked.items(): ann.append({ 'key': key, 'key_string': repr(key), 'value': repr(value), 'value_type': type(value).__name__, 'value_type_link': getTypeLink(type(value)) }) return ann def isAnnotatable(self): return annotation.interfaces.IAnnotatable.providedBy(self.context) def getAnnotationsInfo(self): # We purposefully strip the security here; this is the introspector, # so we want to see things that we usually cannot see naked = zope.security.proxy.removeSecurityProxy(self.context) annotations = annotation.interfaces.IAnnotations(naked) ann = [] for key, value in annotations.items(): ann.append({ 'key': key, 'key_string': repr(key), 'value': repr(value), 'value_type': type(value).__name__, 'value_type_link': getTypeLink(type(value)) }) return ann
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/browser/introspector.py
introspector.py
__docformat__ = 'restructuredtext' from zope.interface.interfaces import IInterface from zope.proxy import removeAllProxies from zope.publisher.browser import BrowserView from zope.traversing.browser import absoluteURL from zope.app.apidoc.browser.utilities import findAPIDocumentationRootURL from zope.app.apidoc.codemodule.interfaces import IClassDocumentation from zope.app.apidoc.codemodule.interfaces import IFunctionDocumentation from zope.app.apidoc.codemodule.interfaces import IModuleDocumentation from zope.app.apidoc.codemodule.interfaces import ITextFile from zope.app.apidoc.codemodule.interfaces import IZCMLFile from zope.app.apidoc.utilities import getPythonPath from zope.app.apidoc.utilities import renderText def formatDocString(text, module=None, summary=False): """Format a doc string for display. module is either a Python module (from sys.modules) or the dotted name of a module. If summary is true, the result is plain text and includes only the summary part of the doc string. If summary is false, the result is HTML and includes the whole doc string. """ if text is None: return None lines = text.strip().split('\n') # Get rid of possible CVS id. lines = [line for line in lines if not line.startswith('$Id')] if summary: for i in range(len(lines)): if not lines[i].strip(): del lines[i:] break return '\n'.join(lines) return renderText('\n'.join(lines), module) class ModuleDetails(BrowserView): """Represents the details of a module or package.""" def __init__(self, context, request): super().__init__(context, request) items = sorted(self.context.items()) self.text_files = [] self.zcml_files = [] self.modules = [] self.interfaces = [] self.classes = [] self.functions = [] for name, obj in items: entry = {'name': name, 'url': absoluteURL(obj, self.request)} if IFunctionDocumentation.providedBy(obj): entry['doc'] = formatDocString( obj.getDocString(), self.context.getPath()) entry['signature'] = obj.getSignature() self.functions.append(entry) elif IModuleDocumentation.providedBy(obj): entry['doc'] = formatDocString( obj.getDocString(), obj.getPath(), True) self.modules.append(entry) elif IInterface.providedBy(obj): entry['path'] = getPythonPath(removeAllProxies(obj)) entry['doc'] = formatDocString( obj.__doc__, obj.__module__, True) self.interfaces.append(entry) elif IClassDocumentation.providedBy(obj): entry['doc'] = formatDocString( obj.getDocString(), self.context.getPath(), True) self.classes.append(entry) elif IZCMLFile.providedBy(obj): self.zcml_files.append(entry) elif ITextFile.providedBy(obj): self.text_files.append(entry) def getAPIDocRootURL(self): return findAPIDocumentationRootURL(self.context, self.request) def getDoc(self): """Get the doc string of the module, formatted as HTML.""" return formatDocString( self.context.getDocString(), self.context.getPath()) def getPath(self): """Return the path to the module""" return self.context.getPath() def isPackage(self): """Return true if this module is a package""" return self.context.isPackage() def getModuleInterfaces(self): """Return entries about interfaces the module provides""" entries = [] for iface in self.context.getDeclaration(): entries.append({ 'name': iface.__name__, 'path': getPythonPath(removeAllProxies(iface)) }) return entries def getModules(self): """Return entries about contained modules and subpackages""" return self.modules def getInterfaces(self): """Return entries about interfaces declared by the module""" return self.interfaces def getClasses(self): """Return entries about classes declared by the module""" return self.classes def getTextFiles(self): """Return entries about text files contained in the package""" return self.text_files def getZCMLFiles(self): """Return entries about ZCML files contained in the package""" return self.zcml_files def getFunctions(self): """Return entries about functions declared by the package""" return self.functions
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/browser/module.py
module.py
======================== Object Introspector View ======================== The "Introspector" view provides access to information about the current obejct, the context of the introspector view. When in ``devmode``, the introspector is simply available as follows: >>> from zope.testbrowser.wsgi import Browser >>> browser = Browser() >>> browser.addHeader('Authorization', 'Basic mgr:mgrpw') >>> browser.handleErrors = False >>> browser.open('http://localhost/manage') >>> browser.getLink('Introspector').click() The page starts with telling you the class/type >>> browser.getLink('zope.site.folder.Folder').url 'http://localhost/++apidoc++/Code/zope/site/folder/Folder/index.html' and the name of the object: >>> '&lt;no name&gt;' in browser.contents True Of course, the root folder does not have a name. As you can see the type links directly to the API documentation of the class. The next section lists all directly provided interfaces. The root folder directly provides the :class:`zope.site.interfaces.ISite` and :class:`zope.site.interfaces.IRootFolder` interface, so we should see those: >>> browser.getLink('zope.component.interfaces.ISite').url '.../++apidoc++/Interface/zope.component.interfaces.ISite/index.html' >>> browser.getLink('zope.site.interfaces.IRootFolder').url '...apidoc++/Interface/zope.site.interfaces.IRootFolder/index.html' The next two section, the implemented interfaces and the base classes, are not instance specific pieces of information, but they are still nice to see at this point. For example, a :class:`zope.site.folder.Folder` instance provides the following interfaces: >>> browser.getLink('zope.site.interfaces.IFolder').url '.../++apidoc++/Interface/zope.site.interfaces.IFolder/index.html' >>> browser.getLink('persistent.interfaces.IPersistent').url '.../++apidoc++/Interface/persistent.interfaces.IPersistent/index.html' >>> browser.getLink('zope.component.interfaces.IPossibleSite').url '.../Interface/zope.component.interfaces.IPossibleSite/index.html' >>> browser.getLink('zope.location.interfaces.IContained').url '...doc++/Interface/zope.location.interfaces.IContained/index.html' The base classes of the ``Folder`` are as follows: >>> browser.getLink('zope.site.site.SiteManagerContainer').url '...apidoc++/Code/zope/site/site/SiteManagerContainer/index.html' Now that we described the component and class level of the object, the view dives into some details. First it lists the attributes/properties of the object, including the value of the attribute. This is information can be very useful when debugging an application. The only attribute of the folder is the data attribute: >>> print(browser.contents) <!DOCTYPE... ... <h2>Attributes/Properties</h2> <div class="indent"> <ul class="attr-list"> <li> <b><code>data</code></b> ... <br /> <i>Value:</i> <a href="http://localhost/++attribute++data/@@introspector.html"> <code>&lt;BTrees.OOBTree.OOBTree object at ...&gt;</code> </a> <br /> <span class="small"> <i>Permissions:</i> n/a <span>(read)</span>, n/a <span>(write)</span> </span> </li> </ul> </div> ... There are, however, several methods since the full mapping interface is implemented. Like for the class method documentation, the method's signature, doc string, permissions and the interface the method is declared in. Here an example: >>> print(browser.contents) <!DOCTYPE... ... <h2>Methods</h2> <div class="indent"> <ul class="attr-list"> <li> <b><code>get(key, default=None)</code> </b><br /> <div class="inline documentation"><p>See interface <cite>IReadContainer</cite></p> </div> <span class="small"> <i>Interface:</i> <a href="...">zope.interface.common.mapping.IReadMapping</a><br /> </span> <span class="small"> <i>Permissions:</i> zope.View <span>(read)</span>, n/a <span>(write)</span> </span> </li> ... </ul> </div> ... Towards the bottom of the page, there are some optional sections. Some objects, for example our root folder, are inheritely mappings or sequences. Their data then is often hard to see in the attributes section, so they are provided in a aseparate section. To see anything useful, we have to add an object to the folder first: >>> import re >>> browser.getLink(re.compile('^File$')).click() >>> from io import BytesIO >>> browser.getControl('Data').value = BytesIO(b'content') >>> browser.getControl(name='add_input_name').value = 'file.txt' >>> browser.getControl('Add').click() >>> browser.getLink('Introspector').click() Now the introspector will show the file and allow you to click on it: >>> print(browser.contents) <!DOCTYPE... ... <div> <h2>Mapping Items</h2> <div class="indent"> <ul class="attr-list"> <li> <b> <code>'file.txt'</code> </b> <br /> <a href="++items++file.txt/@@introspector.html"> <code>&lt;...File object at ...&gt;</code> </a> (<span>type:</span> <a href="http://localhost/++apidoc++/Code/zope/container/contained/ContainedProxy/index.html"> <code>ContainedProxy</code></a>) ... The final section of the introspector displays the annotations that are declared for the object. The standard annotation that almost every object provides is the Dublin Core: >>> print(browser.contents) <!DOCTYPE... ... <h2>Annotations</h2> <div class="indent"> <ul class="attr-list"> <li> <b> <code>'zope.app.dublincore.ZopeDublinCore'</code> </b> <br /> <a href="++annotations++zope.app.dublincore.ZopeDublinCore/@@introspector.html"> <code>...</code> </a> (<span>type:</span> <a href="http://localhost/++apidoc++/Code/zope/dublincore/annotatableadapter/ZDCAnnotationData/index.html"> <code>ZDCAnnotationData</code></a>) </li> </ul> </div> </div> <BLANKLINE> </div> ... As you can see you can click on the annotation to discover it further; the exact constructor signature varies depending on Python version (some versions report ``*args, **kwargs``, others report ``dict=None, **kwargs``): >>> browser.getLink('ZDCAnnotationData').click() >>> print(browser.contents) <!DOCTYPE... ... <h2 ...>Constructor</h2> <div class="indent"> <div> <b><code>__init__(..., **kwargs)</code> </b><br /> <div class="inline documentation"></div> </div> ... That's it! The introspector view has a lot more potential, but that's for someone else to do.
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/codemodule/browser/introspector.rst
introspector.rst
======================================== Module Menu and ZCML Directive Details ======================================== This document provides an overview of all browser-presentation related objects. .. currentmodule:: zope.app.apidoc.ifacemodule :func:`menu.getAllTextOfInterface` ================================== Get all searchable text from an interface >>> import zope.interface >>> import zope.schema >>> class IFoo(zope.interface.Interface): ... '''foo''' ... ... def bar(self): ... '''bar''' ... ... blah = zope.interface.Attribute('blah', 'blah') ... ... field = zope.schema.Field( ... title = 'title', description = 'description') Now get the text. Note that there is no particular order during the text collection. >>> from zope.app.apidoc.ifacemodule.menu import getAllTextOfInterface >>> text = getAllTextOfInterface(IFoo) >>> 'foo' in text True >>> 'bar' in text True >>> 'blah' in text True >>> 'field' in text True >>> 'title' in text True >>> 'description' in text True ``Menu`` class ============== This is the :class:`menu class <menu.Menu>` for the Interface Documentation Module. The menu allows one to look for interfaces by full-text search or partial names. The :meth:`findInterfaces <menu.Menu.findInterfaces>` method provides a simple search mechanism. Before we can test the method, let's create a :class:`menu.Menu` instance: >>> from zope.interface.interfaces import IElement, IAttribute >>> from zope.app.apidoc.ifacemodule.menu import Menu >>> menu = Menu() >>> menu.context = {'IElement': IElement, 'IAttribute': IAttribute} >>> menu.request = {'name_only': 'on', 'search_str': ''} Now let's see how successful our searches are: >>> menu.request['search_str'] = 'Elem' >>> from pprint import pprint >>> pprint(menu.findInterfaces(), width=1) [{'name': 'IElement', 'url': './IElement/index.html'}] >>> menu.request['search_str'] = 'I' >>> pprint(menu.findInterfaces(), width=1) [{'name': 'IAttribute', 'url': './IAttribute/index.html'}, {'name': 'IElement', 'url': './IElement/index.html'}] Now using the full text search: >>> del menu.request['name_only'] >>> menu.request['search_str'] = 'object' >>> pprint(menu.findInterfaces(), width=1) [{'name': 'IAttribute', 'url': './IAttribute/index.html'}, {'name': 'IElement', 'url': './IElement/index.html'}] >>> menu.request['search_str'] = 'Stores' >>> pprint(menu.findInterfaces(), width=1) [{'name': 'IAttribute', 'url': './IAttribute/index.html'}] ``InterfaceDetails`` class ========================== .. currentmodule:: zope.app.apidoc.ifacemodule.browser :class:`This view <InterfaceDetails>` provides many details about an interface. Most methods of the class actually use the public inspection API. Before we can test the view, we need to create an interesting setup, so that the view can provide some useful data. Let's start by defining a complex interface: >>> class IFoo(zope.interface.Interface): ... """This is the Foo interface ... ... More description here... ... """ ... foo = zope.interface.Attribute('This is foo.') ... bar = zope.interface.Attribute('This is bar.') ... ... title = zope.schema.TextLine( ... description='Title', ... required=True, ... default='Foo') ... ... description = zope.schema.Text( ... description='Desc', ... required=False, ... default='Foo.') ... ... def blah(): ... """This is blah.""" ... ... def get(key, default=None): ... """This is get.""" Let's now create another interface ``IBar`` and make ``Foo`` an adapter from ``IBar`` to ``IFoo``: >>> class IBar(zope.interface.Interface): ... pass >>> @zope.interface.implementer(IFoo) ... class Foo(object): ... pass >>> from zope import component as ztapi >>> ztapi.provideAdapter(adapts=(IBar,), provides=IFoo, factory=Foo) >>> from zope.app.apidoc.classregistry import classRegistry >>> classRegistry['builtins.Foo'] = Foo Let's also register a factory for ``Foo`` >>> from zope.component.interfaces import IFactory >>> from zope.component.factory import Factory >>> ztapi.provideUtility(Factory(Foo, title='Foo Factory'), IFactory, ... 'FooFactory') and a utility providing ``IFoo``: >>> ztapi.provideUtility(Foo(), IFoo, 'The Foo') Now that the initial setup is done, we can create an interface that is located in the interface documentation module >>> ifacemodule = apidoc.get('Interface') >>> from zope.location import LocationProxy >>> iface = LocationProxy(IFoo, ifacemodule, 'IFoo') and finally the details view: >>> from zope.publisher.browser import TestRequest >>> from zope.app.apidoc.ifacemodule.browser import InterfaceDetails >>> details = InterfaceDetails(iface, TestRequest()) :meth:`InterfaceDetails.getId` ------------------------------ Return the id of the field as it is defined for the interface utility. >>> details.getId() 'IFoo' :meth:`InterfaceDetails.getDoc` ------------------------------- Return the main documentation string of the interface. >>> details.getDoc()[:32] '<p>This is the Foo interface</p>' :meth:`InterfaceDetails.getBases` --------------------------------- Get all bases of this class >>> details.getBases() ['zope.interface.Interface'] :meth:`InterfaceDetails.getTypes` --------------------------------- Return a list of interface types that are specified for this interface. Initially we do not have any types >>> details.getTypes() [] but when I create and assign a type to the interface >>> class IMyType(zope.interface.interfaces.IInterface): ... pass >>> zope.interface.directlyProvides(IFoo, IMyType) we get a result: >>> pprint(details.getTypes(), width=1) [{'name': 'IMyType', 'path': 'builtins.IMyType'}] :meth:`InterfaceDetails.getAttributes` -------------------------------------- Return a list of attributes in the order they were specified. >>> pprint(sorted(details.getAttributes(), key=lambda x: x['name'])) [{'doc': '<p>This is bar.</p>\n', 'name': 'bar'}, {'doc': '<p>This is foo.</p>\n', 'name': 'foo'}] :meth:`InterfaceDetails.getMethods` ----------------------------------- Return a list of methods in the order they were specified. >>> pprint(sorted(details.getMethods(), key=lambda x: x['name'])) [{'doc': '<p>This is blah.</p>\n', 'name': 'blah', 'signature': '()'}, {'doc': '<p>This is get.</p>\n', 'name': 'get', 'signature': '(key, default=None)'}] :meth:`InterfaceDetails.getFields` ---------------------------------- Return a list of fields in required + alphabetical order. The required attributes are listed first, then the optional attributes. >>> pprint(details.getFields(), width=1) [{'class': {'name': 'TextLine', 'path': 'zope/schema/_bootstrapfields/TextLine'}, 'default': "'Foo'", 'description': '<p>Title</p>\n', 'iface': {'id': 'zope.schema.interfaces.ITextLine', 'name': 'ITextLine'}, 'name': 'title', 'required': True, 'required_string': 'required', 'title': ''}, {'class': {'name': 'Text', 'path': 'zope/schema/_bootstrapfields/Text'}, 'default': "'Foo.'", 'description': '<p>Desc</p>\n', 'iface': {'id': 'zope.schema.interfaces.IText', 'name': 'IText'}, 'name': 'description', 'required': False, 'required_string': 'optional', 'title': ''}] :meth:`InterfaceDetails.getSpecificRequiredAdapters` ---------------------------------------------------- Get adapters where this interface is required. >>> pprint(details.getSpecificRequiredAdapters()) [] :meth:`InterfaceDetails.getExtendedRequiredAdapters` ---------------------------------------------------- Get adapters where this interface is required. >>> pprint(details.getExtendedRequiredAdapters()) [] Note that this includes all interfaces registered for :class:`zope.interface.interface.Interface`. :meth:`InterfaceDetails.getGenericRequiredAdapters` --------------------------------------------------- Get adapters where this interface is required. >>> required = details.getGenericRequiredAdapters() >>> len(required) >= 10 True :meth:`InterfaceDetails.getProvidedAdapters` -------------------------------------------- Get adapters where this interface is provided. >>> pprint(details.getProvidedAdapters(), width=1) [{'doc': '', 'factory': 'builtins.Foo', 'factory_url': None, 'name': '', 'provided': {'module': 'builtins', 'name': 'IFoo'}, 'required': [{'isInterface': True, 'isType': False, 'module': 'builtins', 'name': 'IBar'}], 'zcml': None}] :meth:`InterfaceDetails.getClasses` ----------------------------------- Get the classes that implement this interface. >>> pprint(details.getClasses(), width=1) [{'path': 'builtins.Foo', 'url': 'builtins/Foo'}] :meth:`InterfaceDetails.getFactories` ------------------------------------- Return the factories, who will provide objects implementing this interface. >>> pprint(details.getFactories()) [{'description': '', 'name': 'FooFactory', 'title': 'Foo Factory', 'url': None}] :meth:`InterfaceDetails.getUtilities` ------------------------------------- Return all utilities that provide this interface. >>> pprint(details.getUtilities()) [{'iface_id': 'builtins.IFoo', 'name': 'The Foo', 'path': 'builtins.Foo', 'url': None, 'url_name': 'VGhlIEZvbw=='}]
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/ifacemodule/browser.rst
browser.rst
==================================== The Interface Documentation Module ==================================== .. currentmodule:: zope.app.apidoc.ifacemodule.ifacemodule This documentation module allows you to inspect all aspects of an interface and its role within the Zope 3 framework. The :class:`module <InterfaceModule>` can be instantiated like all other documentation modules: >>> from zope.app.apidoc.ifacemodule.ifacemodule import InterfaceModule >>> module = InterfaceModule() After registering an interface >>> from zope.interface import Interface >>> class IFoo(Interface): ... pass >>> from zope.component.interface import provideInterface >>> provideInterface(None, IFoo) >>> provideInterface('IFoo', IFoo) Now let's lookup an interface that is registered. >>> module.get('IFoo') <InterfaceClass builtins.IFoo> >>> module.get(IFoo.__module__ + '.IFoo') <InterfaceClass builtins.IFoo> Now we find an interface that is not in the site manager, but exists. >>> module.get('zope.app.apidoc.interfaces.IDocumentationModule') <InterfaceClass zope.app.apidoc.interfaces.IDocumentationModule> Finally, you can list all registered interfaces: >>> ifaces = sorted(module.items()) >>> from pprint import pprint >>> pprint(ifaces) [... ('IFoo', <InterfaceClass builtins.IFoo>), ... ('builtins.IFoo', <InterfaceClass builtins.IFoo>), ...]
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/ifacemodule/README.rst
README.rst
__docformat__ = "reStructuredText" import zope.interface import zope.schema from zope.i18nmessageid import ZopeMessageFactory as _ class IInterfaceDetailsPreferences(zope.interface.Interface): __doc__ = _(""" Preferences for API Docs' Interface Details Screen It is possible to hide and show various sections of the interface details' screen. The following preferences allow you to choose the sections to be shown by default. """) showSpecificRequiredAdapters = zope.schema.Bool( title=_("Specific Required Interface Adapters"), description=_("Show specific required interface adapters"), required=False, default=True) showExtendedRequiredAdapters = zope.schema.Bool( title=_("Extended Required Interface Adapters"), description=_("Show extended required interface adapters"), required=False, default=True) showGenericRequiredAdapters = zope.schema.Bool( title=_("Generic Required Interface Adapters"), description=_("Show generic required interface adapters"), required=False, default=False) showBrowserViews = zope.schema.Bool( title=_("Browser Views"), description=_("Show browser views"), required=False, default=True) showSpecificBrowserViews = zope.schema.Bool( title=_("Specific Browser Views"), description=_("Show specific browser views"), required=False, default=True) showExtendedBrowserViews = zope.schema.Bool( title=_("Extended Browser Views"), description=_("Show extended browser views"), required=False, default=False) showGenericBrowserViews = zope.schema.Bool( title=_("Generic Browser Views"), description=_("Show generic browser views"), required=False, default=False) showXMLRPCViews = zope.schema.Bool( title=_("XML-RPC Views"), description=_("Show XML-RPC views"), required=False, default=False) showSpecificXMLRPCViews = zope.schema.Bool( title=_("Specific XML-RPC Views"), description=_("Show specific XML-RPC views"), required=False, default=True) showExtendedXMLRPCViews = zope.schema.Bool( title=_("Extended XML-RPC Views"), description=_("Show extended XML-RPC views"), required=False, default=False) showGenericXMLRPCViews = zope.schema.Bool( title=_("Generic XML-RPC Views"), description=_("Show generic XML-RPC views"), required=False, default=False) showHTTPViews = zope.schema.Bool( title=_("Generic HTTP Views"), description=_("Show generic HTTP views"), required=False, default=False) showSpecificHTTPViews = zope.schema.Bool( title=_("Specific HTTP Views"), description=_("Show specific HTTP views"), required=False, default=True) showExtendedHTTPViews = zope.schema.Bool( title=_("Extended HTTP Views"), description=_("Show extended HTTP views"), required=False, default=False) showGenericHTTPViews = zope.schema.Bool( title=_("Generic HTTP Views"), description=_("Show generic HTTP views"), required=False, default=False) showFTPViews = zope.schema.Bool( title=_("FTP Views"), description=_("Show FTP views"), required=False, default=False) showSpecificFTPViews = zope.schema.Bool( title=_("Specific FTP Views"), description=_("Show specific FTP views"), required=False, default=True) showExtendedFTPViews = zope.schema.Bool( title=_("Extended FTP Views"), description=_("Show extended FTP views"), required=False, default=False) showGenericFTPViews = zope.schema.Bool( title=_("Generic FTP Views"), description=_("Show generic FTP views"), required=False, default=False) showOtherViews = zope.schema.Bool( title=_("Other Views"), description=_("Show other (unidentified) views"), required=False, default=False) showSpecificOtherViews = zope.schema.Bool( title=_("Specific Other Views"), description=_("Show specific other views"), required=False, default=True) showExtendedOtherViews = zope.schema.Bool( title=_("Extended Other Views"), description=_("Show extended other views"), required=False, default=False) showGenericOtherViews = zope.schema.Bool( title=_("Generic Other Views"), description=_("Show generic other views"), required=False, default=False)
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/ifacemodule/interfaces.py
interfaces.py
__docformat__ = 'restructuredtext' from zope.component.interface import queryInterface from zope.component.interface import searchInterfaceUtilities from zope.i18nmessageid import ZopeMessageFactory as _ from zope.interface import implementer from zope.location import LocationProxy from zope.location.interfaces import ILocation from zope.app.apidoc.interfaces import IDocumentationModule from zope.app.apidoc.utilities import DocumentationModuleBase class IInterfaceModule(IDocumentationModule): """Interface API Documentation Module This is a marker interface, so that we can write adapters for objects implementing this interface. """ @implementer(ILocation, IInterfaceModule) class InterfaceModule(DocumentationModuleBase): r""" Represent the Documentation of all Interfaces. The items of the container are all the interfaces listed in the global site manager. """ #: The title. title = _('Interfaces') #: The description. description = _(""" All used and important interfaces are registered through the site manager. While it would be possible to just list all attributes, it is hard on the user to read such an overfull list. Therefore, interfaces that have partial common module paths are bound together. The documentation of an interface also provides a wide variety of information, including of course the declared attributes/fields and methods, but also available adapters, and utilities that provide this interface. """) def get(self, key, default=None): iface = queryInterface(key, default) if iface is default: # Yeah, we find more items than we claim to have! This way we can # handle all interfaces using this module. :-) parts = key.split('.') try: mod = __import__('.'.join(parts[:-1]), {}, {}, ('*',)) except ImportError: iface = default else: iface = getattr(mod, parts[-1], default) if iface is not default: iface = LocationProxy(iface, self, key) return iface def items(self): items = sorted(searchInterfaceUtilities(self)) items = [(i[0], LocationProxy(i[1], self, i[0])) for i in items] return items
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/ifacemodule/ifacemodule.py
ifacemodule.py
__docformat__ = 'restructuredtext' import inspect from zope.i18nmessageid import ZopeMessageFactory as _ from zope.proxy import removeAllProxies from zope.publisher.browser import BrowserView from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.ftp import IFTPRequest from zope.publisher.interfaces.http import IHTTPRequest from zope.publisher.interfaces.xmlrpc import IXMLRPCRequest from zope.security.proxy import removeSecurityProxy from zope.traversing.api import getName from zope.traversing.api import traverse from zope.traversing.browser import absoluteURL from zope.app.apidoc import classregistry from zope.app.apidoc import component from zope.app.apidoc import interface from zope.app.apidoc import presentation from zope.app.apidoc.browser.utilities import findAPIDocumentationRoot from zope.app.apidoc.browser.utilities import findAPIDocumentationRootURL from zope.app.apidoc.utilities import getPythonPath from zope.app.apidoc.utilities import renderText class InterfaceDetails(BrowserView): """View class for an Interface.""" def __init__(self, context, request): super().__init__(context, request) self._prepareViews() def getAPIDocRootURL(self): return findAPIDocumentationRootURL(self.context, self.request) def getId(self): """Return the id of the field as it is defined for the interface utility. Example:: >>> from tests import getInterfaceDetails >>> details = getInterfaceDetails() >>> details.getId() 'IFoo' """ return getName(self.context) def getDoc(self): r"""Return the main documentation string of the interface. Example:: >>> from tests import getInterfaceDetails >>> details = getInterfaceDetails() >>> details.getDoc()[:55] u'<div class="document">\n<p>This is the Foo interface</p>' """ # We must remove all proxies here, so that we get the context's # __module__ attribute. If we only remove security proxies, the # location proxy's module will be returned. iface = removeAllProxies(self.context) return renderText(iface.__doc__, inspect.getmodule(iface)) def getBases(self): """Get all bases of this class Example:: >>> from tests import getInterfaceDetails >>> details = getInterfaceDetails() >>> details.getBases() ['zope.interface.Interface'] """ # Persistent interfaces are security proxied, so we need to strip the # security proxies off iface = removeSecurityProxy(self.context) return [getPythonPath(base) for base in iface.__bases__] def getTypes(self): """Return a list of interface types that are specified for this interface.""" # We have to really, really remove all proxies, since self.context (an # interface) is usually security proxied and location proxied. To get # the types, we need all proxies gone, otherwise the proxies' # interfaces are picked up as well. iface = removeAllProxies(self.context) return [{'name': type.getName(), 'path': getPythonPath(type)} for type in interface.getInterfaceTypes(iface)] def getAttributes(self): """Return a list of attributes in the order they were specified.""" # The `Interface` and `Attribute` class have no security declarations, # so that we are not able to access any API methods on proxied # objects. If we only remove security proxies, the location proxy's # module will be returned. iface = removeAllProxies(self.context) return [interface.getAttributeInfoDictionary(attr) for name, attr in interface.getAttributes(iface)] def getMethods(self): """Return a list of methods in the order they were specified.""" # The `Interface` class have no security declarations, so that we are # not able to access any API methods on proxied objects. If we only # remove security proxies, the location proxy's module will be # returned. iface = removeAllProxies(self.context) return [interface.getMethodInfoDictionary(method) for name, method in interface.getMethods(iface)] def getFields(self): r"""Return a list of fields in required + alphabetical order. The required attributes are listed first, then the optional attributes.""" # The `Interface` class have no security declarations, so that we are # not able to access any API methods on proxied objects. If we only # remove security proxies, the location proxy's module will be # returned. iface = removeAllProxies(self.context) # Make sure that the required fields are shown first def sorter(x): return (not x[1].required, x[0].lower()) return [interface.getFieldInfoDictionary(field) for name, field in interface.getFieldsInOrder(iface, sorter)] def getSpecificRequiredAdapters(self): """Get adapters where this interface is required.""" # Must remove security and location proxies, so that we have access to # the API methods and class representation. iface = removeAllProxies(self.context) regs = component.getRequiredAdapters(iface) regs = component.filterAdapterRegistrations( regs, iface, level=component.SPECIFIC_INTERFACE_LEVEL) regs = [component.getAdapterInfoDictionary(reg) for reg in regs] return regs def getExtendedRequiredAdapters(self): """Get adapters where this interface is required.""" # Must remove security and location proxies, so that we have access to # the API methods and class representation. iface = removeAllProxies(self.context) regs = component.getRequiredAdapters(iface) regs = component.filterAdapterRegistrations( regs, iface, level=component.EXTENDED_INTERFACE_LEVEL) regs = [component.getAdapterInfoDictionary(reg) for reg in regs] return regs def getGenericRequiredAdapters(self): """Get adapters where this interface is required.""" # Must remove security and location proxies, so that we have access to # the API methods and class representation. iface = removeAllProxies(self.context) regs = component.getRequiredAdapters(iface) regs = tuple(component.filterAdapterRegistrations( regs, iface, level=component.GENERIC_INTERFACE_LEVEL)) return [component.getAdapterInfoDictionary(reg) for reg in regs] def getProvidedAdapters(self): """Get adapters where this interface is provided.""" # Must remove security and location proxies, so that we have access to # the API methods and class representation. regs = component.getProvidedAdapters(removeAllProxies(self.context)) return [component.getAdapterInfoDictionary(reg) for reg in regs] def getClasses(self): """Get the classes that implement this interface. Example:: >>> from pprint import pprint >>> from tests import getInterfaceDetails >>> details = getInterfaceDetails() >>> classes = details.getClasses() >>> pprint(classes) [[('path', 'zope.app.apidoc.ifacemodule.tests.Foo'), ('url', 'zope/app/apidoc/ifacemodule/tests/Foo')]] """ # Must remove security and location proxies, so that we have access to # the API methods and class representation. iface = removeAllProxies(self.context) classes = classregistry.classRegistry.getClassesThatImplement(iface) return [{'path': path, 'url': path.replace('.', '/')} for path, klass in classes] def getFactories(self): """Return the factories, who will provide objects implementing this interface.""" # Must remove security and location proxies, so that we have access to # the API methods and class representation. regs = component.getFactories(removeAllProxies(self.context)) return [component.getFactoryInfoDictionary(reg) for reg in regs] def getUtilities(self): """Return all utilities that provide this interface.""" # Must remove security and location proxies, so that we have access to # the API methods and class representation. regs = component.getUtilities(removeAllProxies(self.context)) return [component.getUtilityInfoDictionary(reg) for reg in regs] def _prepareViews(self): views = {IBrowserRequest: [], IXMLRPCRequest: [], IHTTPRequest: [], IFTPRequest: [], None: []} type_map = {IBrowserRequest: 'Browser', IXMLRPCRequest: 'XMLRPC', IHTTPRequest: 'HTTP', IFTPRequest: 'FTP', None: 'Other'} level_map = {'generic': component.GENERIC_INTERFACE_LEVEL, 'extended': component.EXTENDED_INTERFACE_LEVEL, 'specific': component.SPECIFIC_INTERFACE_LEVEL} iface = removeAllProxies(self.context) for reg in presentation.getViews(iface): type = presentation.getPresentationType(reg.required[-1]) views[(type in views) and type or None].append(reg) for type, sel_views in views.items(): for level, qualifier in level_map.items(): regs = tuple(component.filterAdapterRegistrations( sel_views, iface, level=qualifier)) infos = [presentation.getViewInfoDictionary(reg) for reg in regs] setattr(self, level + type_map[type] + 'Views', infos) def getViewClassTitles(self): return { "specific": _("Specific views"), "extended": _("Extended views"), "generic": _("Generic views"), } def getViewTypeTitles(self): return { "browser": _("Browser"), "xmlrpc": _("XML-RPC"), "http": _("HTTP"), "ftp": _("FTP"), "other": _("Other"), } class InterfaceBreadCrumbs: """View that provides breadcrumbs for interface objects""" context = None request = None def __call__(self): """Create breadcrumbs for an interface object. The breadcrumbs are rooted at the code browser. """ docroot = findAPIDocumentationRoot(self.context) codeModule = traverse(docroot, "Code") crumbs = [{ 'name': _('[top]'), 'url': absoluteURL(codeModule, self.request) }] # We need the __module__ of the interface, not of a location proxy, # so we have to remove all proxies. iface = removeAllProxies(self.context) mod_names = iface.__module__.split('.') obj = codeModule for name in mod_names: try: obj = traverse(obj, name) except KeyError: # pragma: no cover # An unknown (root) module, such as logging continue crumbs.append({ 'name': name, 'url': absoluteURL(obj, self.request) }) crumbs.append({ 'name': iface.__name__, 'url': absoluteURL(self.context, self.request) }) return crumbs
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/ifacemodule/browser.py
browser.py
======================================== Module Menu and ZCML Directive Details ======================================== .. currentmodule:: zope.app.apidoc.zcmlmodule.browser :class:`Menu` ============= Let's start out by creating a menu. First we instantiate the class: >>> from zope.app.apidoc.zcmlmodule.browser import Menu >>> menu = Menu() then we create a ZCML module instance: >>> from zope.publisher.browser import TestRequest >>> module = apidoc.get('ZCML') >>> menu.context = module >>> menu.request = TestRequest() Now we create a namespace representing directives available in all namespaces >>> from zope.app.apidoc.zcmlmodule import Namespace >>> ns = Namespace(module, 'ALL') and generate a tree node : >>> from zope.app.tree.node import Node >>> node = Node(ns) We can now ask the menu for the title of the namespace >>> menu.getMenuTitle(node) 'All Namespaces' and the link to the namespace overview. >>> menu.getMenuLink(node) is None True Since the 'ALL' namespace is not that useful, let's create a namespace instance for the browser namespace: >>> ns = Namespace(module, 'http://namespaces.zope.org/browser') >>> node = Node(ns) And again we can get its title and menu link: >>> menu.getMenuTitle(node) 'browser' >>> menu.getMenuLink(node) is None True Now we add the ``page`` directive to the browser namespace: >>> from zope.app.apidoc.zcmlmodule import Directive >>> dir = Directive(ns, 'page', None, None, None, None) >>> node = Node(dir) And we can get its menu title and link. >>> menu.getMenuTitle(node) 'page' >>> menu.getMenuLink(node) 'http://127.0.0.1/++apidoc++/ZCML/http_co__sl__sl_namespaces.zope.org_sl_browser/page/index.html' Note that the directive's namespace URL is encoded, so it can be used in a URL. :class:`DirectiveDetails` ========================= A browser view class that provides support for the ZCML directive overview. Let's create a directive that we can use as context for the details: >>> from zope.interface import Interface, Attribute >>> class IFoo(Interface): ... class_ = Attribute('class_') >>> def foo(): ... pass >>> directive = Directive(ns, 'page', IFoo, foo, None, ()) Now we can isntantiate the view: >>> from zope.app.apidoc.zcmlmodule.browser import DirectiveDetails >>> details = DirectiveDetails() >>> details.context = directive >>> details.request = TestRequest() We are now ready to see what the details class has to offer. :meth:`DirectiveDetails.getSchema` ---------------------------------- Returns the interface details class for the schema. >>> iface_details = details.getSchema() >>> iface_details <zope.app.apidoc.ifacemodule.browser.InterfaceDetails object at ...> >>> iface_details.context <InterfaceClass builtins.IFoo> The :meth:`DirectiveDetails._getFieldName` method of the interface details has been overridden to neglect trailing underscores in the field name. This is necessary, since Python keywords cannot be used as field names: >>> iface_details._getFieldName(IFoo['class_']) 'class' :meth:`DirectiveDetails.getNamespaceName` ----------------------------------------- Return the name of the namespace. >>> details.getNamespaceName() 'http://namespaces.zope.org/browser' If the directive is in the 'ALL' namespace, a special string is returned: >>> details2 = DirectiveDetails() >>> ns2 = Namespace(module, 'ALL') >>> details2.context = Directive(ns2, 'include', None, None, None, None) >>> details2.getNamespaceName() '<i>all namespaces</i>' :meth:`getFileInfo` ------------------- Get the file where the directive was declared. If the info attribute is not set, return ``None``: >>> details.getFileInfo() is None True If the info attribute is a parser info, then return the details: >>> from zope.configuration.xmlconfig import ParserInfo >>> details.context.info = ParserInfo('foo.zcml', 2, 3) >>> info = details.getFileInfo() >>> from pprint import pprint >>> pprint(info, width=1) {'column': 3, 'ecolumn': 3, 'eline': 2, 'file': 'foo.zcml', 'line': 2} If the info is a string, ``None`` should be returned again: >>> details.context.info = 'info here' >>> details.getFileInfo() is None True :meth:`DirectiveDetails.getInfo` -------------------------------- Get the configuration information string of the directive: >>> details.context.info = 'info here' >>> details.getInfo() 'info here' Return ``None``, if the info attribute is a parser info: >>> details.context.info = ParserInfo('foo.zcml', 2, 3) >>> details.getInfo() is None True :meth:`DirectiveDetails.getHandler` ----------------------------------- Return information about the directive handler object. >>> pprint(details.getHandler(), width=1) {'path': 'None.foo', 'url': None} :meth:`DirectiveDetails.getSubdirectives` ----------------------------------------- Create a list of subdirectives. Currently, we have not specifiedany subdirectives >>> details.getSubdirectives() [] but if we add one >>> def handler(): ... pass >>> details.context.subdirs = ( ... ('browser', 'foo', IFoo, handler, 'info'),) the result becomes more interesting: >>> pprint(details.getSubdirectives(), width=1) [{'handler': {'path': 'None.handler', 'url': None}, 'info': 'info', 'name': 'foo', 'namespace': 'browser', 'schema': <zope.app.apidoc.ifacemodule.browser.InterfaceDetails ...>}]
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/zcmlmodule/browser.rst
browser.rst
=============================== The ZCML Documentation Module =============================== .. currentmodule:: zope.app.apidoc.zcmlmodule This documentation module provides you with a complete reference of all directives available on your Zope 3 installation. :class:`ZCMLModule` =================== The ZCML module class manages all available ZCML namespaces. Once we initialize the module >>> from zope.app.apidoc.zcmlmodule import ZCMLModule >>> module = ZCMLModule() it evaluates all meta directives and creates the namspace list: >>> module.get('http://namespaces.zope.org/browser').getFullName() 'http://namespaces.zope.org/browser' You can also access the namespace via its encoded form: >>> module.get( ... 'http_co__sl__sl_namespaces.zope.org_sl_browser').getFullName() 'http://namespaces.zope.org/browser' and via its short form: >>> module.get('browser').getFullName() 'http://namespaces.zope.org/browser' If the module does not exist, the usual :const:`None` is returned: >>> module.get('foo') is None True You can also list all namespaces: >>> names = [n for n, ns in module.items()] >>> 'ALL' in names True >>> 'http_co__sl__sl_namespaces.zope.org_sl_browser' in names True >>> 'http_co__sl__sl_namespaces.zope.org_sl_meta' in names True :class:`Namespace` ================== Simple namespace object for the ZCML Documentation Module. The namespace manages a particular ZCML namespace. The object always expects the parent to be a :class:`ZCMLModule` instance. So let's create a namespace: >>> module = ZCMLModule() >>> from zope.app.apidoc.zcmlmodule import Namespace, _clear >>> _clear() >>> ns = Namespace(ZCMLModule(), 'http://namespaces.zope.org/browser') We can now get its short name, which is the name without the URL prefix: >>> ns.getShortName() 'browser' and its full name in unquoted form: >>> ns.getFullName() 'http://namespaces.zope.org/browser' or even quoted: >>> ns.getQuotedName() 'http_co__sl__sl_namespaces.zope.org_sl_browser' One can get a directive using the common mapping interface: >>> ns.get('pages').__name__ 'pages' >>> ns.get('foo') is None True >>> print('\n'.join([name for name, dir in ns.items()][:3])) addMenuItem addform containerViews :func:`quoteNS` =============== Quotes a namespace to make it URL-secure. >>> from zope.app.apidoc.zcmlmodule import quoteNS >>> quoteNS('http://namespaces.zope.org/browser') 'http_co__sl__sl_namespaces.zope.org_sl_browser' :func:`unquoteNS` ================= Un-quotes a namespace from a URL-secure version. >>> from zope.app.apidoc.zcmlmodule import unquoteNS >>> unquoteNS('http_co__sl__sl_namespaces.zope.org_sl_browser') 'http://namespaces.zope.org/browser'
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/zcmlmodule/README.rst
README.rst
__docformat__ = 'restructuredtext' import keyword from zope.configuration.xmlconfig import ParserInfo from zope.location import LocationProxy from zope.security.proxy import isinstance from zope.security.proxy import removeSecurityProxy from zope.traversing.api import getName from zope.traversing.api import getParent from zope.app.apidoc.browser.utilities import findAPIDocumentationRootURL from zope.app.apidoc.ifacemodule.browser import InterfaceDetails from zope.app.apidoc.utilities import getPythonPath from zope.app.apidoc.utilities import isReferencable from zope.app.apidoc.utilities import relativizePath from zope.app.apidoc.zcmlmodule import Directive from zope.app.apidoc.zcmlmodule import Namespace class Menu: """Menu View Helper Class""" context = None request = None def getMenuTitle(self, node): """Return the title of the node that is displayed in the menu.""" obj = node.context if isinstance(obj, Namespace): name = obj.getShortName() if name == 'ALL': return 'All Namespaces' return name return getName(obj) def getMenuLink(self, node): """Return the HTML link of the node that is displayed in the menu.""" obj = node.context if isinstance(obj, Directive): ns = getParent(obj) apidoc_url = findAPIDocumentationRootURL( self.context, self.request) return '{}/ZCML/{}/{}/index.html'.format( apidoc_url, getName(ns), getName(obj)) return None def _getFieldName(field): name = field.getName() if name.endswith("_") and keyword.iskeyword(name[:-1]): name = name[:-1] return name class DirectiveDetails: """View class for a Directive.""" context = None request = None def getAPIDocRootURL(self): return findAPIDocumentationRootURL(self.context, self.request) def _getInterfaceDetails(self, schema): schema = LocationProxy(schema, self.context, getPythonPath(schema)) details = InterfaceDetails(schema, self.request) details._getFieldName = _getFieldName return details def getSchema(self): """Return the schema of the directive.""" return self._getInterfaceDetails(self.context.schema) def getNamespaceName(self): """Return the name of the namespace.""" name = getParent(self.context).getFullName() if name == 'ALL': return '<i>all namespaces</i>' return name def getFileInfo(self): """Get the file where the directive was declared.""" # ZCML directive `info` objects do not have security declarations, so # everything is forbidden by default. We need to remove the security # proxies in order to get to the data. info = removeSecurityProxy(self.context.info) if isinstance(info, ParserInfo): return {'file': relativizePath(info.file), 'line': info.line, 'column': info.column, 'eline': info.eline, 'ecolumn': info.ecolumn} def getInfo(self): """Get the file where the directive was declared.""" if isinstance(self.context.info, str): return self.context.info return None def getHandler(self): """Return information about the handler.""" if self.context.handler is not None: path = getPythonPath(self.context.handler) return { 'path': path, 'url': isReferencable(path) and path.replace('.', '/') or None} def getSubdirectives(self): """Create a list of subdirectives.""" dirs = [] for ns, name, schema, handler, info in self.context.subdirs: details = self._getInterfaceDetails(schema) path = getPythonPath(handler) url = path.replace('.', '/') if isReferencable(path) else None dirs.append({ 'namespace': ns, 'name': name, 'schema': details, 'handler': {'path': path, 'url': url}, 'info': info, }) return dirs
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/zcmlmodule/browser.py
browser.py
from zope.testing.cleanup import addCleanUp __docformat__ = 'restructuredtext' import zope.app.appsetup.appsetup from zope.configuration import docutils from zope.i18nmessageid import ZopeMessageFactory as _ from zope.interface import implementer from zope.location.interfaces import ILocation from zope.app.apidoc.interfaces import IDocumentationModule from zope.app.apidoc.utilities import DocumentationModuleBase from zope.app.apidoc.utilities import ReadContainerBase # Caching variables, so that the meta-ZCML files need to be read only once namespaces = None subdirs = None def quoteNS(ns): """Quotes a namespace to make it URL-secure.""" ns = ns.replace(':', '_co_') ns = ns.replace('/', '_sl_') return ns def unquoteNS(ns): """Un-quotes a namespace from a URL-secure version.""" ns = ns.replace('_sl_', '/') ns = ns.replace('_co_', ':') return ns @implementer(ILocation) class Namespace(ReadContainerBase): """Simple namespace object for the ZCML Documentation Module. This container has :class:`Directive` items as its values. """ def __init__(self, parent, name): self.__parent__ = parent self.__realname__ = name self.__name__ = self.getQuotedName() def getShortName(self): """Get the short name of the namespace.""" name = self.__realname__ if name.startswith('http://namespaces.zope.org/'): name = name[27:] return name def getFullName(self): """Get the full name of the namespace.""" return self.__realname__ def getQuotedName(self): """Get the full name, but quoted for a URL.""" name = self.getFullName() name = quoteNS(name) return name def get(self, key, default=None): _makeDocStructure() ns = self.getFullName() if key not in namespaces[ns]: return default schema, handler, info = namespaces[ns][key] sd = subdirs.get((ns, key), []) directive = Directive(self, key, schema, handler, info, sd) return directive def items(self): _makeDocStructure() return sorted((key, self.get(key)) for key in namespaces[self.getFullName()].keys()) @implementer(ILocation) class Directive: """Represents a ZCML Directive.""" def __init__(self, ns, name, schema, handler, info, subdirs): self.__parent__ = ns self.__name__ = name self.schema = schema self.handler = handler self.info = info self.subdirs = subdirs @implementer(IDocumentationModule) class ZCMLModule(DocumentationModuleBase): r""" Represent the Documentation of all ZCML namespaces. The items of the container are tuples of globally known namespaces found in the :func:`appsetup config context <zope.app.appsetup.appsetup.getConfigContext>`. """ #: Title. title = _('ZCML Reference') #: Description. description = _(""" This module presents you with a complete list of ZCML directives and serves therefore well as reference. The menu provides you with a tree that organizes the directives by namespaces. The documentation contents for each directive tells you all the available attributes and their semantics. It also provides a link to the interface the directive confirms to. If available, it will even tell you the file the directive was declared in. At the end a list of available subdirectives is given, also listing the implemented interface and available attributes. """) def get(self, key, default=None): """Get the namespace by name; long and abbreviated names work. """ _makeDocStructure() key = unquoteNS(key) if key in namespaces: return Namespace(self, key) # TODO: Search for other packages outside this root. full_key = 'http://namespaces.zope.org/' + key if full_key in namespaces: return Namespace(self, full_key) return default def items(self): _makeDocStructure() result = [] for key in namespaces: namespace = Namespace(self, key) # We need to make sure that we use the quoted URL as key result.append((namespace.getQuotedName(), namespace)) result.sort() return result def _makeDocStructure(): # Some trivial caching global namespaces global subdirs if namespaces is not None and subdirs is not None: return context = zope.app.appsetup.appsetup.getConfigContext() assert context is not None namespaces, subdirs = docutils.makeDocStructures(context) # Empty keys are not so good for a container if '' in namespaces: namespaces['ALL'] = namespaces[''] del namespaces[''] def _clear(): global namespaces global subdirs namespaces = None subdirs = None addCleanUp(_clear)
zope.app.apidoc
/zope.app.apidoc-5.0-py3-none-any.whl/zope/app/apidoc/zcmlmodule/__init__.py
__init__.py
======= CHANGES ======= 4.1.0 (2022-07-13) ------------------ - Add support for Python 3.7, 3.8, 3.9, 3.10. - Drop support for Python 3.3 and 3.4. - Make tests compatible with ``zope.app.locales >= 4.2``. 4.0.0 (2017-05-03) ------------------ - Add support for Python 3.4, 3.5 and 3.6 and PyPy. - Remove test dependency on ``zope.app.testing`` and ``zope.app.zcmlfiles``, among others. - Change dependency on ``ZODB3`` to ``ZODB``. - Remove the ability of ``ZopeVersion`` to parse information from a subversion checkout. zope.app packages are in git now. 3.5.10 (2011-11-02) ------------------- - Extended the locale-specific fix from version 3.5.6 for hosts which set ``LC_*`` in the environment: those variables shadow ``LANG``. - Replaced a testing dependency on zope.app.authentication with zope.password. - Removed unneeded zope.app.appsetup test dependency. 3.5.9 (2010-12-18) ------------------ - Bugfix: AttributeError: 'module' object has no attribute '__file__' when you used ``pip install`` instead of ``easy_install``. The IZopeVersion utility now returns "Meaningless", since there's no monolithic Zope 3 in the modern eggified world. 3.5.8 (2010-09-17) ------------------ - Replaced a testing dependency on zope.app.securitypolicy with one on zope.securitypolicy. 3.5.7 (2010-07-08) ------------------ - 3.5.6 was a bad egg release. 3.5.6 (2010-07-07) ------------------ - Bugfix: Launching ``svn`` replaced the whole environment instead of just appending ``LANG``. 3.5.5 (2010-01-09) ------------------ - Extracted RuntimeInfo and ApplicationRoot functionality into zope.applicationcontrol. Import this functionality from this package instead (see BBB imports inside this package). 3.5.4 (2010-01-08) ------------------ - Test dependency on zptpage removed. 3.5.3 (2010-01-05) ------------------ - Updated to use newer zope.publisher 3.12 and zope.login to make tests work. 3.5.2 (2009-12-19) ------------------ - Move 'zope.ManageApplication' permission from zope.app.security package - Break dependency on ``zope.app.appsetup`` by using a conditional import 3.5.1 (2009-08-15) ------------------ - Added missing (normal and test) dependencies. - Renenabled functional tests. 3.5.0 (2009-05-23) ------------------ - The application controller is now registered as a utility so that other packages like zope.traversing and zope.app.publication do not need to depend on this package directly. This also makes the application controller pluggable. 3.4.3 (2008-07-30) ------------------ - Make the test for the ZopeVersion bugfix in 3.4.2 not fail when run from an egg rather than a checkout. 3.4.2 (2008-07-30) ------------------ - Substitute zope.app.zapi by direct calls to its wrapped apis. See http://launchpad.net/bugs/219302 - Bugfix: ZopeVersion used to report an unknown version when running on a machine with a locale different than English. See http://launchpad.net/bugs/177733 - Fixed deprecation warning in ftesting.zcml: import ZopeSecurityPolicy from the new location. 3.4.1 (2007-09-27) ------------------ - rebumped to replace faulty egg 3.4.0 (2007-09-25) ------------------ - Initial documented release - Reflect changes form zope.app.error refactoring
zope.app.applicationcontrol
/zope.app.applicationcontrol-4.1.0.tar.gz/zope.app.applicationcontrol-4.1.0/CHANGES.rst
CHANGES.rst
__docformat__ = 'restructuredtext' from ZODB.interfaces import IDatabase from ZODB.POSException import StorageError from zope.size import byteDisplay from zope import component from zope.app.applicationcontrol.i18n import ZopeMessageFactory as _ size_types = (int, float) try: size_types += (long,) except NameError: pass class ZODBControlView(object): status = None def __init__(self, context, request): self.context = context self.request = request @property def databases(self): res = [] for name, db in component.getUtilitiesFor(IDatabase): d = { 'dbName': db.getName(), 'utilName': str(name), 'size': self._getSize(db), } res.append(d) return res def _getSize(self, db): """Get the database size in a human readable format.""" size = db.getSize() # IDatabase requires this to return byte size assert isinstance(size, size_types) or size is None return byteDisplay(size or 0) def update(self): if self.status is not None: return self.status status = [] if 'PACK' in self.request.form: dbs = self.request.form.get('dbs', []) try: days = int(self.request.form.get('days', '').strip() or 0) except ValueError: status.append(_('Error: Invalid Number')) self.status = status return self.status for dbName in dbs: db = component.getUtility(IDatabase, name=dbName) try: db.pack(days=days) status.append(_('ZODB "${name}" successfully packed.', mapping=dict(name=str(dbName)))) except StorageError as err: status.append(_('ERROR packing ZODB "${name}": ${err}', mapping=dict(name=str(dbName), err=err))) self.status = status return self.status
zope.app.applicationcontrol
/zope.app.applicationcontrol-4.1.0.tar.gz/zope.app.applicationcontrol-4.1.0/src/zope/app/applicationcontrol/browser/zodbcontrol.py
zodbcontrol.py
Changelog ========= 5.0 (2023-02-09) ---------------- - Add support for Python 3.9, 3.10, 3.11. - Drop support for Python 2.7, 3.5, 3.6. 4.2.0 (2020-05-20) ------------------ - Drop support for ``python setup.py test``. - Add support for Python 3.8. - Drop support for Python 3.4. 4.1.0 (2018-12-15) ------------------ - Add support for Python 3.6, 3.7 and PyPy3. - Drop support for Python 3.3. 4.0.0 (2016-08-08) ------------------ - Add dependency on ``zdaemon`` (split off from ``ZODB``). - Claim support for Python 3.4, 3.5 and PyPy which requires ``zope.app.publication`` >= 4.0. - Drop Python 2.6 support. 4.0.0a1 (2013-03-03) -------------------- - Added support for Python 3.3. - Replaced deprecated ``zope.interface.implements`` usage with equivalent ``zope.interface.implementer`` decorator. - Dropped support for Python 2.4 and 2.5. 3.16.0 (2011-01-27) ------------------- - Added stacking of storages for layer/test level setup separation in derived ZODBLayers. 3.15.0 (2010-09-25) ------------------- - Updated tests to run with `zope.testing >= 3.10`, requiring at least this version and `zope.testrunner`. - Switch ``IErrorReportingUtility copy_to_zlog`` field to ``True``. - Using Python's `doctest` module instead of depreacted `zope.testing.doctest`. 3.14.0 (2010-04-13) ------------------- - Made `zope.testing` an optional (test) dependency. - Removed test dependency on `zope.app.testing`. 3.13.0 (2009-12-24) ------------------- - Import hooks functionality from zope.component after it was moved there from zope.site. - Import ISite from zope.component after it was moved there from zope.location. This lifts the dependency on zope.location. - Added missing install dependency on `zope.testing`. 3.12.0 (2009-06-20) ------------------- - Using ``zope.processlifetime`` interfaces and implementations directly instead of BBB imports from ``zope.app.appsetup``. - Got rid of depencency on ``zope.app.component``. - Got rid of test dependency on ``zope.app.security``. 3.11 (2009-05-13) ----------------- - Event interfaces / implementations moved to ``zope.processlifetime``, version 1.0. Depend on this package, and add BBB imports. 3.10.1 (2009-03-31) ------------------- - Fixed a ``DeprecationWarning`` introduced in 3.10.0. - Added doctests to long description to show up at pypi. 3.10.0 (2009-03-19) ------------------- - Finally deprecate the "asObject" argument of helper functions in the ``zope.app.appsetup.bootstrap`` module. If your code uses any of these functions, please remove the "asObject=True" argument passing anywhere, because the support for that argument will be dropped soon. - Move session utility bootstrapping logic from ``zope.session`` into this package. This removes a dependency from zope.session to this package. - Remove one more deprecated function. 3.9.0 (2009-01-31) ------------------ - Use ``zope.site`` instead of ``zope.app.folder`` and ``zope.app.component``. - Use ``zope.container`` instead of ``zope.app.container``. - Move error log bootstrapping logic from ``zope.error`` into this package. This removes a dependency from zope.error to this package. Also added a test for bootstrapping the error log here, which was missing in ``zope.error``. 3.8.0 (2008-08-25) ------------------ - Feature: Developed an entry point that allows you to quickly bring up an application instance for debugging purposes. (Implemented by Marius Gedminas and Stephan Richter.) 3.7.0 (2008-08-19) ------------------ - Added ``.product.loadConfiguration`` test-support function; loads product configuration (only) from a file object, allowing test code (including setup) to make use of the same configuration schema support used by normal startup. 3.6.0 (2008-07-23) ------------------ - Added additional test support functions to set the configuration for a single section, and save/restore the entire configuration. 3.5.0 (2008-06-17) ------------------ - Added helper class for supporting product configuration tests. - Added documentation for the product configuration API, with tests. 3.4.1 (2007-09-27) ------------------ - Egg was faulty, re-released. 3.4.0 (2007-09-25) ------------------ - Initial documented release. - Reflect changes form zope.app.error refactoring.
zope.app.appsetup
/zope.app.appsetup-5.0.tar.gz/zope.app.appsetup-5.0/CHANGES.rst
CHANGES.rst
Bootstrap helpers ================= The bootstrap helpers provide a number of functions that help with bootstrapping. The bootStrapSubscriber function makes sure that there is a root object. It subscribes to DatabaseOpened events: >>> from zope.app.appsetup import bootstrap >>> import zope.processlifetime >>> from ZODB.MappingStorage import DB >>> db = DB() >>> bootstrap.bootStrapSubscriber(zope.processlifetime.DatabaseOpened(db)) The subscriber makes sure that there is a root folder: >>> from zope.app.publication.zopepublication import ZopePublication >>> conn = db.open() >>> root = conn.root()[ZopePublication.root_name] >>> sm = root.getSiteManager() >>> conn.close() A DatabaseOpenedWithRoot is generated with the database. >>> from zope.component.eventtesting import getEvents >>> [event] = getEvents(zope.processlifetime.IDatabaseOpenedWithRoot) >>> event.database is db True Generally, startup code that expects the root object and site to have been created will want to subscribe to this event, not IDataBaseOpenedEvent. The subscriber generates the event whether or not the root had to be set up: >>> bootstrap.bootStrapSubscriber(zope.processlifetime.DatabaseOpened(db)) >>> [e, event] = getEvents(zope.processlifetime.IDatabaseOpenedWithRoot) >>> event.database is db True Check the Security Policy ------------------------- When the security policy got refactored to be really pluggable, the inclusion of the security policy configuration was moved to the very top level, to site.zcml. This happened in r24770, after ZopeX3 3.0 was released, but before 3.1. Now the maintainers of existing 3.0 sites need to manually update their site.zcml to include securitypolicy.zcml while upgrading to 3.1. See also http://www.zope.org/Collectors/Zope3-dev/381 . >>> from zope.testing.loggingsupport import InstalledHandler >>> handler = InstalledHandler('zope.app.appsetup') If the security policy is unset from the default ParanoidSecurityPolicy, we get a warning: >>> from zope.app.appsetup.bootstrap import checkSecurityPolicy >>> event = object() >>> checkSecurityPolicy(event) >>> print(handler) zope.app.appsetup WARNING Security policy is not configured. Please make sure that securitypolicy.zcml is included in site.zcml immediately before principals.zcml However, if any non-default security policy is installed, no warning is emitted: >>> from zope.security.management import setSecurityPolicy >>> defaultPolicy = setSecurityPolicy(object()) >>> handler.clear() >>> checkSecurityPolicy(event) >>> print(handler) <BLANKLINE> Clean up: >>> handler.uninstall()
zope.app.appsetup
/zope.app.appsetup-5.0.tar.gz/zope.app.appsetup-5.0/src/zope/app/appsetup/bootstrap.rst
bootstrap.rst
Debug console ============= The debug console lets you have a Python prompt with the full Zope environment loaded (which includes the ZCML configuration, as well as an open database connection). Let's define a helper to run the debug script and trap SystemExit exceptions that would otherwise hide the output >>> from __future__ import print_function >>> import sys >>> from zope.app.appsetup import debug >>> def run(*args): ... sys.argv[0] = 'debug' ... sys.stderr = sys.stdout ... try: ... debug.main(args) ... except SystemExit as e: ... print("(exited with status %d)" % e.code) If you call the script with no arguments, it displays a brief error message on stderr >>> run() Error: please specify a configuration file For help, use debug -h (exited with status 2) We need to pass a ZConfig configuration file as an argument >>> run('-C', 'test.conf.txt') The application root is known as `root`. Now you have the root object from the open database available as a global variable named 'root' in the __main__ module: >>> main_module = sys.modules['__main__'] >>> main_module.root # doctest: +ELLIPSIS <zope.site.folder.Folder object at ...> and we have asked Python to enter interactive mode by setting the PYTHONINSPECT environment variable >>> import os >>> os.environ.get('PYTHONINSPECT') 'true' We have to do extra work to honor the PYTHONSTARTUP environment variable: >>> pythonstartup = os.path.join(os.path.dirname(debug.__file__), ... 'testdata', 'pythonstartup.py') >>> os.environ['PYTHONSTARTUP'] = pythonstartup >>> run('-C', 'test.conf.txt') The application root is known as `root`. You can see that our pythonstartup file was executed because it changed the prompt >>> sys.ps1 'debug> '
zope.app.appsetup
/zope.app.appsetup-5.0.tar.gz/zope.app.appsetup-5.0/src/zope/app/appsetup/debug.rst
debug.rst
"""Code to initialize the application server.""" import ZODB.ActivityMonitor import ZODB.interfaces import zope.component import zope.component.hooks import zope.interface import zope.processlifetime from zope.security.interfaces import IParticipation from zope.security.management import system_user @zope.interface.implementer(IParticipation) class SystemConfigurationParticipation: principal = system_user interaction = None _configured = False def config(file, features=(), execute=True): r"""Execute the ZCML configuration file. This procedure defines the global site setup. Optionally you can also provide a list of features that are inserted in the configuration context before the execution is started. Let's create a trivial sample ZCML file. >>> import tempfile >>> fn = tempfile.mktemp('.zcml') >>> zcml = open(fn, 'w') >>> written = zcml.write(''' ... <configure xmlns:meta="http://namespaces.zope.org/meta" ... xmlns:zcml="http://namespaces.zope.org/zcml"> ... <meta:provides feature="myFeature" /> ... <configure zcml:condition="have myFeature2"> ... <meta:provides feature="myFeature4" /> ... </configure> ... </configure> ... ''') >>> zcml.close() We can now pass the file into the `config()` function: # End an old interaction first >>> from zope.security.management import endInteraction >>> endInteraction() >>> context = config(fn, features=('myFeature2', 'myFeature3')) >>> context.hasFeature('myFeature') True >>> context.hasFeature('myFeature2') True >>> context.hasFeature('myFeature3') True >>> context.hasFeature('myFeature4') True Further, we should have access to the configuration file name and context now: >>> getConfigSource() is fn True >>> getConfigContext() is context True Let's now clean up by removing the temporary file: >>> import os >>> os.remove(fn) """ global _configured global __config_source __config_source = file if _configured: return from zope.configuration import config from zope.configuration import xmlconfig # Set user to system_user, so we can do anything we want from zope.security.management import newInteraction newInteraction(SystemConfigurationParticipation()) # Hook up custom component architecture calls zope.component.hooks.setHooks() # Load server-independent site config context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for feature in features: context.provideFeature(feature) context = xmlconfig.file(file, context=context, execute=execute) # Reset user from zope.security.management import endInteraction endInteraction() _configured = execute global __config_context __config_context = context return context def database(db): """Load ZODB database from Python module or FileStorage file""" if type(db) is str: # Database name if db.endswith('.py'): # Python source, exec it globals = {} exec(compile(open(db).read(), db, 'exec'), globals) if 'DB' in globals: db = globals['DB'] else: storage = globals['Storage'] from ZODB.DB import DB db = DB(storage, cache_size=4000) elif db.endswith(".fs"): from ZODB.DB import DB from ZODB.FileStorage import FileStorage storage = FileStorage(db) db = DB(storage, cache_size=4000) # The following will fail unless the application has been configured. from zope.event import notify notify(zope.processlifetime.DatabaseOpened(db)) return db def multi_database(database_factories): """Set up a multi-database from an iterable of database factories Return a sequence of databases, and a mapping of from database name to database. >>> class DB: ... def __init__(self, number): ... self.number = number ... def __repr__(self): ... return "DB(%s)" % self.number ... def getActivityMonitor(self): ... return self._activity_monitor ... def setActivityMonitor(self, am): ... self._activity_monitor = am >>> class Factory: ... def __init__(self, name, number): ... self.name = name ... self.number = number ... def open(self): ... return DB(self.number) >>> s, m = multi_database( ... [Factory(None, 3), Factory('y', 2), Factory('x', 1)]) >>> list(s) [DB(3), DB(2), DB(1)] >>> [d.database_name for d in s] ['', 'y', 'x'] >>> [d.databases is m for d in s] [True, True, True] >>> items = m.items() >>> sorted(list(items)) [('', DB(3)), ('x', DB(1)), ('y', DB(2))] Each of the databases is registered as an IDatabase utility: >>> from zope import component >>> [(component.getUtility(ZODB.interfaces.IDatabase, name) is m[name]) ... for name in m] [True, True, True] And has an activity monitor: >>> [isinstance(db.getActivityMonitor(), ... ZODB.ActivityMonitor.ActivityMonitor) ... for db in m.values()] [True, True, True] """ databases = {} result = [] for factory in database_factories: name = factory.name or '' if name in databases: raise ValueError("Duplicate database name: %r" % name) db = factory.open() db.databases = databases db.database_name = name databases[name] = db # Grrr bug in ZODB. Database doesn't declare that it implements # IDatabase. if not ZODB.interfaces.IDatabase.providedBy(db): zope.interface.directlyProvides(db, ZODB.interfaces.IDatabase) zope.component.provideUtility(db, ZODB.interfaces.IDatabase, name) db.setActivityMonitor(ZODB.ActivityMonitor.ActivityMonitor()) result.append(db) return result, databases __config_context = None def getConfigContext(): return __config_context __config_source = None def getConfigSource(): return __config_source def reset(): global _configured _configured = False global __config_source __config_source = None global __config_context __config_context = None try: import zope.testing.cleanup except ImportError: pass else: zope.testing.cleanup.addCleanUp(reset)
zope.app.appsetup
/zope.app.appsetup-5.0.tar.gz/zope.app.appsetup-5.0/src/zope/app/appsetup/appsetup.py
appsetup.py
Product-specific configuration ============================== The ``product`` module of this package provides a very simple way to deal with what has traditionally been called "product configuration", where "product" refers to the classic Zope 2 notion of a product. The configuration schema for the application server allows named <product-config> sections to be added to the configuration file, and product code can use the API provided by the module to retrieve configuration sections for given names. There are two public functions in the module that should be used in normal operations, and additional functions and a class that can be used to help with testing: >>> from __future__ import print_function >>> from zope.app.appsetup import product Let's look at the helper class first, since we'll use it in describing the public (application) interface. We'll follow that with the functions for normal operation, then the remaining test-support functions. Faux configuration object ------------------------- The ``FauxConfiguration`` class constructs objects that behave like the ZConfig section objects to the extent needed for the product configuration API. These will be used here, and may also be used to create configurations for testing components that consume such configuration. The constructor requires two arguments: the name of the section, and a mapping of keys to values that the section should provide. Let's create a simple example: >>> one = product.FauxConfiguration("one", {}) >>> one.getSectionName() 'one' >>> one.mapping {} Providing a non-empty set of key/value pairs trivially behaves as expected: >>> two = product.FauxConfiguration("two", {"abc": "def"}) >>> two.getSectionName() 'two' >>> two.mapping {'abc': 'def'} Application API --------------- There are two functions in the application interface for this module. One is used by the configuration provider, and the other is used by the consumer. The provider's API takes a sequence of configuration objects that conform to the behaviors exhibited by the default ZConfig section objects. Since the ``FauxConfiguration`` class provides these behaviors, we can easily see how this can be used: >>> product.setProductConfigurations([one, two]) Now that we've established some configuration, we want to be able to use it. We do this using the ``getProductConfiguration()`` function. This function takes a name and returns a matching configuration section if there is one, of None if not: >>> product.getProductConfiguration("one") {} >>> product.getProductConfiguration("not-there") is None True Note that for a section that exists, only the internal mapping is provided, not the containing section object. This is a historical wart; we'll just need to live with it until new APIs are introduced. Setting the configuration a second time will overwrite the prior configuration; sections previously available will no longer be: >>> product.setProductConfigurations([two]) >>> product.getProductConfiguration("one") is None True The new sections are available, as expected: >>> product.getProductConfiguration("two") {'abc': 'def'} Test support functions ---------------------- Additional functions are provided that make it easier to manage configuration state in testing. The first can be used to provide configuration for a single name. The function takes a name and either a configuration mapping or ``None`` as arguments. If ``None`` is provided as the second argument, any configuration settings for the name are removed, if present. If the second argument is not ``None``, it will be used as the return value for ``getProductConfiguration`` for the given name. >>> product.setProductConfiguration("first", None) >>> print(product.getProductConfiguration("first")) None >>> product.setProductConfiguration("first", {"key": "value1"}) >>> product.getProductConfiguration("first") {'key': 'value1'} >>> product.setProductConfiguration("first", {"key": "value2"}) >>> product.getProductConfiguration("first") {'key': 'value2'} >>> product.setProductConfiguration("first", {"alt": "another"}) >>> product.getProductConfiguration("first") {'alt': 'another'} >>> product.setProductConfiguration("second", {"you": "there"}) >>> product.getProductConfiguration("first") {'alt': 'another'} >>> product.getProductConfiguration("second") {'you': 'there'} >>> product.setProductConfiguration("first", None) >>> print(product.getProductConfiguration("first")) None The other two functions work in concert, saving and restoring the entirety of the configuration state. Our current configuration includes data for the "second" key, and none for the "first" key: >>> print(product.getProductConfiguration("first")) None >>> print(product.getProductConfiguration("second")) {'you': 'there'} Let's save this state: >>> state = product.saveConfiguration() Now let's replace the kitchen sink: >>> product.setProductConfigurations([ ... product.FauxConfiguration("x", {"a": "b"}), ... product.FauxConfiguration("y", {"c": "d"}), ... ]) >>> print(product.getProductConfiguration("first")) None >>> print(product.getProductConfiguration("second")) None >>> product.getProductConfiguration("x") {'a': 'b'} >>> product.getProductConfiguration("y") {'c': 'd'} The saved configuration state can be restored: >>> product.restoreConfiguration(state) >>> print(product.getProductConfiguration("x")) None >>> print(product.getProductConfiguration("y")) None >>> print(product.getProductConfiguration("first")) None >>> print(product.getProductConfiguration("second")) {'you': 'there'} There's an additional function that can be used to load product configuration from a file object; only product configuration components are accepted. The function returns a mapping of names to configuration objects suitable for passing to ``setProductConfiguration``. Using this with ``setProductConfigurations`` would require constructing ``FauxConfiguration`` objects. Let's create some sample configuration text: >>> product_config = ''' ... <product-config product1> ... key1 product1-value1 ... key2 product1-value2 ... </product-config> ... ... <product-config product2> ... key1 product2-value1 ... key3 product2-value2 ... </product-config> ... ''' We can now load the configuration using the ``loadConfiguration`` function: >>> import io >>> import pprint >>> sio = io.StringIO(product_config) >>> config = product.loadConfiguration(sio) >>> pprint.pprint(config, width=1) {'product1': {'key1': 'product1-value1', 'key2': 'product1-value2'}, 'product2': {'key1': 'product2-value1', 'key3': 'product2-value2'}} Extensions that provide product configurations can be used as well: >>> product_config = ''' ... %import zope.app.appsetup.testproduct ... ... <testproduct foobar> ... </testproduct> ... ... <testproduct barfoo> ... key1 value1 ... key2 value2 ... </testproduct> ... ''' >>> sio = io.StringIO(product_config) >>> config = product.loadConfiguration(sio) >>> pprint.pprint(config, width=1) {'barfoo': {'key1': 'value1', 'key2': 'value2', 'product-name': 'barfoo'}, 'foobar': {'product-name': 'foobar'}}
zope.app.appsetup
/zope.app.appsetup-5.0.tar.gz/zope.app.appsetup-5.0/src/zope/app/appsetup/product.rst
product.rst
import logging import warnings import transaction import zope.component.interfaces import zope.event import zope.lifecycleevent import zope.processlifetime from zope.app.publication.zopepublication import ZopePublication from zope.container.interfaces import INameChooser from zope.security.management import getSecurityPolicy from zope.security.simplepolicies import ParanoidSecurityPolicy from zope.site import site from zope.site.folder import rootFolder from zope.traversing.api import traverse _marker = object() def ensureObject(root_folder, object_name, object_type, object_factory, asObject=_marker): """Check that there's a basic object in the site manager. If not, add one. Return the name abdded, if we added an object, otherwise None. """ if asObject is not _marker: warnings.warn("asObject argument is deprecated and will be " "removed in Zope 3.6", DeprecationWarning, 2) package = getSiteManagerDefault(root_folder) valid_objects = [name for name in package if object_type.providedBy(package[name])] if valid_objects: return None name = object_name obj = object_factory() package[name] = obj return obj def ensureUtility(root_folder, interface, utility_type, utility_factory, name='', asObject=_marker, **kw): """Add a utility to the top site manager Returns the name added or ``None`` if nothing was added. """ if asObject is not _marker: warnings.warn("asObject argument is deprecated and will be " "removed in Zope 3.6", DeprecationWarning, 2) sm = root_folder.getSiteManager() utils = [reg for reg in sm.registeredUtilities() if (reg.provided.isOrExtends(interface) and reg.name == name)] if len(utils) == 0: return addConfigureUtility( root_folder, interface, utility_type, utility_factory, name, asObject, **kw) else: return None def addConfigureUtility( root_folder, interface, utility_type, utility_factory, name='', asObject=_marker, **kw): """Add and configure a utility to the root folder.""" if asObject is not _marker: warnings.warn("asObject argument is deprecated and will be " "removed in Zope 3.6", DeprecationWarning, 2) utility = addUtility(root_folder, utility_type, utility_factory, **kw) root_folder.getSiteManager().registerUtility(utility, interface, name) return utility def addUtility(root_folder, utility_type, utility_factory, asObject=_marker, **kw): """Add a Utility to the root folder's site manager. The utility is added to the default package and activated. """ if asObject is not _marker: warnings.warn("asObject argument is deprecated and will be " "removed in Zope 3.6", DeprecationWarning, 2) package = getSiteManagerDefault(root_folder) chooser = INameChooser(package) utility = utility_factory() name = chooser.chooseName(utility_type, utility) package[name] = utility # the utility might have been location-proxied; we need the name # information (__name__) so let's get it back again from the # container utility = package[name] # Set additional attributes on the utility for k, v in kw.items(): setattr(utility, k, v) return utility def getSiteManagerDefault(root_folder): package = traverse(root_folder.getSiteManager(), 'default') return package def getInformationFromEvent(event): """Extract information from the event Return a tuple containing - db - connection open from the db - root connection object - the root_folder object """ db = event.database connection = db.open() root = connection.root() root_folder = root.get(ZopePublication.root_name, None) return db, connection, root, root_folder ###################################################################### ###################################################################### def bootStrapSubscriber(event): """The actual subscriber to the bootstrap IDataBaseOpenedEvent Boostrap a Zope3 instance given a database object This first checks if the root folder exists and has a site manager. If it exists, nothing else is changed. If no root folder exists, one is added. """ db, connection, root, root_folder = getInformationFromEvent(event) if root_folder is None: # ugh... we depend on the root folder implementation root_folder = rootFolder() zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(root_folder)) root[ZopePublication.root_name] = root_folder if not zope.component.interfaces.ISite.providedBy(root_folder): site_manager = site.LocalSiteManager(root_folder) root_folder.setSiteManager(site_manager) transaction.commit() connection.close() zope.event.notify(zope.processlifetime.DatabaseOpenedWithRoot(db)) ######################################################################## ######################################################################## def checkSecurityPolicy(event): """Warn if the configured security policy is ParanoidSecurityPolicy Between Zope X3 3.0 and Zope 3.1, the security policy configuration was refactored and now it needs to be included from site.zcml. """ if getSecurityPolicy() is ParanoidSecurityPolicy: logging.getLogger('zope.app.appsetup').warning( 'Security policy is not configured.\n' 'Please make sure that securitypolicy.zcml is included' ' in site.zcml immediately\n' 'before principals.zcml')
zope.app.appsetup
/zope.app.appsetup-5.0.tar.gz/zope.app.appsetup-5.0/src/zope/app/appsetup/bootstrap.py
bootstrap.py
======= Changes ======= 5.0 (2023-02-09) ---------------- - Drop support for Python 2.7, 3.3, 3.4, 3.5, 3.6. - Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11. 4.0.0 (2017-05-02) ------------------ - Drop test dependency on zope.app.zcmlfiles and zope.app.testing. - Drop explicit dependency on ZODB3. - Add support for Python 3.4, 3.5 and 3.6, and PyPy. 3.9 (2010-10-18) ---------------- * Move concrete IAuthenticatorPlugin implementations to zope.pluggableauth.plugins. Leave backwards compatibility imports. * Use zope.formlib throughout to lift the dependency on zope.app.form. As it turns out, zope.app.form is still a indirect test dependency though. 3.8.0 (2010-09-25) ------------------ * Using python's ``doctest`` module instead of deprecated ``zope.testing.doctest[unit]``. * Moved the following views from `zope.app.securitypolicy` here, to inverse dependency between these two packages, as `zope.app.securitypolicy` deprecated in ZTK 1.0: - ``@@grant.html`` - ``@@AllRolePermissions.html`` - ``@@RolePermissions.html`` - ``@@RolesWithPermission.html`` 3.7.1 (2010-02-11) ------------------ * Using the new `principalfactories.zcml` file, from ``zope.pluggableauth``, to avoid duplication errors, in the adapters registration. 3.7.0 (2010-02-08) ------------------ * The Pluggable Authentication utility has been severed and released in a standalone package: `zope.pluggableauth`. We are now using this new package, providing backward compatibility imports to assure a smooth transition. 3.6.2 (2010-01-05) ------------------ * Fix tests by using zope.login, and require new zope.publisher 3.12. 3.6.1 (2009-10-07) ------------------ * Fix ftesting.zcml due to ``zope.securitypolicy`` update. * Don't use ``zope.app.testing.ztapi`` in tests, use zope.component's testing functions instead. * Fix functional tests and stop using port 8081. Redirecting to different port without trusted flag is not allowed. 3.6.0 (2009-03-14) ------------------ * Separate the presentation template and camefrom/redirection logic for the ``loginForm.html`` view. Now the logic is contained in the ``zope.app.authentication.browser.loginform.LoginForm`` class. * Fix login form redirection failure in some cases with Python 2.6. * Use the new ``zope.authentication`` package instead of ``zope.app.security``. * The "Password Manager Names" vocabulary and simple password manager registry were moved to the ``zope.password`` package. * Remove deprecated code. 3.5.0 (2009-03-06) ------------------ * Split password manager functionality off to the new ``zope.password`` package. Backward-compatibility imports are left in place. * Use ``zope.site`` instead of ``zope.app.component``. (Browser code still needs ``zope.app.component`` as it depends on view classes of this package.) 3.5.0a2 (2009-02-01) -------------------- * Make old encoded passwords really work. 3.5.0a1 (2009-01-31) -------------------- * Use ``zope.container`` instead of ``zope.app.container``. (Browser code still needs ``zope.app.container`` as it depends on view classes of this package.) * Encoded passwords are now stored with a prefix ({MD5}, {SHA1}, {SSHA}) indicating the used encoding schema. Old (encoded) passwords can still be used. * Add an SSHA password manager that is compatible with standard LDAP passwords. As this encoding gives better security agains dictionary attacks, users are encouraged to switch to this new password schema. * InternalPrincipal now uses SSHA password manager by default. 3.4.4 (2008-12-12) ------------------ * Depend on zope.session instead of zope.app.session. The first one currently has all functionality we need. * Fix deprecation warnings for ``md5`` and ``sha`` on Python 2.6. 3.4.3 (2008-08-07) ------------------ * No changes. Retag for correct release on PyPI. 3.4.2 (2008-07-09) ------------------- * Make it compatible with zope.app.container 3.6.1 and 3.5.4 changes, Changed ``super(BTreeContainer, self).__init__()`` to ``super(GroupFolder, self).__init__()`` in ``GroupFolder`` class. 3.4.1 (2007-10-24) ------------------ * Avoid deprecation warning. 3.4.0 (2007-10-11) ------------------ * Updated package meta-data. 3.4.0b1 (2007-09-27) -------------------- * First release independent of Zope.
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/CHANGES.rst
CHANGES.rst
============= Group Folders ============= Group folders provide support for groups information stored in the ZODB. They are persistent, and must be contained within the PAUs that use them. Like other principals, groups are created when they are needed. Group folders contain group-information objects that contain group information. We create group information using the `GroupInformation` class: >>> import zope.app.authentication.groupfolder >>> g1 = zope.app.authentication.groupfolder.GroupInformation("Group 1") >>> groups = zope.app.authentication.groupfolder.GroupFolder('group.') >>> groups['g1'] = g1 Note that when group-info is added, a GroupAdded event is generated: >>> from zope.app.authentication import interfaces >>> from zope.component.eventtesting import getEvents >>> getEvents(interfaces.IGroupAdded) [<GroupAdded 'group.g1'>] Groups are defined with respect to an authentication service. Groups must be accessible via an authentication service and can contain principals accessible via an authentication service. To illustrate the group interaction with the authentication service, we'll create a sample authentication service: >>> from zope import interface >>> from zope.authentication.interfaces import IAuthentication >>> from zope.authentication.interfaces import PrincipalLookupError >>> from zope.security.interfaces import IGroupAwarePrincipal >>> from zope.app.authentication.groupfolder import setGroupsForPrincipal >>> @interface.implementer(IGroupAwarePrincipal) ... class Principal(object): ... ... def __init__(self, id, title='', description=''): ... self.id, self.title, self.description = id, title, description ... self.groups = [] >>> class PrincipalCreatedEvent: ... def __init__(self, authentication, principal): ... self.authentication = authentication ... self.principal = principal >>> from zope.app.authentication import principalfolder >>> @interface.implementer(IAuthentication) ... class Principals(object): ... ... def __init__(self, groups, prefix='auth.'): ... self.prefix = prefix ... self.principals = { ... 'p1': principalfolder.PrincipalInfo('p1', '', '', ''), ... 'p2': principalfolder.PrincipalInfo('p2', '', '', ''), ... 'p3': principalfolder.PrincipalInfo('p3', '', '', ''), ... 'p4': principalfolder.PrincipalInfo('p4', '', '', ''), ... } ... self.groups = groups ... groups.__parent__ = self ... ... def getAuthenticatorPlugins(self): ... return [('principals', self.principals), ('groups', self.groups)] ... ... def getPrincipal(self, id): ... if not id.startswith(self.prefix): ... raise PrincipalLookupError(id) ... id = id[len(self.prefix):] ... info = self.principals.get(id) ... if info is None: ... info = self.groups.principalInfo(id) ... if info is None: ... raise PrincipalLookupError(id) ... principal = Principal(self.prefix+info.id, ... info.title, info.description) ... setGroupsForPrincipal(PrincipalCreatedEvent(self, principal)) ... return principal This class doesn't really implement the full `IAuthentication` interface, but it implements the `getPrincipal` method used by groups. It works very much like the pluggable authentication utility. It creates principals on demand. It calls `setGroupsForPrincipal`, which is normally called as an event subscriber, when principals are created. In order for `setGroupsForPrincipal` to find out group folder, we have to register it as a utility: >>> from zope.app.authentication.interfaces import IAuthenticatorPlugin >>> from zope.component import provideUtility >>> provideUtility(groups, IAuthenticatorPlugin) We will create and register a new principals utility: >>> principals = Principals(groups) >>> provideUtility(principals, IAuthentication) Now we can set the principals on the group: >>> g1.principals = ['auth.p1', 'auth.p2'] >>> g1.principals ('auth.p1', 'auth.p2') Adding principals fires an event. >>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1] <PrincipalsAddedToGroup ['auth.p1', 'auth.p2'] u'auth.group.g1'> We can now look up groups for the principals: >>> groups.getGroupsForPrincipal('auth.p1') (u'group.g1',) Note that the group id is a concatenation of the group-folder prefix and the name of the group-information object within the folder. If we delete a group: >>> del groups['g1'] then the groups folder loses the group information for that group's principals: >>> groups.getGroupsForPrincipal('auth.p1') () but the principal information on the group is unchanged: >>> g1.principals ('auth.p1', 'auth.p2') It also fires an event showing that the principals are removed from the group (g1 is group information, not a zope.security.interfaces.IGroup). >>> getEvents(interfaces.IPrincipalsRemovedFromGroup)[-1] <PrincipalsRemovedFromGroup ['auth.p1', 'auth.p2'] u'auth.group.g1'> Adding the group sets the folder principal information. Let's use a different group name: >>> groups['G1'] = g1 >>> groups.getGroupsForPrincipal('auth.p1') (u'group.G1',) Here we see that the new name is reflected in the group information. An event is fired, as usual. >>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1] <PrincipalsAddedToGroup ['auth.p1', 'auth.p2'] u'auth.group.G1'> In terms of member events (principals added and removed from groups), we have now seen that events are fired when a group information object is added and when it is removed from a group folder; and we have seen that events are fired when a principal is added to an already-registered group. Events are also fired when a principal is removed from an already-registered group. Let's quickly see some more examples. >>> g1.principals = ('auth.p1', 'auth.p3', 'auth.p4') >>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1] <PrincipalsAddedToGroup ['auth.p3', 'auth.p4'] u'auth.group.G1'> >>> getEvents(interfaces.IPrincipalsRemovedFromGroup)[-1] <PrincipalsRemovedFromGroup ['auth.p2'] u'auth.group.G1'> >>> g1.principals = ('auth.p1', 'auth.p2') >>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1] <PrincipalsAddedToGroup ['auth.p2'] u'auth.group.G1'> >>> getEvents(interfaces.IPrincipalsRemovedFromGroup)[-1] <PrincipalsRemovedFromGroup ['auth.p3', 'auth.p4'] u'auth.group.G1'> Groups can contain groups: >>> g2 = zope.app.authentication.groupfolder.GroupInformation("Group Two") >>> groups['G2'] = g2 >>> g2.principals = ['auth.group.G1'] >>> groups.getGroupsForPrincipal('auth.group.G1') (u'group.G2',) >>> old = getEvents(interfaces.IPrincipalsAddedToGroup)[-1] >>> old <PrincipalsAddedToGroup ['auth.group.G1'] u'auth.group.G2'> Groups cannot contain cycles: >>> g1.principals = ('auth.p1', 'auth.p2', 'auth.group.G2') ... # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... zope.pluggableauth.plugins.groupfolder.GroupCycle: ('auth.group.G2', ['auth.group.G2', 'auth.group.G1']) Trying to do so does not fire an event. >>> getEvents(interfaces.IPrincipalsAddedToGroup)[-1] is old True They need not be hierarchical: >>> ga = zope.app.authentication.groupfolder.GroupInformation("Group A") >>> groups['GA'] = ga >>> gb = zope.app.authentication.groupfolder.GroupInformation("Group B") >>> groups['GB'] = gb >>> gb.principals = ['auth.group.GA'] >>> gc = zope.app.authentication.groupfolder.GroupInformation("Group C") >>> groups['GC'] = gc >>> gc.principals = ['auth.group.GA'] >>> gd = zope.app.authentication.groupfolder.GroupInformation("Group D") >>> groups['GD'] = gd >>> gd.principals = ['auth.group.GA', 'auth.group.GB'] >>> ga.principals = ['auth.p1'] Group folders provide a very simple search interface. They perform simple string searches on group titles and descriptions. >>> list(groups.search({'search': 'grou'})) # doctest: +NORMALIZE_WHITESPACE [u'group.G1', u'group.G2', u'group.GA', u'group.GB', u'group.GC', u'group.GD'] >>> list(groups.search({'search': 'two'})) [u'group.G2'] They also support batching: >>> list(groups.search({'search': 'grou'}, 2, 3)) [u'group.GA', u'group.GB', u'group.GC'] If you don't supply a search key, no results will be returned: >>> list(groups.search({})) [] Identifying groups ------------------ The function, `setGroupsForPrincipal`, is a subscriber to principal-creation events. It adds any group-folder-defined groups to users in those groups: >>> principal = principals.getPrincipal('auth.p1') >>> principal.groups [u'auth.group.G1', u'auth.group.GA'] Of course, this applies to groups too: >>> principal = principals.getPrincipal('auth.group.G1') >>> principal.id 'auth.group.G1' >>> principal.groups [u'auth.group.G2'] In addition to setting principal groups, the `setGroupsForPrincipal` function also declares the `IGroup` interface on groups: >>> [iface.__name__ for iface in interface.providedBy(principal)] ['IGroup', 'IGroupAwarePrincipal'] >>> [iface.__name__ ... for iface in interface.providedBy(principals.getPrincipal('auth.p1'))] ['IGroupAwarePrincipal'] Special groups -------------- Two special groups, Authenticated, and Everyone may apply to users created by the pluggable-authentication utility. There is a subscriber, specialGroups, that will set these groups on any non-group principals if IAuthenticatedGroup, or IEveryoneGroup utilities are provided. Lets define a group-aware principal: >>> import zope.security.interfaces >>> @interface.implementer(zope.security.interfaces.IGroupAwarePrincipal) ... class GroupAwarePrincipal(Principal): ... ... def __init__(self, id): ... Principal.__init__(self, id) ... self.groups = [] If we notify the subscriber with this principal, nothing will happen because the groups haven't been defined: >>> prin = GroupAwarePrincipal('x') >>> event = interfaces.FoundPrincipalCreated(42, prin, {}) >>> zope.app.authentication.groupfolder.specialGroups(event) >>> prin.groups [] Now, if we define the Everybody group: >>> import zope.authentication.interfaces >>> @interface.implementer(zope.authentication.interfaces.IEveryoneGroup) ... class EverybodyGroup(Principal): ... pass >>> everybody = EverybodyGroup('all') >>> provideUtility(everybody, zope.authentication.interfaces.IEveryoneGroup) Then the group will be added to the principal: >>> zope.app.authentication.groupfolder.specialGroups(event) >>> prin.groups ['all'] Similarly for the authenticated group: >>> @interface.implementer(zope.authentication.interfaces.IAuthenticatedGroup) ... class AuthenticatedGroup(Principal): ... pass >>> authenticated = AuthenticatedGroup('auth') >>> provideUtility(authenticated, zope.authentication.interfaces.IAuthenticatedGroup) Then the group will be added to the principal: >>> prin.groups = [] >>> zope.app.authentication.groupfolder.specialGroups(event) >>> prin.groups.sort() >>> prin.groups ['all', 'auth'] These groups are only added to non-group principals: >>> prin.groups = [] >>> interface.directlyProvides(prin, zope.security.interfaces.IGroup) >>> zope.app.authentication.groupfolder.specialGroups(event) >>> prin.groups [] And they are only added to group aware principals: >>> @interface.implementer(zope.security.interfaces.IPrincipal) ... class SolitaryPrincipal(object): ... ... id = title = description = '' >>> event = interfaces.FoundPrincipalCreated(42, SolitaryPrincipal(), {}) >>> zope.app.authentication.groupfolder.specialGroups(event) >>> prin.groups [] Member-aware groups ------------------- The groupfolder includes a subscriber that gives group principals the zope.security.interfaces.IGroupAware interface and an implementation thereof. This allows groups to be able to get and set their members. Given an info object and a group... >>> @interface.implementer(zope.app.authentication.groupfolder.IGroupInformation) ... class DemoGroupInformation(object): ... ... def __init__(self, title, description, principals): ... self.title = title ... self.description = description ... self.principals = principals ... >>> i = DemoGroupInformation( ... 'Managers', 'Taskmasters', ('joe', 'jane')) ... >>> info = zope.app.authentication.groupfolder.GroupInfo( ... 'groups.managers', i) >>> @interface.implementer(IGroupAwarePrincipal) ... class DummyGroup(object): ... ... def __init__(self, id, title=u'', description=u''): ... self.id = id ... self.title = title ... self.description = description ... self.groups = [] ... >>> principal = DummyGroup('foo') >>> zope.security.interfaces.IMemberAwareGroup.providedBy(principal) False ...when you call the subscriber, it adds the two pseudo-methods to the principal and makes the principal provide the IMemberAwareGroup interface. >>> zope.app.authentication.groupfolder.setMemberSubscriber( ... interfaces.FoundPrincipalCreated( ... 'dummy auth (ignored)', principal, info)) >>> principal.getMembers() ('joe', 'jane') >>> principal.setMembers(('joe', 'jane', 'jaimie')) >>> principal.getMembers() ('joe', 'jane', 'jaimie') >>> zope.security.interfaces.IMemberAwareGroup.providedBy(principal) True The two methods work with the value on the IGroupInformation object. >>> i.principals == principal.getMembers() True Limitation ========== The current group-folder design has an important limitation! There is no point in assigning principals to a group from a group folder unless the principal is from the same pluggable authentication utility. o If a principal is from a higher authentication utility, the user will not get the group definition. Why? Because the principals group assignments are set when the principal is authenticated. At that point, the current site is the site containing the principal definition. Groups defined in lower sites will not be consulted, o It is impossible to assign users from lower authentication utilities because they can't be seen when managing the group, from the site containing the group. A better design might be to store user-role assignments independent of the group definitions and to look for assignments during (url) traversal. This could get quite complex though. While it is possible to have multiple authentication utilities long a URL path, it is generally better to stick to a simpler model in which there is only one authentication utility along a URL path (in addition to the global utility, which is used for bootstrapping purposes).
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/groupfolder.rst
groupfolder.rst
================================ Pluggable-Authentication Utility ================================ The Pluggable-Authentication Utility (PAU) provides a framework for authenticating principals and associating information with them. It uses plugins and subscribers to get its work done. For a pluggable-authentication utility to be used, it should be registered as a utility providing the `zope.authentication.interfaces.IAuthentication` interface. Authentication -------------- The primary job of PAU is to authenticate principals. It uses two types of plug-ins in its work: - Credentials Plugins - Authenticator Plugins Credentials plugins are responsible for extracting user credentials from a request. A credentials plugin may in some cases issue a 'challenge' to obtain credentials. For example, a 'session' credentials plugin reads credentials from a session (the "extraction"). If it cannot find credentials, it will redirect the user to a login form in order to provide them (the "challenge"). Authenticator plugins are responsible for authenticating the credentials extracted by a credentials plugin. They are also typically able to create principal objects for credentials they successfully authenticate. Given a request object, the PAU returns a principal object, if it can. The PAU does this by first iterateing through its credentials plugins to obtain a set of credentials. If it gets credentials, it iterates through its authenticator plugins to authenticate them. If an authenticator succeeds in authenticating a set of credentials, the PAU uses the authenticator to create a principal corresponding to the credentials. The authenticator notifies subscribers if an authenticated principal is created. Subscribers are responsible for adding data, especially groups, to the principal. Typically, if a subscriber adds data, it should also add corresponding interface declarations. Simple Credentials Plugin ~~~~~~~~~~~~~~~~~~~~~~~~~ To illustrate, we'll create a simple credentials plugin:: >>> from zope import interface >>> from zope.app.authentication import interfaces >>> @interface.implementer(interfaces.ICredentialsPlugin) ... class MyCredentialsPlugin(object): ... ... ... def extractCredentials(self, request): ... return request.get('credentials') ... ... def challenge(self, request): ... pass # challenge is a no-op for this plugin ... ... def logout(self, request): ... pass # logout is a no-op for this plugin As a plugin, MyCredentialsPlugin needs to be registered as a named utility:: >>> myCredentialsPlugin = MyCredentialsPlugin() >>> provideUtility(myCredentialsPlugin, name='My Credentials Plugin') Simple Authenticator Plugin ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Next we'll create a simple authenticator plugin. For our plugin, we'll need an implementation of IPrincipalInfo:: >>> @interface.implementer(interfaces.IPrincipalInfo) ... class PrincipalInfo(object): ... ... def __init__(self, id, title, description): ... self.id = id ... self.title = title ... self.description = description ... ... def __repr__(self): ... return 'PrincipalInfo(%r)' % self.id Our authenticator uses this type when it creates a principal info:: >>> @interface.implementer(interfaces.IAuthenticatorPlugin) ... class MyAuthenticatorPlugin(object): ... ... def authenticateCredentials(self, credentials): ... if credentials == 'secretcode': ... return PrincipalInfo('bob', 'Bob', '') ... ... def principalInfo(self, id): ... pass # plugin not currently supporting search As with the credentials plugin, the authenticator plugin must be registered as a named utility:: >>> myAuthenticatorPlugin = MyAuthenticatorPlugin() >>> provideUtility(myAuthenticatorPlugin, name='My Authenticator Plugin') Principal Factories ~~~~~~~~~~~~~~~~~~~ While authenticator plugins provide principal info, they are not responsible for creating principals. This function is performed by factory adapters. For these tests we'll borrow some factories from the principal folder:: >>> from zope.app.authentication import principalfolder >>> provideAdapter(principalfolder.AuthenticatedPrincipalFactory) >>> provideAdapter(principalfolder.FoundPrincipalFactory) For more information on these factories, see their docstrings. Configuring a PAU ~~~~~~~~~~~~~~~~~ Finally, we'll create the PAU itself:: >>> from zope.app import authentication >>> pau = authentication.PluggableAuthentication('xyz_') and configure it with the two plugins:: >>> pau.credentialsPlugins = ('My Credentials Plugin', ) >>> pau.authenticatorPlugins = ('My Authenticator Plugin', ) Using the PAU to Authenticate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We can now use the PAU to authenticate a sample request:: >>> from zope.publisher.browser import TestRequest >>> print(pau.authenticate(TestRequest())) None In this case, we cannot authenticate an empty request. In the same way, we will not be able to authenticate a request with the wrong credentials:: >>> print(pau.authenticate(TestRequest(credentials='let me in!'))) None However, if we provide the proper credentials:: >>> request = TestRequest(credentials='secretcode') >>> principal = pau.authenticate(request) >>> principal Principal('xyz_bob') we get an authenticated principal. Authenticated Principal Creates Events ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We can verify that the appropriate event was published:: >>> [event] = getEvents(interfaces.IAuthenticatedPrincipalCreated) >>> event.principal is principal True >>> event.info PrincipalInfo('bob') >>> event.request is request True The info object has the id, title, and description of the principal. The info object is also generated by the authenticator plugin, so the plugin may itself have provided additional information on the info object:: >>> event.info.title 'Bob' >>> event.info.id # does not include pau prefix 'bob' >>> event.info.description '' It is also decorated with two other attributes, credentialsPlugin and authenticatorPlugin: these are the plugins used to extract credentials for and authenticate this principal. These attributes can be useful for subscribers that want to react to the plugins used. For instance, subscribers can determine that a given credential plugin does or does not support logout, and provide information usable to show or hide logout user interface:: >>> event.info.credentialsPlugin is myCredentialsPlugin True >>> event.info.authenticatorPlugin is myAuthenticatorPlugin True Normally, we provide subscribers to these events that add additional information to the principal. For example, we'll add one that sets the title:: >>> def add_info(event): ... event.principal.title = event.info.title >>> provideHandler(add_info, [interfaces.IAuthenticatedPrincipalCreated]) Now, if we authenticate a principal, its title is set:: >>> principal = pau.authenticate(request) >>> principal.title 'Bob' Multiple Authenticator Plugins ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The PAU works with multiple authenticator plugins. It uses each plugin, in the order specified in the PAU's authenticatorPlugins attribute, to authenticate a set of credentials. To illustrate, we'll create another authenticator:: >>> class MyAuthenticatorPlugin2(MyAuthenticatorPlugin): ... ... def authenticateCredentials(self, credentials): ... if credentials == 'secretcode': ... return PrincipalInfo('black', 'Black Spy', '') ... elif credentials == 'hiddenkey': ... return PrincipalInfo('white', 'White Spy', '') >>> provideUtility(MyAuthenticatorPlugin2(), name='My Authenticator Plugin 2') If we put it before the original authenticator:: >>> pau.authenticatorPlugins = ( ... 'My Authenticator Plugin 2', ... 'My Authenticator Plugin') Then it will be given the first opportunity to authenticate a request:: >>> pau.authenticate(TestRequest(credentials='secretcode')) Principal('xyz_black') If neither plugins can authenticate, pau returns None:: >>> print(pau.authenticate(TestRequest(credentials='let me in!!'))) None When we change the order of the authenticator plugins:: >>> pau.authenticatorPlugins = ( ... 'My Authenticator Plugin', ... 'My Authenticator Plugin 2') we see that our original plugin is now acting first:: >>> pau.authenticate(TestRequest(credentials='secretcode')) Principal('xyz_bob') The second plugin, however, gets a chance to authenticate if first does not:: >>> pau.authenticate(TestRequest(credentials='hiddenkey')) Principal('xyz_white') Multiple Credentials Plugins ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ As with with authenticators, we can specify multiple credentials plugins. To illustrate, we'll create a credentials plugin that extracts credentials from a request form:: >>> @interface.implementer(interfaces.ICredentialsPlugin) ... class FormCredentialsPlugin: ... ... def extractCredentials(self, request): ... return request.form.get('my_credentials') ... ... def challenge(self, request): ... pass ... ... def logout(request): ... pass >>> provideUtility(FormCredentialsPlugin(), ... name='Form Credentials Plugin') and insert the new credentials plugin before the existing plugin:: >>> pau.credentialsPlugins = ( ... 'Form Credentials Plugin', ... 'My Credentials Plugin') The PAU will use each plugin in order to try and obtain credentials from a request:: >>> pau.authenticate(TestRequest(credentials='secretcode', ... form={'my_credentials': 'hiddenkey'})) Principal('xyz_white') In this case, the first credentials plugin succeeded in getting credentials from the form and the second authenticator was able to authenticate the credentials. Specifically, the PAU went through these steps: - Get credentials using 'Form Credentials Plugin' - Got 'hiddenkey' credentials using 'Form Credentials Plugin', try to authenticate using 'My Authenticator Plugin' - Failed to authenticate 'hiddenkey' with 'My Authenticator Plugin', try 'My Authenticator Plugin 2' - Succeeded in authenticating with 'My Authenticator Plugin 2' Let's try a different scenario:: >>> pau.authenticate(TestRequest(credentials='secretcode')) Principal('xyz_bob') In this case, the PAU went through these steps:: - Get credentials using 'Form Credentials Plugin' - Failed to get credentials using 'Form Credentials Plugin', try 'My Credentials Plugin' - Got 'scecretcode' credentials using 'My Credentials Plugin', try to authenticate using 'My Authenticator Plugin' - Succeeded in authenticating with 'My Authenticator Plugin' Let's try a slightly more complex scenario:: >>> pau.authenticate(TestRequest(credentials='hiddenkey', ... form={'my_credentials': 'bogusvalue'})) Principal('xyz_white') This highlights PAU's ability to use multiple plugins for authentication: - Get credentials using 'Form Credentials Plugin' - Got 'bogusvalue' credentials using 'Form Credentials Plugin', try to authenticate using 'My Authenticator Plugin' - Failed to authenticate 'boguskey' with 'My Authenticator Plugin', try 'My Authenticator Plugin 2' - Failed to authenticate 'boguskey' with 'My Authenticator Plugin 2' -- there are no more authenticators to try, so lets try the next credentials plugin for some new credentials - Get credentials using 'My Credentials Plugin' - Got 'hiddenkey' credentials using 'My Credentials Plugin', try to authenticate using 'My Authenticator Plugin' - Failed to authenticate 'hiddenkey' using 'My Authenticator Plugin', try 'My Authenticator Plugin 2' - Succeeded in authenticating with 'My Authenticator Plugin 2' (shouts and cheers!) Principal Searching ------------------- As a component that provides IAuthentication, a PAU lets you lookup a principal with a principal ID. The PAU looks up a principal by delegating to its authenticators. In our example, none of the authenticators implement this search capability, so when we look for a principal:: >>> print(pau.getPrincipal('xyz_bob')) Traceback (most recent call last): zope.authentication.interfaces.PrincipalLookupError: bob >>> print(pau.getPrincipal('white')) Traceback (most recent call last): zope.authentication.interfaces.PrincipalLookupError: white >>> print(pau.getPrincipal('black')) Traceback (most recent call last): zope.authentication.interfaces.PrincipalLookupError: black For a PAU to support search, it needs to be configured with one or more authenticator plugins that support search. To illustrate, we'll create a new authenticator:: >>> @interface.implementer(interfaces.IAuthenticatorPlugin) ... class SearchableAuthenticatorPlugin: ... ... def __init__(self): ... self.infos = {} ... self.ids = {} ... ... def principalInfo(self, id): ... return self.infos.get(id) ... ... def authenticateCredentials(self, credentials): ... id = self.ids.get(credentials) ... if id is not None: ... return self.infos[id] ... ... def add(self, id, title, description, credentials): ... self.infos[id] = PrincipalInfo(id, title, description) ... self.ids[credentials] = id This class is typical of an authenticator plugin. It can both authenticate principals and find principals given a ID. While there are cases where an authenticator may opt to not perform one of these two functions, they are less typical. As with any plugin, we need to register it as a utility:: >>> searchable = SearchableAuthenticatorPlugin() >>> provideUtility(searchable, name='Searchable Authentication Plugin') We'll now configure the PAU to use only the searchable authenticator:: >>> pau.authenticatorPlugins = ('Searchable Authentication Plugin',) and add some principals to the authenticator:: >>> searchable.add('bob', 'Bob', 'A nice guy', 'b0b') >>> searchable.add('white', 'White Spy', 'Sneaky', 'deathtoblack') Now when we ask the PAU to find a principal:: >>> pau.getPrincipal('xyz_bob') Principal('xyz_bob') but only those it knows about:: >>> print(pau.getPrincipal('black')) Traceback (most recent call last): zope.authentication.interfaces.PrincipalLookupError: black Found Principal Creates Events ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ As evident in the authenticator's 'createFoundPrincipal' method (see above), a FoundPrincipalCreatedEvent is published when the authenticator finds a principal on behalf of PAU's 'getPrincipal':: >>> clearEvents() >>> principal = pau.getPrincipal('xyz_white') >>> principal Principal('xyz_white') >>> [event] = getEvents(interfaces.IFoundPrincipalCreated) >>> event.principal is principal True >>> event.info PrincipalInfo('white') The info has an authenticatorPlugin, but no credentialsPlugin, since none was used:: >>> event.info.credentialsPlugin is None True >>> event.info.authenticatorPlugin is searchable True As we have seen with authenticated principals, it is common to subscribe to principal created events to add information to the newly created principal. In this case, we need to subscribe to IFoundPrincipalCreated events:: >>> provideHandler(add_info, [interfaces.IFoundPrincipalCreated]) Now when a principal is created as a result of a search, it's title and description will be set (by the add_info handler function). Multiple Authenticator Plugins ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ As with the other operations we've seen, the PAU uses multiple plugins to find a principal. If the first authenticator plugin can't find the requested principal, the next plugin is used, and so on. To illustrate, we'll create and register a second searchable authenticator:: >>> searchable2 = SearchableAuthenticatorPlugin() >>> provideUtility(searchable2, name='Searchable Authentication Plugin 2') and add a principal to it:: >>> searchable.add('black', 'Black Spy', 'Also sneaky', 'deathtowhite') When we configure the PAU to use both searchable authenticators (note the order):: >>> pau.authenticatorPlugins = ( ... 'Searchable Authentication Plugin 2', ... 'Searchable Authentication Plugin') we see how the PAU uses both plugins:: >>> pau.getPrincipal('xyz_white') Principal('xyz_white') >>> pau.getPrincipal('xyz_black') Principal('xyz_black') If more than one plugin know about the same principal ID, the first plugin is used and the remaining are not delegated to. To illustrate, we'll add another principal with the same ID as an existing principal:: >>> searchable2.add('white', 'White Rider', '', 'r1der') >>> pau.getPrincipal('xyz_white').title 'White Rider' If we change the order of the plugins:: >>> pau.authenticatorPlugins = ( ... 'Searchable Authentication Plugin', ... 'Searchable Authentication Plugin 2') we get a different principal for ID 'white':: >>> pau.getPrincipal('xyz_white').title 'White Spy' Issuing a Challenge ------------------- Part of PAU's IAuthentication contract is to challenge the user for credentials when its 'unauthorized' method is called. The need for this functionality is driven by the following use case: - A user attempts to perform an operation he is not authorized to perform. - A handler responds to the unauthorized error by calling IAuthentication 'unauthorized'. - The authentication component (in our case, a PAU) issues a challenge to the user to collect new credentials (typically in the form of logging in as a new user). The PAU handles the credentials challenge by delegating to its credentials plugins. Currently, the PAU is configured with the credentials plugins that don't perform any action when asked to challenge (see above the 'challenge' methods). To illustrate challenges, we'll subclass an existing credentials plugin and do something in its 'challenge':: >>> class LoginFormCredentialsPlugin(FormCredentialsPlugin): ... ... def __init__(self, loginForm): ... self.loginForm = loginForm ... ... def challenge(self, request): ... request.response.redirect(self.loginForm) ... return True This plugin handles a challenge by redirecting the response to a login form. It returns True to signal to the PAU that it handled the challenge. We will now create and register a couple of these plugins:: >>> provideUtility(LoginFormCredentialsPlugin('simplelogin.html'), ... name='Simple Login Form Plugin') >>> provideUtility(LoginFormCredentialsPlugin('advancedlogin.html'), ... name='Advanced Login Form Plugin') and configure the PAU to use them:: >>> pau.credentialsPlugins = ( ... 'Simple Login Form Plugin', ... 'Advanced Login Form Plugin') Now when we call 'unauthorized' on the PAU:: >>> request = TestRequest() >>> pau.unauthorized(id=None, request=request) we see that the user is redirected to the simple login form:: >>> request.response.getStatus() 302 >>> request.response.getHeader('location') 'simplelogin.html' We can change the challenge policy by reordering the plugins:: >>> pau.credentialsPlugins = ( ... 'Advanced Login Form Plugin', ... 'Simple Login Form Plugin') Now when we call 'unauthorized':: >>> request = TestRequest() >>> pau.unauthorized(id=None, request=request) the advanced plugin is used because it's first:: >>> request.response.getStatus() 302 >>> request.response.getHeader('location') 'advancedlogin.html' Challenge Protocols ~~~~~~~~~~~~~~~~~~~ Sometimes, we want multiple challengers to work together. For example, the HTTP specification allows multiple challenges to be issued in a response. A challenge plugin can provide a `challengeProtocol` attribute that effectively groups related plugins together for challenging. If a plugin returns `True` from its challenge and provides a non-None challengeProtocol, subsequent plugins in the credentialsPlugins list that have the same challenge protocol will also be used to challenge. Without a challengeProtocol, only the first plugin to succeed in a challenge will be used. Let's look at an example. We'll define a new plugin that specifies an 'X-Challenge' protocol:: >>> class XChallengeCredentialsPlugin(FormCredentialsPlugin): ... ... challengeProtocol = 'X-Challenge' ... ... def __init__(self, challengeValue): ... self.challengeValue = challengeValue ... ... def challenge(self, request): ... value = self.challengeValue ... existing = request.response.getHeader('X-Challenge', '') ... if existing: ... value += ' ' + existing ... request.response.setHeader('X-Challenge', value) ... return True and register a couple instances as utilities:: >>> provideUtility(XChallengeCredentialsPlugin('basic'), ... name='Basic X-Challenge Plugin') >>> provideUtility(XChallengeCredentialsPlugin('advanced'), ... name='Advanced X-Challenge Plugin') When we use both plugins with the PAU:: >>> pau.credentialsPlugins = ( ... 'Basic X-Challenge Plugin', ... 'Advanced X-Challenge Plugin') and call 'unauthorized':: >>> request = TestRequest() >>> pau.unauthorized(None, request) we see that both plugins participate in the challange, rather than just the first plugin:: >>> request.response.getHeader('X-Challenge') 'advanced basic' Pluggable-Authentication Prefixes --------------------------------- Principal ids are required to be unique system wide. Plugins will often provide options for providing id prefixes, so that different sets of plugins provide unique ids within a PAU. If there are multiple pluggable-authentication utilities in a system, it's a good idea to give each PAU a unique prefix, so that principal ids from different PAUs don't conflict. We can provide a prefix when a PAU is created:: >>> pau = authentication.PluggableAuthentication('mypau_') >>> pau.credentialsPlugins = ('My Credentials Plugin', ) >>> pau.authenticatorPlugins = ('My Authenticator Plugin', ) When we create a request and try to authenticate:: >>> pau.authenticate(TestRequest(credentials='secretcode')) Principal('mypau_bob') Note that now, our principal's id has the pluggable-authentication utility prefix. We can still lookup a principal, as long as we supply the prefix:: >> pau.getPrincipal('mypas_42') Principal('mypas_42', "{'domain': 42}") >> pau.getPrincipal('mypas_41') OddPrincipal('mypas_41', "{'int': 41}") Searching --------- PAU implements ISourceQueriables:: >>> from zope.schema.interfaces import ISourceQueriables >>> ISourceQueriables.providedBy(pau) True This means a PAU can be used in a principal source vocabulary (Zope provides a sophisticated searching UI for principal sources). As we've seen, a PAU uses each of its authenticator plugins to locate a principal with a given ID. However, plugins may also provide the interface IQuerySchemaSearch to indicate they can be used in the PAU's principal search scheme. Currently, our list of authenticators:: >>> pau.authenticatorPlugins ('My Authenticator Plugin',) does not include a queriable authenticator. PAU cannot therefore provide any queriables:: >>> list(pau.getQueriables()) [] Before we illustrate how an authenticator is used by the PAU to search for principals, we need to setup an adapter used by PAU:: >>> import zope.app.authentication.authentication >>> provideAdapter( ... authentication.authentication.QuerySchemaSearchAdapter, ... provides=interfaces.IQueriableAuthenticator) This adapter delegates search responsibility to an authenticator, but prepends the PAU prefix to any principal IDs returned in a search. Next, we'll create a plugin that provides a search interface:: >>> @interface.implementer(interfaces.IQuerySchemaSearch) ... class QueriableAuthenticatorPlugin(MyAuthenticatorPlugin): ... ... schema = None ... ... def search(self, query, start=None, batch_size=None): ... yield 'foo' ... and install it as a plugin:: >>> plugin = QueriableAuthenticatorPlugin() >>> provideUtility(plugin, ... provides=interfaces.IAuthenticatorPlugin, ... name='Queriable') >>> pau.authenticatorPlugins += ('Queriable',) Now, the PAU provides a single queriable:: >>> list(pau.getQueriables()) # doctest: +ELLIPSIS [('Queriable', ...QuerySchemaSearchAdapter object...)] We can use this queriable to search for our principal:: >>> queriable = list(pau.getQueriables())[0][1] >>> list(queriable.search('not-used')) ['mypau_foo'] Note that the resulting principal ID includes the PAU prefix. Were we to search the plugin directly:: >>> list(plugin.search('not-used')) ['foo'] The result does not include the PAU prefix. The prepending of the prefix is handled by the PluggableAuthenticationQueriable. Queryiable plugins can provide the ILocation interface. In this case the QuerySchemaSearchAdapter's __parent__ is the same as the __parent__ of the plugin:: >>> import zope.location.interfaces >>> @interface.implementer(zope.location.interfaces.ILocation) ... class LocatedQueriableAuthenticatorPlugin(QueriableAuthenticatorPlugin): ... ... __parent__ = __name__ = None ... >>> import zope.component.hooks >>> site = zope.component.hooks.getSite() >>> plugin = LocatedQueriableAuthenticatorPlugin() >>> plugin.__parent__ = site >>> plugin.__name__ = 'localname' >>> provideUtility(plugin, ... provides=interfaces.IAuthenticatorPlugin, ... name='location-queriable') >>> pau.authenticatorPlugins = ('location-queriable',) We have one queriable again:: >>> queriables = list(pau.getQueriables()) >>> queriables # doctest: +ELLIPSIS [('location-queriable', ...QuerySchemaSearchAdapter object...)] The queriable's __parent__ is the site as set above:: >>> queriable = queriables[0][1] >>> queriable.__parent__ is site True If the queriable provides ILocation but is not actually locatable (i.e. the parent is None) the pau itself becomes the parent:: >>> plugin = LocatedQueriableAuthenticatorPlugin() >>> provideUtility(plugin, ... provides=interfaces.IAuthenticatorPlugin, ... name='location-queriable-wo-parent') >>> pau.authenticatorPlugins = ('location-queriable-wo-parent',) We have one queriable again:: >>> queriables = list(pau.getQueriables()) >>> queriables # doctest: +ELLIPSIS [('location-queriable-wo-parent', ...QuerySchemaSearchAdapter object...)] And the parent is the pau:: >>> queriable = queriables[0][1] >>> queriable.__parent__ # doctest: +ELLIPSIS <zope.pluggableauth.authentication.PluggableAuthentication object ...> >>> queriable.__parent__ is pau True
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/README.rst
README.rst
__docformat__ = "reStructuredText" import base64 import zope.dublincore.interfaces from zope.pluggableauth import interfaces from zope.schema import vocabulary from zope.schema.interfaces import IVocabularyFactory from zope import component from zope import i18n from zope import interface from zope.app.authentication.i18n import ZopeMessageFactory as _ UTILITY_TITLE = _( 'zope.app.authentication.vocabulary-utility-plugin-title', '${name} (a utility)') CONTAINED_TITLE = _( 'zope.app.authentication.vocabulary-contained-plugin-title', '${name} (in contents)') MISSING_TITLE = _( 'zope.app.authentication.vocabulary-missing-plugin-title', '${name} (not found; deselecting will remove)') def _pluginVocabulary(context, interface, attr_name): """Vocabulary that provides names of plugins of a specified interface. Given an interface, the options should include the unique names of all of the plugins that provide the specified interface for the current context-- which is expected to be a pluggable authentication utility, hereafter referred to as a PAU). These plugins may be objects contained within the PAU ("contained plugins"), or may be utilities registered for the specified interface, found in the context of the PAU ("utility plugins"). Contained plugins mask utility plugins of the same name. The vocabulary also includes the current values of the PAU even if they do not correspond to a contained or utility plugin. """ terms = {} isPAU = interfaces.IPluggableAuthentication.providedBy(context) if isPAU: for k, v in context.items(): if interface.providedBy(v): dc = zope.dublincore.interfaces.IDCDescriptiveProperties( v, None) if dc is not None and dc.title: title = dc.title else: title = k terms[k] = vocabulary.SimpleTerm( k, base64.b64encode( k.encode('utf-8') if not isinstance(k, bytes) else k).strip(), i18n.Message(CONTAINED_TITLE, mapping={'name': title})) utils = component.getUtilitiesFor(interface, context) for nm, _util in utils: if nm not in terms: terms[nm] = vocabulary.SimpleTerm( nm, base64.b64encode(nm.encode('utf-8') if not isinstance(nm, bytes) else nm).strip(), i18n.Message(UTILITY_TITLE, mapping={'name': nm})) if isPAU: for nm in set(getattr(context, attr_name)): if nm not in terms: terms[nm] = vocabulary.SimpleTerm( nm, base64.b64encode( nm.encode('utf-8') if not isinstance(nm, bytes) else nm).strip(), i18n.Message(MISSING_TITLE, mapping={'name': nm})) return vocabulary.SimpleVocabulary( [term for nm, term in sorted(terms.items())]) def authenticatorPlugins(context): return _pluginVocabulary( context, interfaces.IAuthenticatorPlugin, 'authenticatorPlugins') interface.alsoProvides(authenticatorPlugins, IVocabularyFactory) def credentialsPlugins(context): return _pluginVocabulary( context, interfaces.ICredentialsPlugin, 'credentialsPlugins') interface.alsoProvides(credentialsPlugins, IVocabularyFactory)
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/vocabulary.py
vocabulary.py
================ Principal Folder ================ Principal folders contain principal-information objects that contain principal information. We create an internal principal using the `InternalPrincipal` class: >>> from zope.app.authentication.principalfolder import InternalPrincipal >>> p1 = InternalPrincipal('login1', '123', "Principal 1", ... passwordManagerName="SHA1") >>> p2 = InternalPrincipal('login2', '456', "The Other One") and add them to a principal folder: >>> from zope.app.authentication.principalfolder import PrincipalFolder >>> principals = PrincipalFolder('principal.') >>> principals['p1'] = p1 >>> principals['p2'] = p2 Authentication -------------- Principal folders provide the `IAuthenticatorPlugin` interface. When we provide suitable credentials: >>> from pprint import pprint >>> principals.authenticateCredentials({'login': 'login1', 'password': '123'}) PrincipalInfo(u'principal.p1') We get back a principal id and supplementary information, including the principal title and description. Note that the principal id is a concatenation of the principal-folder prefix and the name of the principal-information object within the folder. None is returned if the credentials are invalid: >>> principals.authenticateCredentials({'login': 'login1', ... 'password': '1234'}) >>> principals.authenticateCredentials(42) Search ------ Principal folders also provide the IQuerySchemaSearch interface. This supports both finding principal information based on their ids: >>> principals.principalInfo('principal.p1') PrincipalInfo('principal.p1') >>> principals.principalInfo('p1') and searching for principals based on a search string: >>> list(principals.search({'search': 'other'})) [u'principal.p2'] >>> list(principals.search({'search': 'OTHER'})) [u'principal.p2'] >>> list(principals.search({'search': ''})) [u'principal.p1', u'principal.p2'] >>> list(principals.search({'search': 'eek'})) [] >>> list(principals.search({})) [] If there are a large number of matches: >>> for i in range(20): ... i = str(i) ... p = InternalPrincipal('l'+i, i, "Dude "+i) ... principals[i] = p >>> pprint(list(principals.search({'search': 'D'}))) [u'principal.0', u'principal.1', u'principal.10', u'principal.11', u'principal.12', u'principal.13', u'principal.14', u'principal.15', u'principal.16', u'principal.17', u'principal.18', u'principal.19', u'principal.2', u'principal.3', u'principal.4', u'principal.5', u'principal.6', u'principal.7', u'principal.8', u'principal.9'] We can use batching parameters to specify a subset of results: >>> pprint(list(principals.search({'search': 'D'}, start=17))) [u'principal.7', u'principal.8', u'principal.9'] >>> pprint(list(principals.search({'search': 'D'}, batch_size=5))) [u'principal.0', u'principal.1', u'principal.10', u'principal.11', u'principal.12'] >>> pprint(list(principals.search({'search': 'D'}, start=5, batch_size=5))) [u'principal.13', u'principal.14', u'principal.15', u'principal.16', u'principal.17'] There is an additional method that allows requesting the principal id associated with a login id. The method raises KeyError when there is no associated principal:: >>> principals.getIdByLogin("not-there") Traceback (most recent call last): KeyError: 'not-there' If there is a matching principal, the id is returned:: >>> principals.getIdByLogin("login1") u'principal.p1' Changing credentials -------------------- Credentials can be changed by modifying principal-information objects: >>> p1.login = 'bob' >>> p1.password = 'eek' >>> principals.authenticateCredentials({'login': 'bob', 'password': 'eek'}) PrincipalInfo(u'principal.p1') >>> principals.authenticateCredentials({'login': 'login1', ... 'password': 'eek'}) >>> principals.authenticateCredentials({'login': 'bob', ... 'password': '123'}) It is an error to try to pick a login name that is already taken: >>> p1.login = 'login2' Traceback (most recent call last): ... ValueError: Principal Login already taken! If such an attempt is made, the data are unchanged: >>> principals.authenticateCredentials({'login': 'bob', 'password': 'eek'}) PrincipalInfo(u'principal.p1') Removing principals ------------------- Of course, if a principal is removed, we can no-longer authenticate it: >>> del principals['p1'] >>> principals.authenticateCredentials({'login': 'bob', ... 'password': 'eek'})
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/principalfolder.rst
principalfolder.rst
============ Vocabularies ============ The vocabulary module provides vocabularies for the authenticator plugins and the credentials plugins. The options should include the unique names of all of the plugins that provide the appropriate interface (interfaces.ICredentialsPlugin or interfaces.IAuthentiatorPlugin, respectively) for the current context-- which is expected to be a pluggable authentication utility, hereafter referred to as a PAU. These names may be for objects contained within the PAU ("contained plugins"), or may be utilities registered for the specified interface, found in the context of the PAU ("utility plugins"). Contained plugins mask utility plugins of the same name. They also may be names currently selected in the PAU that do not actually have a corresponding plugin at this time. Here is a short example of how the vocabulary should work. Let's say we're working with authentication plugins. We'll create some faux authentication plugins, and register some of them as utilities and put others in a faux PAU. >>> from zope.app.authentication import interfaces >>> from zope import interface, component >>> @interface.implementer(interfaces.IAuthenticatorPlugin) ... class DemoPlugin(object): ... ... def __init__(self, name): ... self.name = name ... >>> utility_plugins = dict( ... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(4)) >>> contained_plugins = dict( ... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(1, 5)) >>> sorted(utility_plugins.keys()) [0, 1, 2, 3] >>> for p in utility_plugins.values(): ... component.provideUtility(p, name=p.name) ... >>> sorted(contained_plugins.keys()) # 1 will mask utility plugin 1 [1, 2, 3, 4] >>> @interface.implementer(interfaces.IPluggableAuthentication) ... class DemoAuth(dict): ... ... def __init__(self, *args, **kwargs): ... super(DemoAuth, self).__init__(*args, **kwargs) ... self.authenticatorPlugins = (u'Plugin 3', u'Plugin X') ... self.credentialsPlugins = (u'Plugin 4', u'Plugin X') ... >>> auth = DemoAuth((p.name, p) for p in contained_plugins.values()) >>> @component.adapter(interface.Interface) ... @interface.implementer(component.IComponentLookup) ... def getSiteManager(context): ... return component.getGlobalSiteManager() ... >>> component.provideAdapter(getSiteManager) We are now ready to create a vocabulary that we can use. The context is our faux authentication utility, `auth`. >>> from zope.app.authentication import vocabulary >>> vocab = vocabulary.authenticatorPlugins(auth) Iterating over the vocabulary results in all of the terms, in a relatively arbitrary order of their names. (This vocabulary should typically use a widget that sorts values on the basis of localized collation order of the term titles.) >>> [term.value for term in vocab] # doctest: +NORMALIZE_WHITESPACE [u'Plugin 0', u'Plugin 1', u'Plugin 2', u'Plugin 3', u'Plugin 4', u'Plugin X'] Similarly, we can use `in` to test for the presence of values in the vocabulary. >>> ['Plugin %s' % i in vocab for i in range(-1, 6)] [False, True, True, True, True, True, False] >>> 'Plugin X' in vocab True The length reports the expected value. >>> len(vocab) 6 One can get a term for a given value using `getTerm()`; its token, in turn, should also return the same effective term from `getTermByToken`. >>> values = ['Plugin 0', 'Plugin 1', 'Plugin 2', 'Plugin 3', 'Plugin 4', ... 'Plugin X'] >>> for val in values: ... term = vocab.getTerm(val) ... assert term.value == val ... term2 = vocab.getTermByToken(term.token) ... assert term2.token == term.token ... assert term2.value == val ... The terms have titles, which are message ids that show the plugin title or id and whether the plugin is a utility or just contained in the auth utility. We'll give one of the plugins a dublin core title just to show the functionality. >>> import zope.dublincore.interfaces >>> class ISpecial(interface.Interface): ... pass ... >>> interface.directlyProvides(contained_plugins[1], ISpecial) >>> @interface.implementer(zope.dublincore.interfaces.IDCDescriptiveProperties) ... @component.adapter(ISpecial) ... class DemoDCAdapter(object): ... def __init__(self, context): ... pass ... title = u'Special Title' ... >>> component.provideAdapter(DemoDCAdapter) We need to regenerate the vocabulary, since it calculates all of its data at once. >>> vocab = vocabulary.authenticatorPlugins(auth) Now we'll check the titles. We'll have to translate them to see what we expect. >>> from zope import i18n >>> import pprint >>> pprint.pprint([i18n.translate(term.title) for term in vocab]) [u'Plugin 0 (a utility)', u'Special Title (in contents)', u'Plugin 2 (in contents)', u'Plugin 3 (in contents)', u'Plugin 4 (in contents)', u'Plugin X (not found; deselecting will remove)'] credentialsPlugins ------------------ For completeness, we'll do the same review of the credentialsPlugins. >>> @interface.implementer(interfaces.ICredentialsPlugin) ... class DemoPlugin(object): ... ... def __init__(self, name): ... self.name = name ... >>> utility_plugins = dict( ... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(4)) >>> contained_plugins = dict( ... (i, DemoPlugin(u'Plugin %d' % i)) for i in range(1, 5)) >>> for p in utility_plugins.values(): ... component.provideUtility(p, name=p.name) ... >>> auth = DemoAuth((p.name, p) for p in contained_plugins.values()) >>> vocab = vocabulary.credentialsPlugins(auth) Iterating over the vocabulary results in all of the terms, in a relatively arbitrary order of their names. (This vocabulary should typically use a widget that sorts values on the basis of localized collation order of the term titles.) Similarly, we can use `in` to test for the presence of values in the vocabulary. The length reports the expected value. >>> [term.value for term in vocab] # doctest: +NORMALIZE_WHITESPACE [u'Plugin 0', u'Plugin 1', u'Plugin 2', u'Plugin 3', u'Plugin 4', u'Plugin X'] >>> ['Plugin %s' % i in vocab for i in range(-1, 6)] [False, True, True, True, True, True, False] >>> 'Plugin X' in vocab True >>> len(vocab) 6 One can get a term for a given value using `getTerm()`; its token, in turn, should also return the same effective term from `getTermByToken`. >>> values = ['Plugin 0', 'Plugin 1', 'Plugin 2', 'Plugin 3', 'Plugin 4', ... 'Plugin X'] >>> for val in values: ... term = vocab.getTerm(val) ... assert term.value == val ... term2 = vocab.getTermByToken(term.token) ... assert term2.token == term.token ... assert term2.value == val ... The terms have titles, which are message ids that show the plugin title or id and whether the plugin is a utility or just contained in the auth utility. We'll give one of the plugins a dublin core title just to show the functionality. We need to regenerate the vocabulary, since it calculates all of its data at once. Then we'll check the titles. We'll have to translate them to see what we expect. >>> interface.directlyProvides(contained_plugins[1], ISpecial) >>> vocab = vocabulary.credentialsPlugins(auth) >>> pprint.pprint([i18n.translate(term.title) for term in vocab]) [u'Plugin 0 (a utility)', u'Special Title (in contents)', u'Plugin 2 (in contents)', u'Plugin 3 (in contents)', u'Plugin 4 (in contents)', u'Plugin X (not found; deselecting will remove)']
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/vocabulary.rst
vocabulary.rst
Using Group Folders =================== Group folders are used to define groups. Before you can define groups, you have to create a group folder and configure it in a pluggable authentication utility. The group folder has to be registered with a pluggable authentication utility before defining any groups. This is because the groups folder needs to use the pluggable authentication utility to find all of the groups containing a given group so that it can check for group cycles. Not all of a group's groups need to be defined in it's group folder. Other groups folders or group-defining plugins could define groups for a group. Let's walk through an example. First, We need to create and register a pluggable authentication utility. >>> print(http(r""" ... POST /++etc++site/default/@@contents.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 98 ... Content-Type: application/x-www-form-urlencoded ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/@@contents.html?type_name=BrowserAdd__zope.pluggableauth.authentication.PluggableAuthentication ... ... type_name=BrowserAdd__zope.pluggableauth.authentication.PluggableAuthentication&new_value=PAU""")) HTTP/1.1 303 See Other ... >>> print(http(r""" ... GET /++etc++site/default/PAU/@@registration.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/@@contents.html?type_name=BrowserAdd__zope.pluggableauth.authentication.PluggableAuthentication ... """)) HTTP/1.1 200 Ok ... Register PAU. >>> print(http(r""" ... POST /++etc++site/default/PAU/addRegistration.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 687 ... Content-Type: multipart/form-data; boundary=---------------------------5559795404609280911441883437 ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/PAU/addRegistration.html ... ... -----------------------------5559795404609280911441883437 ... Content-Disposition: form-data; name="field.comment" ... ... ... -----------------------------5559795404609280911441883437 ... Content-Disposition: form-data; name="field.actions.register" ... ... Register ... -----------------------------5559795404609280911441883437-- ... """)) HTTP/1.1 303 See Other ... Add a Principal folder plugin `users` to PAU. >>> print(http(r""" ... POST /++etc++site/default/PAU/+/AddPrincipalFolder.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 429 ... Content-Type: multipart/form-data; boundary=---------------------------95449631112274213651507932125 ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/PAU/+/AddPrincipalFolder.html= ... ... -----------------------------95449631112274213651507932125 ... Content-Disposition: form-data; name="field.prefix" ... ... users ... -----------------------------95449631112274213651507932125 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------95449631112274213651507932125 ... Content-Disposition: form-data; name="add_input_name" ... ... users ... -----------------------------95449631112274213651507932125-- ... """)) HTTP/1.1 303 See Other ... Next we will add some users. >>> print(http(r""" ... POST /++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 780 ... Content-Type: multipart/form-data; boundary=---------------------------5110544421083023415453147877 ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.login" ... ... bob ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.passwordManagerName" ... ... Plain Text ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.password" ... ... 123 ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.title" ... ... Bob ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------5110544421083023415453147877-- ... """, handle_errors=False)) HTTP/1.1 303 See Other ... >>> print(http(r""" ... POST /++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 780 ... Content-Type: multipart/form-data; boundary=---------------------------5110544421083023415453147877 ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.login" ... ... bill ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.passwordManagerName" ... ... Plain Text ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.password" ... ... 123 ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.title" ... ... Bill ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------5110544421083023415453147877-- ... """)) HTTP/1.1 303 See Other ... >>> print(http(r""" ... POST /++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 780 ... Content-Type: multipart/form-data; boundary=---------------------------5110544421083023415453147877 ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.login" ... ... betty ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.passwordManagerName" ... ... Plain Text ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.password" ... ... 123 ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.title" ... ... Betty ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------5110544421083023415453147877-- ... """)) HTTP/1.1 303 See Other ... >>> print(http(r""" ... POST /++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 780 ... Content-Type: multipart/form-data; boundary=---------------------------5110544421083023415453147877 ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.login" ... ... sally ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.passwordManagerName" ... ... Plain Text ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.password" ... ... 123 ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.title" ... ... Sally ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------5110544421083023415453147877-- ... """)) HTTP/1.1 303 See Other ... >>> print(http(r""" ... POST /++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 780 ... Content-Type: multipart/form-data; boundary=---------------------------5110544421083023415453147877 ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.login" ... ... george ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.passwordManagerName" ... ... Plain Text ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.password" ... ... 123 ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.title" ... ... George ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------5110544421083023415453147877-- ... """)) HTTP/1.1 303 See Other ... >>> print(http(r""" ... POST /++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 780 ... Content-Type: multipart/form-data; boundary=---------------------------5110544421083023415453147877 ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.login" ... ... mike ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.passwordManagerName" ... ... Plain Text ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.password" ... ... 123 ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.title" ... ... Mike ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------5110544421083023415453147877-- ... """)) HTTP/1.1 303 See Other ... >>> print(http(r""" ... POST /++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 780 ... Content-Type: multipart/form-data; boundary=---------------------------5110544421083023415453147877 ... Cookie: zope3_cs_6a553b3=-j7C3CdeW9sUK8BP5x97u2d9o242xMJDzJd8HCQ5AAi9xeFcGTFkAs ... Referer: http://localhost/++etc++site/default/PAU/users/+/AddPrincipalInformation.html%3D ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.login" ... ... mary ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.passwordManagerName" ... ... Plain Text ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.password" ... ... 123 ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.title" ... ... Mary ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------5110544421083023415453147877 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------5110544421083023415453147877-- ... """)) HTTP/1.1 303 See Other ... Next, We'll add out group folder plugin in PAU. >>> print(http(r""" ... POST /++etc++site/default/PAU/+/AddGroupFolder.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 427 ... Content-Type: multipart/form-data; boundary=---------------------------4150524541658557772058105275 ... Referer: http://localhost/++etc++site/default/PAU/+/AddGroupFolder.html= ... ... -----------------------------4150524541658557772058105275 ... Content-Disposition: form-data; name="field.prefix" ... ... groups ... -----------------------------4150524541658557772058105275 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------4150524541658557772058105275 ... Content-Disposition: form-data; name="add_input_name" ... ... groups ... -----------------------------4150524541658557772058105275-- ... """)) HTTP/1.1 303 See Other ... Next we'll select the credentials and authenticators for the PAU: >>> print(http(r""" ... POST /++etc++site/default/PAU/@@configure.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 1313 ... Content-Type: multipart/form-data; boundary=---------------------------2026736768606413562109112352 ... Referer: http://localhost/++etc++site/default/PAU/@@configure.html ... ... -----------------------------2026736768606413562109112352 ... Content-Disposition: form-data; name="field.credentialsPlugins.to" ... ... U2Vzc2lvbiBDcmVkZW50aWFscw== ... -----------------------------2026736768606413562109112352 ... Content-Disposition: form-data; name="field.credentialsPlugins-empty-marker" ... ... ... -----------------------------2026736768606413562109112352 ... Content-Disposition: form-data; name="field.authenticatorPlugins.to" ... ... dXNlcnM= ... -----------------------------2026736768606413562109112352 ... Content-Disposition: form-data; name="field.authenticatorPlugins.to" ... ... Z3JvdXBz ... -----------------------------2026736768606413562109112352 ... Content-Disposition: form-data; name="field.authenticatorPlugins-empty-marker" ... ... ... -----------------------------2026736768606413562109112352 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Change ... -----------------------------2026736768606413562109112352 ... Content-Disposition: form-data; name="field.credentialsPlugins" ... ... U2Vzc2lvbiBDcmVkZW50aWFscw== ... -----------------------------2026736768606413562109112352 ... Content-Disposition: form-data; name="field.authenticatorPlugins" ... ... dXNlcnM= ... -----------------------------2026736768606413562109112352 ... Content-Disposition: form-data; name="field.authenticatorPlugins" ... ... Z3JvdXBz ... -----------------------------2026736768606413562109112352-- ... """)) HTTP/1.1 200 Ok ... Now, we can define some groups. Let's start with a group named "Admin": >>> print(http(r""" ... POST /++etc++site/default/PAU/groups/+/AddGroupInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 550 ... Content-Type: multipart/form-data; boundary=---------------------------20619400354342370301249668954 ... Referer: http://localhost/++etc++site/default/PAU/groups/+/AddGroupInformation.html= ... ... -----------------------------20619400354342370301249668954 ... Content-Disposition: form-data; name="field.title" ... ... Admin ... -----------------------------20619400354342370301249668954 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------20619400354342370301249668954 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------20619400354342370301249668954 ... Content-Disposition: form-data; name="add_input_name" ... ... admin ... -----------------------------20619400354342370301249668954-- ... """)) HTTP/1.1 303 See Other ... That includes Betty, Mary and Mike: >>> print(http(r""" ... POST /++etc++site/default/PAU/groups/admin/@@edit.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 1509 ... Content-Type: multipart/form-data; boundary=---------------------------6981402699601872602121555350 ... Referer: http://localhost/++etc++site/default/PAU/groups/admin/@@edit.html ... ... -----------------------------6981402699601872602121555350 ... Content-Disposition: form-data; name="field.title" ... ... Admin ... -----------------------------6981402699601872602121555350 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------6981402699601872602121555350 ... Content-Disposition: form-data; name="field.principals.displayed" ... ... y ... -----------------------------6981402699601872602121555350 ... Content-Disposition: form-data; name="field.principals.MC51c2Vycw__.query.field.search" ... ... ... -----------------------------6981402699601872602121555350 ... Content-Disposition: form-data; name="field.principals:list" ... ... dXNlcnMz ... -----------------------------6981402699601872602121555350 ... Content-Disposition: form-data; name="field.principals:list" ... ... dXNlcnM3 ... -----------------------------6981402699601872602121555350 ... Content-Disposition: form-data; name="field.principals:list" ... ... dXNlcnM2 ... -----------------------------6981402699601872602121555350 ... Content-Disposition: form-data; name="field.principals.MC51c2Vycw__.apply" ... ... Apply ... -----------------------------6981402699601872602121555350 ... Content-Disposition: form-data; name="field.principals.MC5ncm91cHM_.query.field.search" ... ... ... -----------------------------6981402699601872602121555350 ... Content-Disposition: form-data; name="field.principals.MQ__.query.searchstring" ... ... ... -----------------------------6981402699601872602121555350-- ... """)) HTTP/1.1 200 Ok ... and a group "Power Users" >>> print(http(r""" ... POST /++etc++site/default/PAU/groups/+/AddGroupInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 561 ... Content-Type: multipart/form-data; boundary=---------------------------168380148515549442351132560943 ... Referer: http://localhost/++etc++site/default/PAU/groups/+/AddGroupInformation.html= ... ... -----------------------------168380148515549442351132560943 ... Content-Disposition: form-data; name="field.title" ... ... Power Users ... -----------------------------168380148515549442351132560943 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------168380148515549442351132560943 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------168380148515549442351132560943 ... Content-Disposition: form-data; name="add_input_name" ... ... power ... -----------------------------168380148515549442351132560943-- ... """)) HTTP/1.1 303 See Other ... with Bill and Betty as members: >>> print(http(r""" ... POST /++etc++site/default/PAU/groups/power/@@edit.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 1729 ... Content-Type: multipart/form-data; boundary=---------------------------181944013812647128322134918391 ... Referer: http://localhost/++etc++site/default/PAU/groups/power/@@edit.html ... ... -----------------------------181944013812647128322134918391 ... Content-Disposition: form-data; name="field.title" ... ... Power Users ... -----------------------------181944013812647128322134918391 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------181944013812647128322134918391 ... Content-Disposition: form-data; name="field.principals:list" ... ... dXNlcnMz ... -----------------------------181944013812647128322134918391 ... Content-Disposition: form-data; name="field.principals:list" ... ... dXNlcnMy ... -----------------------------181944013812647128322134918391 ... Content-Disposition: form-data; name="field.principals.displayed" ... ... y ... -----------------------------181944013812647128322134918391 ... Content-Disposition: form-data; name="field.principals.MC51c2Vycw__.query.field.search" ... ... ... -----------------------------181944013812647128322134918391 ... Content-Disposition: form-data; name="field.principals.MC5ncm91cHM_.query.field.search" ... ... ... -----------------------------181944013812647128322134918391 ... Content-Disposition: form-data; name="field.principals.MQ__.query.searchstring" ... ... ... -----------------------------181944013812647128322134918391 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Change ... -----------------------------181944013812647128322134918391-- ... """)) HTTP/1.1 200 Ok ... Now, with these groups set up, we should see these groups on the affected principals. First, we'll make the root folder the thread-local site: >>> from zope.component.hooks import setSite >>> setSite(getRootFolder()) and we'll get the pluggable authentication utility: >>> from zope.authentication.interfaces import IAuthentication >>> from zope.component import getUtility >>> principals = getUtility(IAuthentication) Finally we'll get Betty and see that she is in the admin and power-user groups: >>> betty = principals.getPrincipal(u'users3') >>> betty.groups.sort() >>> betty.groups ['groupspower', 'zope.Authenticated', 'zope.Everybody'] And we'll get Bill, and see that he is only in the power-user group: >>> bill = principals.getPrincipal(u'users2') >>> bill.groups ['zope.Everybody', 'zope.Authenticated', 'groupspower']
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/groupfolder.rst
groupfolder.rst
from datetime import datetime from zope.component import getUtilitiesFor from zope.component import getUtility from zope.exceptions.interfaces import UserError from zope.i18n import translate from zope.i18nmessageid import ZopeMessageFactory as _ from zope.interface import implementer from zope.security.interfaces import IPermission from zope.securitypolicy.interfaces import Allow from zope.securitypolicy.interfaces import Deny from zope.securitypolicy.interfaces import IRole from zope.securitypolicy.interfaces import IRolePermissionManager from zope.securitypolicy.interfaces import Unset class RolePermissionView: _pagetip = _("""For each permission you want to grant (or deny) to a role, set the entry for that permission and role to a '+' (or '-'). Permissions are shown on the left side, going down. Roles are shown accross the top. """) request = None context = None _roles = None _permissions = None def pagetip(self): return translate(self._pagetip, context=self.request) def roles(self): roles = getattr(self, '_roles', None) if roles is None: roles = [ (translate(role.title, context=self.request).strip(), role) for name, role in getUtilitiesFor(IRole)] roles.sort() roles = self._roles = [role for name, role in roles] return roles def permissions(self): permissions = getattr(self, '_permissions', None) if permissions is None: permissions = [ (translate(perm.title, context=self.request).strip(), perm) for name, perm in getUtilitiesFor(IPermission) if name != 'zope.Public'] permissions.sort() permissions = self._permissions = [perm for name, perm in permissions] return permissions def availableSettings(self, noacquire=False): aq = {'id': Unset.getName(), 'shorttitle': ' ', 'title': _('permission-acquire', 'Acquire')} rest = [{'id': Allow.getName(), 'shorttitle': '+', 'title': _('permission-allow', 'Allow')}, {'id': Deny.getName(), 'shorttitle': '-', 'title': _('permission-deny', 'Deny')}, ] return rest if noacquire else [aq] + rest def permissionRoles(self): context = self.context.__parent__ roles = self.roles() return [PermissionRoles(permission, context, roles) for permission in self.permissions()] def permissionForID(self, pid): roles = self.roles() perm = getUtility(IPermission, pid) return PermissionRoles(perm, self.context.__parent__, roles) def roleForID(self, rid): permissions = self.permissions() role = getUtility(IRole, rid) return RolePermissions(role, self.context.__parent__, permissions) def update(self, testing=None): status = '' changed = False if 'SUBMIT' in self.request: roles = [r.id for r in self.roles()] permissions = [p.id for p in self.permissions()] prm = IRolePermissionManager(self.context.__parent__) for ip in range(len(permissions)): rperm = self.request.get("p%s" % ip) if rperm not in permissions: continue for ir in range(len(roles)): rrole = self.request.get("r%s" % ir) if rrole not in roles: continue setting = self.request.get("p{}r{}".format(ip, ir), None) if setting is not None: if setting == Unset.getName(): prm.unsetPermissionFromRole(rperm, rrole) elif setting == Allow.getName(): prm.grantPermissionToRole(rperm, rrole) elif setting == Deny.getName(): prm.denyPermissionToRole(rperm, rrole) else: raise ValueError("Incorrect setting: %s" % setting) # pragma: no cover changed = True if 'SUBMIT_PERMS' in self.request: prm = IRolePermissionManager(self.context.__parent__) roles = self.roles() rperm = self.request.get('permission_id') settings = self.request.get('settings', ()) for ir in range(len(roles)): rrole = roles[ir].id setting = settings[ir] if setting == Unset.getName(): prm.unsetPermissionFromRole(rperm, rrole) elif setting == Allow.getName(): prm.grantPermissionToRole(rperm, rrole) elif setting == Deny.getName(): prm.denyPermissionToRole(rperm, rrole) else: raise ValueError("Incorrect setting: %s" % setting) changed = True if 'SUBMIT_ROLE' in self.request: role_id = self.request.get('role_id') prm = IRolePermissionManager(self.context.__parent__) allowed = self.request.get(Allow.getName(), ()) denied = self.request.get(Deny.getName(), ()) for permission in self.permissions(): rperm = permission.id if rperm in allowed and rperm in denied: permission_translated = translate( permission.title, context=self.request) msg = _('You choose both allow and deny for permission' ' "${permission}". This is not allowed.', mapping={'permission': permission_translated}) raise UserError(msg) if rperm in allowed: prm.grantPermissionToRole(rperm, role_id) elif rperm in denied: prm.denyPermissionToRole(rperm, role_id) else: prm.unsetPermissionFromRole(rperm, role_id) changed = True if changed: formatter = self.request.locale.dates.getFormatter( 'dateTime', 'medium') status = _("Settings changed at ${date_time}", mapping={'date_time': formatter.format(datetime.utcnow())}) return status @implementer(IPermission) class PermissionRoles: def __init__(self, permission, context, roles): self._permission = permission self._context = context self._roles = roles @property def id(self): return self._permission.id @property def title(self): return self._permission.title @property def description(self): return self._permission.description def roleSettings(self): """ Returns the list of setting names of each role for this permission. """ prm = IRolePermissionManager(self._context) proles = prm.getRolesForPermission(self._permission.id) settings = {} for role, setting in proles: settings[role] = setting.getName() nosetting = Unset.getName() return [settings.get(role.id, nosetting) for role in self._roles] @implementer(IRole) class RolePermissions: def __init__(self, role, context, permissions): self._role = role self._context = context self._permissions = permissions @property def id(self): return self._role.id @property def title(self): return self._role.title @property def description(self): return self._role.description def permissionsInfo(self): prm = IRolePermissionManager(self._context) rperms = prm.getPermissionsForRole(self._role.id) settings = {} for permission, setting in rperms: settings[permission] = setting.getName() nosetting = Unset.getName() return [{'id': permission.id, 'title': permission.title, 'setting': settings.get(permission.id, nosetting)} for permission in self._permissions]
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/rolepermissionview.py
rolepermissionview.py
http://www.zope.org/Collectors/Zope3-dev/663 ============================================ Two plugins(basic-auth and session credentials) link on PAU add menu are broken and can't add them. For IPluggableAuthentication, "plugins.html" is a correct view name but "contents.html" is used. because menu implementation supporsing that all view uses "zope.app.container.browser.contents.Contents" are named "contents.html". In Zope3.2, PluggableAuthentication inherits SiteManagementFolder that provides "contents.html" view. >>> from zope.testbrowser.wsgi import Browser >>> browser = Browser() Create a pau >>> browser.addHeader('Authorization', 'Basic mgr:mgrpw') >>> browser.open('http://localhost/@@contents.html') >>> browser.getLink('Pluggable Authentication Utility').click() >>> browser.getControl(name='add_input_name').value = 'auth' >>> browser.getControl('Add').click() >>> browser.getLink('auth').click() Go to the plugins view >>> browser.getLink('Plugins').click() Add aa basic auth plugin >>> browser.getLink('HTTP Basic-Auth Plugin').click() >>> browser.getControl(name='new_value').value = 'basic' >>> browser.getControl('Apply').click() Add a session-credential plugin >>> browser.getLink('Session Credentials Plugin').click() >>> browser.getControl(name='new_value').value = 'session' >>> browser.getControl('Apply').click() Make sure we can use them: >>> browser.getLink('Configure').click() >>> browser.getControl(name='field.credentialsPlugins.from').value = [ ... 'Wm9wZSBSZWFsbSBCYXNpYy1BdXRo'] >>> browser.getControl(name='field.credentialsPlugins.from').value = [ ... 'YmFzaWM='] >>> browser.getControl(name='field.credentialsPlugins.from').value = [ ... 'U2Vzc2lvbiBDcmVkZW50aWFscw=='] >>> browser.getControl('Change').click()
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/issue663.rst
issue663.rst
__docformat__ = "reStructuredText" from zope.formlib.interfaces import IInputWidget from zope.formlib.interfaces import InputErrors from zope.formlib.interfaces import ISourceQueryView from zope.formlib.interfaces import MissingInputError from zope.formlib.interfaces import WidgetsError from zope.formlib.utility import setUpWidgets from zope.i18n import translate from zope.interface import implementer from zope.schema import getFieldsInOrder from zope.traversing.api import getName from zope.traversing.api import getPath from zope.app.authentication.i18n import ZopeMessageFactory as _ search_label = _('search-button', 'Search') source_label = _("Source path") source_title = _("Path to the source utility") @implementer(ISourceQueryView) class QuerySchemaSearchView: def __init__(self, context, request): self.context = context self.request = request def render(self, name): schema = self.context.schema sourcename = getName(self.context) sourcepath = getPath(self.context) setUpWidgets(self, schema, IInputWidget, prefix=name+'.field') html = [] # add sub title for source search field html.append('<h4>%s</h4>' % sourcename) # start row for path display field html.append('<div class="row">') # for each source add path of source html.append(' <div class="label">') label = translate(source_label, context=self.request) title = translate(source_title, context=self.request) html.append(f' <label for="{sourcename}" title="{title}">') html.append(' %s' % label) html.append(' </label>') html.append(' </div>') html.append(' <div class="field">') html.append(' %s' % sourcepath) html.append(' </div>') html.append('</div>') # start row for search fields html.append('<div class="row">') for field_name, _field in getFieldsInOrder(schema): widget = getattr(self, field_name+'_widget') # for each field add label... html.append(' <div class="label">') html.append(' <label for="%s" title="%s">' % (widget.name, widget.hint)) html.append(' %s' % widget.label) html.append(' </label>') html.append(' </div>') # ...and field widget html.append(' <div class="field">') html.append(' %s' % widget()) if widget.error(): # pragma: no cover html.append(' <div class="error">') html.append(' %s' % widget.error()) html.append(' </div>') html.append(' </div>') # end row html.append('</div>') # add search button for search fields html.append('<div class="row">') html.append(' <div class="field">') html.append(' <input type="submit" name="%s" value="%s" />' % (name + '.search', translate(search_label, context=self.request))) html.append(' </div>') html.append('</div>') return '\n'.join(html) def results(self, name): if (name + '.search') not in self.request: return None schema = self.context.schema setUpWidgets(self, schema, IInputWidget, prefix=name + '.field') # XXX inline the original getWidgetsData call in # zope.app.form.utility to lift the dependency on zope.app.form. data = {} errors = [] for widget_name, field in getFieldsInOrder(schema): widget = getattr(self, widget_name + '_widget') if IInputWidget.providedBy(widget): if widget.hasInput(): try: data[widget_name] = widget.getInputValue() except InputErrors as error: # pragma: no cover errors.append(error) elif field.required: # pragma: no cover errors.append(MissingInputError( widget_name, widget.label, 'the field is required')) if errors: # pragma: no cover raise WidgetsError(errors, widgetsData=data) return self.context.search(data)
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/schemasearch.py
schemasearch.py
We can search group folder with an empty string. We'll add a pluggable authentication utility: >>> print(http(r""" ... POST /++etc++site/default/@@contents.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 98 ... Content-Type: application/x-www-form-urlencoded ... Referer: http://localhost/++etc++site/default/@@contents.html?type_name=BrowserAdd__zope.pluggableauth.authentication.PluggableAuthentication ... ... type_name=BrowserAdd__zope.pluggableauth.authentication.PluggableAuthentication&new_value=PAU""")) HTTP/1.1 303 See Other ... And register it: >>> print(http(r""" ... POST /++etc++site/default/PAU/addRegistration.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 699 ... Content-Type: multipart/form-data; boundary=---------------------------191720529414243436931796477300 ... Referer: http://localhost/++etc++site/default/PAU/addRegistration.html ... ... -----------------------------191720529414243436931796477300 ... Content-Disposition: form-data; name="field.comment" ... ... ... -----------------------------191720529414243436931796477300 ... Content-Disposition: form-data; name="field.actions.register" ... ... Register ... -----------------------------191720529414243436931796477300-- ... """)) HTTP/1.1 303 See Other ... Next, we'll add the group folder: >>> print(http(r""" ... POST /++etc++site/default/PAU/+/AddGroupFolder.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 427 ... Content-Type: multipart/form-data; boundary=---------------------------4150524541658557772058105275 ... Referer: http://localhost/++etc++site/default/PAU/+/AddGroupFolder.html= ... ... -----------------------------4150524541658557772058105275 ... Content-Disposition: form-data; name="field.prefix" ... ... groups ... -----------------------------4150524541658557772058105275 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------4150524541658557772058105275 ... Content-Disposition: form-data; name="add_input_name" ... ... groups ... -----------------------------4150524541658557772058105275-- ... """)) HTTP/1.1 303 See Other ... And add some groups: >>> print(http(r""" ... POST /++etc++site/default/PAU/groups/+/AddGroupInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 550 ... Content-Type: multipart/form-data; boundary=---------------------------12719796373012316301953477158 ... Referer: http://localhost/++etc++site/default/PAU/groups/+/AddGroupInformation.html= ... ... -----------------------------12719796373012316301953477158 ... Content-Disposition: form-data; name="field.title" ... ... Test1 ... -----------------------------12719796373012316301953477158 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------12719796373012316301953477158 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------12719796373012316301953477158 ... Content-Disposition: form-data; name="add_input_name" ... ... Test1 ... -----------------------------12719796373012316301953477158-- ... """)) HTTP/1.1 303 See Other ... >>> print(http(r""" ... POST /++etc++site/default/PAU/groups/+/AddGroupInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 550 ... Content-Type: multipart/form-data; boundary=---------------------------10816732208483809451400699513 ... Referer: http://localhost/++etc++site/default/PAU/groups/+/AddGroupInformation.html= ... ... -----------------------------10816732208483809451400699513 ... Content-Disposition: form-data; name="field.title" ... ... Test2 ... -----------------------------10816732208483809451400699513 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------10816732208483809451400699513 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------10816732208483809451400699513 ... Content-Disposition: form-data; name="add_input_name" ... ... Test2 ... -----------------------------10816732208483809451400699513-- ... """)) HTTP/1.1 303 See Other ... Now we'll configure our pluggable-authentication utility to use the group folder: >>> print(http(r""" ... POST /++etc++site/default/PAU/@@configure.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 1040 ... Content-Type: multipart/form-data; boundary=---------------------------1786480431902757372789659730 ... Referer: http://localhost/++etc++site/default/PAU/@@configure.html ... ... -----------------------------1786480431902757372789659730 ... Content-Disposition: form-data; name="field.credentialsPlugins.to" ... ... U2Vzc2lvbiBDcmVkZW50aWFscw== ... -----------------------------1786480431902757372789659730 ... Content-Disposition: form-data; name="field.credentialsPlugins-empty-marker" ... ... ... -----------------------------1786480431902757372789659730 ... Content-Disposition: form-data; name="field.authenticatorPlugins.to" ... ... Z3JvdXBz ... -----------------------------1786480431902757372789659730 ... Content-Disposition: form-data; name="field.authenticatorPlugins-empty-marker" ... ... ... -----------------------------1786480431902757372789659730 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Change ... -----------------------------1786480431902757372789659730 ... Content-Disposition: form-data; name="field.credentialsPlugins" ... ... U2Vzc2lvbiBDcmVkZW50aWFscw== ... -----------------------------1786480431902757372789659730 ... Content-Disposition: form-data; name="field.authenticatorPlugins" ... ... Z3JvdXBz ... -----------------------------1786480431902757372789659730-- ... """)) HTTP/1.1 200 Ok ... Now, if we search for a group, but don't supply a string: >>> print(http(r""" ... POST /@@grant.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 166 ... Content-Type: application/x-www-form-urlencoded ... Referer: http://localhost/@@grant.html ... ... field.principal.displayed=y&""" ... "field.principal.MC5ncm91cHM_.field.search=&" ... "field.principal.MC5ncm91cHM_.search=Search&" ... "field.principal.MQ__.searchstring=")) HTTP/1.1 200 Ok ...Test1...Test2... We get both of our groups in the result.
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/group_searching_with_empty_string.rst
group_searching_with_empty_string.rst
Using Principal Folders ======================= Principal folders are Pluggable-Authentication plugins that manage principal information, especially authentication credentials. To use a principal folder, you need add a principal folder plugin to the PAU and to configure the PAU to use plugin. Let's look at an example, in which we'll define a new manager named Bob. Initially, attempts to log in as Bob fail: >>> from zope.testbrowser.wsgi import Browser >>> bob_browser = Browser() >>> bob_browser.handleErrors = True >>> bob_browser.raiseHttpErrors = False >>> bob_browser.addHeader("Authorization", "Basic Ym9iOjEyMw==") >>> bob_browser.open("http://localhost/+") >>> print(bob_browser.headers['status']) 401 Unauthorized To allow Bob to log in, we'll start by adding a principal folder to PAU: We need to create and register a pluggable authentication utility. >>> manager_browser = Browser() >>> manager_browser.handleErrors = False >>> manager_browser.addHeader("Authorization", "Basic bWdyOm1ncnB3") >>> manager_browser.post("http://localhost/++etc++site/default/@@contents.html", ... "type_name=BrowserAdd__zope.pluggableauth.authentication.PluggableAuthentication&new_value=PAU") >>> manager_browser.getLink("Registration").click() Register PAU. First we get the registration page: >>> manager_browser.getControl("Register this object").click() And then we can fill out and submit the form: >>> manager_browser.getControl("Register").click() Add a Principal folder plugin to PAU. Again, we get the page, and then submit the form: >>> manager_browser.getLink("Principal Folder").click() >>> manager_browser.getControl(name="field.prefix").value = "users" >>> manager_browser.getControl(name="add_input_name").value = "users" >>> manager_browser.getControl("Add").click() We specify a prefix, ``users``. This is used to make sure that ids used by this plugin don't conflict with ids of other plugins. We also name ths plugin ``users``. This is the name we'll use when we configure the pluggable authentiaction service. Next we'll view the contents page of the principal folder: >>> manager_browser.open("http://localhost/++etc++site/default/PAU/users/@@contents.html") >>> 'users' in manager_browser.contents True And we'll add a principal, Bob: >>> manager_browser.getLink("Principal Information").click() >>> manager_browser.getControl(name="field.login").value = 'bob' >>> manager_browser.getControl(name="field.passwordManagerName").value = 'SHA1' >>> manager_browser.getControl(name="field.password").value = 'bob' >>> manager_browser.getControl(name="field.title").value = 'Bob Smith' >>> manager_browser.getControl(name="field.description").value = 'This is Bob' >>> manager_browser.getControl(name="add_input_name").value = 'bob' >>> manager_browser.getControl(name="UPDATE_SUBMIT").click() >>> manager_browser.open("http://localhost/++etc++site/default/PAU/users/@@contents.html") >>> u'bob' in manager_browser.contents True Note that we didn't pick a name. The name, together with the folder prefix. If we don't choose a name, a numeric id is chosen. Now we have a principal folder with a principal. Configure PAU, with registered principal folder plugin and select any one credentials. Unfortunately, the option lists are computed dynamically in JavaScript, so we can't fill the form out directly. Instead we must send a complete POST body. We're choosing the users folder as the authenticator plugin, and the session utility as the credentials plugin. >>> manager_browser.open("http://localhost/++etc++site/default/PAU/@@configure.html") >>> manager_browser.post("http://localhost/++etc++site/default/PAU/@@configure.html", ... r"""UPDATE_SUBMIT=Change&field.credentialsPlugins=U2Vzc2lvbiBDcmVkZW50aWFscw==&field.authenticatorPlugins=dXNlcnM=""" ... """&field.credentialsPlugins.to=U2Vzc2lvbiBDcmVkZW50aWFscw==&field.authenticatorPlugins.to=dXNlcnM=""") Now, with this in place, Bob can log in (incidentally , if Bob accidentally sends two values for the ``camefrom`` parameter, only the first is respected): >>> bob_browser.open("/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F&camefrom=foo") >>> bob_browser.getControl(name="login").value = 'bob' >>> bob_browser.getControl(name="password").value = 'bob' >>> bob_browser.getControl(name="SUBMIT").click() >>> print(bob_browser.url) http://localhost/ However, Bob isn't allowed to access the management interface. When he attempts to do so, the PAU issues a challenge to let bob login as a different user: >>> bob_browser.open("/+") >>> print(bob_browser.url) http://localhost/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F%2B >>> 'not authorized' in bob_browser.contents True We go to the granting interface and search for and find a principal named Bob (the form control names are magic and generated by zope.formlib; this is searching the PAU): >>> manager_browser.open("/@@contents.html") >>> manager_browser.open("/@@grant.html") >>> '/++etc++site/default/PAU/users' in manager_browser.contents True >>> manager_browser.getControl(name="field.principal.MC51c2Vycw__.field.search").value = 'bob' >>> manager_browser.getControl(name='field.principal.MC51c2Vycw__.search').click() Once we've found him, we see what roles are available: >>> manager_browser.getControl(name="field.principal.MC51c2Vycw__.selection").displayValue = ['Bob Smith'] >>> manager_browser.getControl(name="field.principal.MC51c2Vycw__.apply").click() >>> 'Site Manager' in manager_browser.contents True We can grant Bob the manager role now: >>> allow = manager_browser.getControl(name='field.dXNlcnNib2I_.role.zope.Manager', index=0) >>> allow.value = ['allow'] >>> manager_browser.getControl(name="GRANT_SUBMIT", index=1).click() At which point, Bob can access the management interface: >>> bob_browser.open("http://localhost/@@contents.html") >>> print(bob_browser.url) http://localhost/@@contents.html
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/principalfolder.rst
principalfolder.rst
Granting View ============= The granting view allows the user to grant permissions and roles to principals. The view unfortunately depends on a lot of other components: - Roles >>> from zope.app.authentication.browser import tests as ztapi >>> from zope.securitypolicy.role import Role >>> from zope.securitypolicy.interfaces import IRole >>> ztapi.provideUtility(IRole, Role(u'role1', u'Role 1'), u'role1') >>> ztapi.provideUtility(IRole, Role(u'role2', u'Role 2'), u'role2') >>> ztapi.provideUtility(IRole, Role(u'role3', u'Role 3'), u'role3') - Permissions >>> from zope.security.permission import Permission >>> from zope.security.interfaces import IPermission >>> ztapi.provideUtility(IPermission, Permission(u'permission1', ... u'Permission 1'), u'permission1') >>> ztapi.provideUtility(IPermission, Permission(u'permission2', ... u'Permission 2'), u'permission2') >>> ztapi.provideUtility(IPermission, Permission(u'permission3', ... u'Permission 3'), u'permission3') - Authentication Utility >>> class Principal: ... def __init__(self, id, title): self.id, self.title = id, title >>> from zope.app.security.interfaces import IAuthentication >>> from zope.app.security.interfaces import PrincipalLookupError >>> from zope.interface import implementer >>> @implementer(IAuthentication) ... class AuthUtility(object): ... data = {'jim': Principal('jim', 'Jim Fulton'), ... 'stephan': Principal('stephan', 'Stephan Richter')} ... ... def getPrincipal(self, id): ... try: ... return self.data.get(id) ... except KeyError: ... raise PrincipalLookupError(id) ... ... def getPrincipals(self, search): ... return [principal ... for principal in self.data.values() ... if search in principal.title] >>> ztapi.provideUtility(IAuthentication, AuthUtility()) - Security-related Adapters >>> from zope.annotation.interfaces import IAnnotatable >>> from zope.securitypolicy.interfaces import IPrincipalRoleManager >>> from zope.securitypolicy.principalrole import \ ... AnnotationPrincipalRoleManager >>> ztapi.provideAdapter(IAnnotatable, IPrincipalRoleManager, ... AnnotationPrincipalRoleManager) >>> from zope.securitypolicy.interfaces import \ ... IPrincipalPermissionManager >>> from zope.securitypolicy.principalpermission import \ ... AnnotationPrincipalPermissionManager >>> ztapi.provideAdapter(IAnnotatable, IPrincipalPermissionManager, ... AnnotationPrincipalPermissionManager) - Vocabulary Choice Widgets >>> from zope.schema.interfaces import IChoice >>> from zope.formlib.interfaces import IInputWidget >>> from zope.formlib.widgets import ChoiceInputWidget >>> ztapi.browserViewProviding(IChoice, ChoiceInputWidget, IInputWidget) >>> from zope.schema.interfaces import IVocabularyTokenized >>> from zope.publisher.interfaces.browser import IBrowserRequest >>> from zope.formlib.widgets import DropdownWidget >>> ztapi.provideMultiView((IChoice, IVocabularyTokenized), ... IBrowserRequest, IInputWidget, '', ... DropdownWidget) - Support Views for the Principal Source Widget >>> from zope.app.security.interfaces import IPrincipalSource >>> from zope.app.security.browser.principalterms import PrincipalTerms >>> from zope.browser.interfaces import ITerms >>> ztapi.browserViewProviding(IPrincipalSource, PrincipalTerms, ITerms) >>> from zope.app.security.browser.auth import AuthUtilitySearchView >>> from zope.formlib.interfaces import ISourceQueryView >>> ztapi.browserViewProviding(IAuthentication, ... AuthUtilitySearchView, ... ISourceQueryView) >>> from zope.schema.interfaces import ISource >>> from zope.formlib.source import SourceInputWidget >>> ztapi.provideMultiView((IChoice, ISource), IBrowserRequest, ... IInputWidget, '', SourceInputWidget) - Attribute Annotatable Adapter >>> from zope.app.authentication import tests as setup >>> setup.setUpAnnotations() >>> setup.setUpSiteManagerLookup() - Content Object >>> from zope.annotation.interfaces import IAttributeAnnotatable >>> @implementer(IAttributeAnnotatable) ... class Content(object): ... __annotations__ = {} (This is Jim's understanding of a "easy" setup!) Now that we have all the components we need, let's create *the* view. >>> ob = Content() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> from zope.app.authentication.browser.granting import Granting >>> view = Granting(ob, request) If we call status, we get nothing and the view's principal attribute is `None`: >>> print(view.status()) <BLANKLINE> >>> view.principal Since we have not selected a principal, we have no role or permission widgets: >>> getattr(view, 'roles', None) >>> getattr(view, 'permissions', None) Now that we have a selected principal, then >>> view.request.form['field.principal.displayed'] = 'y' >>> view.request.form['field.principal'] = 'amlt' (Yes, 'amlt' is the base 64 code for 'jim'.) >>> print(view.status()) <BLANKLINE> and now the `view.principal` is set: >>> print(view.principal) jim Now we should have a list of role and permission widgets, and all of them should be unset, because do not have any settings for 'jim'. >>> [str(role.context.title) for role in view.roles] ['Role 1', 'Role 2', 'Role 3'] >>> [str(perm.context.title) for perm in view.permissions] ['Permission 1', 'Permission 2', 'Permission 3'] Now we change some settings and submit the form: >>> from zope.securitypolicy.interfaces import Allow, Deny, Unset >>> view.request.form['field.amlt.role.role1'] = 'unset' >>> view.request.form['field.amlt.role.role1-empty-makrer'] = 1 >>> view.request.form['field.amlt.role.role2'] = 'allow' >>> view.request.form['field.amlt.role.role2-empty-makrer'] = 1 >>> view.request.form['field.amlt.role.role3'] = 'deny' >>> view.request.form['field.amlt.role.role3-empty-makrer'] = 1 >>> view.request.form['field.amlt.permission.permission1'] = 'unset' >>> view.request.form['field.amlt.permission.permission1-empty-makrer'] = 1 >>> view.request.form['field.amlt.permission.permission2'] = 'allow' >>> view.request.form['field.amlt.permission.permission2-empty-makrer'] = 1 >>> view.request.form['field.amlt.permission.permission3'] = 'deny' >>> view.request.form['field.amlt.permission.permission3-empty-makrer'] = 1 >>> view.request.form['GRANT_SUBMIT'] = 'Submit' If we get the status now, the data should be written and a status message should be returned: >>> print(view.status()) Grants updated. >>> roles = IPrincipalRoleManager(ob) >>> roles.getSetting('role1', 'jim') is Unset True >>> roles.getSetting('role2', 'jim') is Allow True >>> roles.getSetting('role3', 'jim') is Deny True >>> roles = IPrincipalPermissionManager(ob) >>> roles.getSetting('permission1', 'jim') is Unset True >>> roles.getSetting('permission2', 'jim') is Allow True >>> roles.getSetting('permission3', 'jim') is Deny True
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/granting.rst
granting.rst
================================ Using a PAU Prefix and Searching ================================ This test confirms that both principals and groups can be searched for in PAUs that have prefixes. First we'll create a PAU with a prefix of `pau1_` and and register: >>> print(http(r""" ... POST /++etc++site/default/+/AddPluggableAuthentication.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 372 ... Content-Type: multipart/form-data; boundary=---------------------------318183180122653 ... ... -----------------------------318183180122653 ... Content-Disposition: form-data; name="field.prefix" ... ... pau1_ ... -----------------------------318183180122653 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------318183180122653 ... Content-Disposition: form-data; name="add_input_name" ... ... PAU1 ... -----------------------------318183180122653-- ... """)) HTTP/1.1 303 See Other ... >>> print(http(r""" ... POST /++etc++site/default/PAU1/addRegistration.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 591 ... Content-Type: multipart/form-data; boundary=---------------------------516441125097 ... ... -----------------------------516441125097 ... Content-Disposition: form-data; name="field.comment" ... ... ... -----------------------------516441125097 ... Content-Disposition: form-data; name="field.actions.register" ... ... Register ... -----------------------------516441125097-- ... """)) HTTP/1.1 303 See Other ... Next we'll create and register a principal folder: >>> print(http(r""" ... POST /++etc++site/default/PAU1/+/AddPrincipalFolder.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 374 ... Content-Type: multipart/form-data; boundary=---------------------------266241536215161 ... ... -----------------------------266241536215161 ... Content-Disposition: form-data; name="field.prefix" ... ... users_ ... -----------------------------266241536215161 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------266241536215161 ... Content-Disposition: form-data; name="add_input_name" ... ... Users ... -----------------------------266241536215161-- ... """)) HTTP/1.1 303 See Other ... and add a principal that we'll later search for: >>> print(http(r""" ... POST /++etc++site/default/PAU1/Users/+/AddPrincipalInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 686 ... Content-Type: multipart/form-data; boundary=---------------------------300171485226567 ... ... -----------------------------300171485226567 ... Content-Disposition: form-data; name="field.login" ... ... bob ... -----------------------------300171485226567 ... Content-Disposition: form-data; name="field.passwordManagerName" ... ... Plain Text ... -----------------------------300171485226567 ... Content-Disposition: form-data; name="field.password" ... ... bob ... -----------------------------300171485226567 ... Content-Disposition: form-data; name="field.title" ... ... Bob ... -----------------------------300171485226567 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------300171485226567 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------300171485226567 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------300171485226567-- ... """)) HTTP/1.1 303 See Other ... Next, we'll add and register a group folder: >>> print(http(r""" ... POST /++etc++site/default/PAU1/+/AddGroupFolder.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 372 ... Content-Type: multipart/form-data; boundary=---------------------------17420126702455 ... ... -----------------------------17420126702455 ... Content-Disposition: form-data; name="field.prefix" ... ... groups_ ... -----------------------------17420126702455 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------17420126702455 ... Content-Disposition: form-data; name="add_input_name" ... ... Groups ... -----------------------------17420126702455-- ... """)) HTTP/1.1 303 See Other ... and add a group to search for: >>> print(http(r""" ... POST /++etc++site/default/PAU1/Groups/+/AddGroupInformation.html%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 485 ... Content-Type: multipart/form-data; boundary=---------------------------323081358415654 ... ... -----------------------------323081358415654 ... Content-Disposition: form-data; name="field.title" ... ... Nice People ... -----------------------------323081358415654 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------323081358415654 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------323081358415654 ... Content-Disposition: form-data; name="add_input_name" ... ... nice ... -----------------------------323081358415654-- ... """)) HTTP/1.1 303 See Other ... Since we're only searching in this test, we won't bother to add anyone to the group. Before we search, we need to register the two authenticator plugins with the PAU: >>> print(http(r""" ... POST /++etc++site/default/PAU1/@@configure.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 888 ... Content-Type: multipart/form-data; boundary=---------------------------610310492754 ... ... -----------------------------610310492754 ... Content-Disposition: form-data; name="field.credentialsPlugins-empty-marker" ... ... ... -----------------------------610310492754 ... Content-Disposition: form-data; name="field.authenticatorPlugins.to" ... ... R3JvdXBz ... -----------------------------610310492754 ... Content-Disposition: form-data; name="field.authenticatorPlugins.to" ... ... VXNlcnM= ... -----------------------------610310492754 ... Content-Disposition: form-data; name="field.authenticatorPlugins-empty-marker" ... ... ... -----------------------------610310492754 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Change ... -----------------------------610310492754 ... Content-Disposition: form-data; name="field.authenticatorPlugins" ... ... R3JvdXBz ... -----------------------------610310492754 ... Content-Disposition: form-data; name="field.authenticatorPlugins" ... ... VXNlcnM= ... -----------------------------610310492754-- ... """)) HTTP/1.1 200 Ok ... Now we'll use the 'grant' interface of the root folder to search for all of the available groups: >>> print(http(r""" ... POST /@@grant.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 191 ... Content-Type: application/x-www-form-urlencoded ... ... field.principal.displayed=y&""" ... "field.principal.MC5Hcm91cHM_.field.search=&" ... "field.principal.MC5Hcm91cHM_.search=Search&" ... "field.principal.MC5Vc2Vycw__.field.search=&" ... "field.principal.MQ__.searchstring=")) HTTP/1.1 200 Ok ... <select name="field.principal.MC5Hcm91cHM_.selection"> <option value="cGF1MV9ncm91cHNfbmljZQ__">Nice People</option> </select> ... Note in the results that the dropdown box (i.e. the select element) has the single group 'Nice People' that we added earlier. Next, we'll use the same 'grant' interface to search for all of the available principals: >>> print(http(r""" ... POST /@@grant.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 255 ... Content-Type: application/x-www-form-urlencoded ... ... field.principal.displayed=y&""" ... "field.principal.MC5Hcm91cHM_.field.search=&" ... "field.principal.MC5Hcm91cHM_.selection=cGF1MV9ncm91cHNfbmljZQ__&" ... "field.principal.MC5Vc2Vycw__.field.search=&" ... "field.principal.MC5Vc2Vycw__.search=Search&" ... "field.principal.MQ__.searchstring=")) HTTP/1.1 200 Ok ... <select name="field.principal.MC5Vc2Vycw__.selection"> <option value="cGF1MV91c2Vyc18x">Bob</option> </select> ... Note here the dropdown contains Bob, the principal we added earlier.
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/pau_prefix_and_searching.rst
pau_prefix_and_searching.rst
__docformat__ = "reStructuredText" import base64 import zope.schema from zope.authentication.principal import PrincipalSource from zope.component import getUtilitiesFor from zope.formlib.interfaces import IInputWidget from zope.formlib.interfaces import MissingInputError from zope.formlib.utility import setUpWidget from zope.formlib.widget import renderElement from zope.formlib.widgets import RadioWidget from zope.i18nmessageid import ZopeMessageFactory as _ from zope.schema.vocabulary import SimpleTerm from zope.security.interfaces import IPermission from zope.securitypolicy.interfaces import Allow from zope.securitypolicy.interfaces import Deny from zope.securitypolicy.interfaces import IPrincipalPermissionManager from zope.securitypolicy.interfaces import IPrincipalRoleManager from zope.securitypolicy.interfaces import IRole from zope.securitypolicy.interfaces import Unset from zope.securitypolicy.vocabulary import GrantVocabulary try: text_type = unicode except NameError: text_type = str settings_vocabulary = GrantVocabulary([ SimpleTerm(Allow, token="allow", title=_('Allow')), SimpleTerm(Unset, token="unset", title=_('Unset')), SimpleTerm(Deny, token='deny', title=_('Deny')), ]) class GrantWidget(RadioWidget): """Grant widget for building a colorized matrix. The matrix shows anytime the status if you edit the radio widgets. This special widget shows the radio input field without labels. The labels are added in the header of the table. The order of the radio input fields is 'Allowed', 'Unset', 'Deny'. """ orientation = "horizontal" _tdTemplate = ( '\n<td class="%s">\n<center>\n<label for="%s" title="%s">\n' '%s\n</label>\n</center>\n</td>\n' ) def __call__(self): """See IBrowserWidget.""" value = self._getFormValue() return self.renderValue(value) def renderItem(self, index, text, value, name, cssClass): """Render an item of the list. Revert the order of label and text. Added field id to the lable attribute. Added tabel td tags for fit in the matrix table. """ tdClass = '' id = '{}.{}'.format(name, index) elem = renderElement('input', value=value, name=name, id=id, cssClass=cssClass, type='radio', extra='onclick="changeMatrix(this);"') return self._tdTemplate % (tdClass, id, text, elem) def renderSelectedItem(self, index, text, value, name, cssClass): """Render a selected item of the list. Revert the order of label and text. Added field id to the lable attribute. """ tdClass = 'default' id = '{}.{}'.format(name, index) elem = renderElement('input', value=value, name=name, id=id, cssClass=cssClass, checked="checked", type='radio', extra='onclick="changeMatrix(this);"') return self._tdTemplate % (tdClass, id, text, elem) def renderItems(self, value): # check if we want to select first item, the previously selected item # or the "no value" item. if (value == self.context.missing_value and getattr(self, 'firstItem', False) and len(self.vocabulary) > 0): if self.context.required: # Grab the first item from the iterator: values = [next(iter(self.vocabulary)).value] elif value != self.context.missing_value: values = [value] else: values = [] items = self.renderItemsWithValues(values) return items def renderValue(self, value): rendered_items = self.renderItems(value) return " ".join(rendered_items) class Granting: principal = None principal_field = zope.schema.Choice( __name__='principal', source=PrincipalSource(), required=True) def __init__(self, context, request): self.context = context self.request = request self.permissions = None self.roles = None self.principal_widget = None def status(self): setUpWidget(self, 'principal', self.principal_field, IInputWidget) if not self.principal_widget.hasInput(): return '' try: principal = self.principal_widget.getInputValue() except MissingInputError: return '' self.principal = principal # Make sure we can use the principal id in a form by base64ing it principal_str = text_type(principal) principal_bytes = principal_str.encode('utf-8') principal_token = base64.b64encode( principal_bytes).strip().replace(b'=', b'_') if not isinstance(principal_token, str): principal_token = principal_token.decode('utf-8') roles = [role for name, role in getUtilitiesFor(IRole)] roles.sort(key=lambda x: x.title) principal_roles = IPrincipalRoleManager(self.context) self.roles = [] for role in roles: name = principal_token + '.role.' + role.id field = zope.schema.Choice(__name__=name, title=role.title, vocabulary=settings_vocabulary) setUpWidget(self, name, field, IInputWidget, principal_roles.getSetting(role.id, principal)) self.roles.append(getattr(self, name + '_widget')) perms = [perm for name, perm in getUtilitiesFor(IPermission)] perms.sort(key=lambda x: x.title) principal_perms = IPrincipalPermissionManager(self.context) self.permissions = [] for perm in perms: if perm.id == 'zope.Public': continue name = principal_token + '.permission.' + perm.id field = zope.schema.Choice(__name__=name, title=perm.title, vocabulary=settings_vocabulary) setUpWidget(self, name, field, IInputWidget, principal_perms.getSetting(perm.id, principal)) self.permissions.append( getattr(self, name+'_widget')) if 'GRANT_SUBMIT' not in self.request: return '' for role in roles: name = principal_token + '.role.' + role.id role_widget = getattr(self, name + '_widget') if role_widget.hasInput(): try: setting = role_widget.getInputValue() except MissingInputError: # pragma: no cover pass else: # Arrgh! if setting is Allow: principal_roles.assignRoleToPrincipal( role.id, principal) elif setting is Deny: principal_roles.removeRoleFromPrincipal( role.id, principal) else: principal_roles.unsetRoleForPrincipal( role.id, principal) for perm in perms: if perm.id == 'zope.Public': continue name = principal_token + '.permission.'+perm.id perm_widget = getattr(self, name + '_widget') if perm_widget.hasInput(): try: setting = perm_widget.getInputValue() except MissingInputError: # pragma: no cover pass else: # Arrgh! if setting is Allow: principal_perms.grantPermissionToPrincipal( perm.id, principal) elif setting is Deny: principal_perms.denyPermissionToPrincipal( perm.id, principal) else: principal_perms.unsetPermissionForPrincipal( perm.id, principal) return _('Grants updated.')
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/granting.py
granting.py
Granting to unauthenticated =========================== There are 3 special groups: - Everybody, that everybody belongs to, - Unauthenticated, that unauthenticated users belong to, and - Authenticating, that authenticated users belong to. Here's an example: First, we'll set up a pluggable authentication utility containing a principal folder, which we'll create first. Create pluggable authentication utility and register it. >>> from zope.testbrowser.wsgi import Browser >>> manager_browser = Browser() >>> manager_browser.handleErrors = False >>> manager_browser.addHeader("Authorization", "Basic bWdyOm1ncnB3") >>> manager_browser.post("http://localhost/++etc++site/default/@@contents.html", ... "type_name=BrowserAdd__zope.pluggableauth.authentication.PluggableAuthentication&new_value=PAU") >>> manager_browser.getLink("Registration").click() Register PAU. First we get the registration page: >>> manager_browser.getControl("Register this object").click() And then we can fill out and submit the form: >>> manager_browser.getControl("Register").click() Add a Principal folder plugin to PAU. Again, we get the page, and then submit the form: >>> manager_browser.getLink("Principal Folder").click() >>> manager_browser.getControl(name="field.prefix").value = "users" >>> manager_browser.getControl(name="add_input_name").value = "users" >>> manager_browser.getControl("Add").click() Next we'll view the contents page of the principal folder: >>> manager_browser.open("http://localhost/++etc++site/default/PAU/users/@@contents.html") >>> 'users' in manager_browser.contents True And we'll add a principal, Bob: >>> manager_browser.getLink("Principal Information").click() >>> manager_browser.getControl(name="field.login").value = 'bob' >>> manager_browser.getControl(name="field.passwordManagerName").value = 'SHA1' >>> manager_browser.getControl(name="field.password").value = 'bob' >>> manager_browser.getControl(name="field.title").value = 'Bob Smith' >>> manager_browser.getControl(name="field.description").value = 'This is Bob' >>> manager_browser.getControl(name="add_input_name").value = 'bob' >>> manager_browser.getControl(name="UPDATE_SUBMIT").click() >>> manager_browser.open("http://localhost/++etc++site/default/PAU/users/@@contents.html") >>> u'bob' in manager_browser.contents True Configure PAU, with registered principal folder plugin and select any one credentials. Unfortunately, the option lists are computed dynamically in JavaScript, so we can't fill the form out directly. Instead we must send a complete POST body. We're choosing the users folder as the authenticator plugin, and the session utility as the credentials plugin. >>> manager_browser.open("http://localhost/++etc++site/default/PAU/@@configure.html") >>> manager_browser.post("http://localhost/++etc++site/default/PAU/@@configure.html", ... r"""UPDATE_SUBMIT=Change&field.credentialsPlugins=U2Vzc2lvbiBDcmVkZW50aWFscw==&field.authenticatorPlugins=dXNlcnM=""" ... """&field.credentialsPlugins.to=U2Vzc2lvbiBDcmVkZW50aWFscw==&field.authenticatorPlugins.to=dXNlcnM=""") Normally, the anonymous role has view, we'll deny it: >>> manager_browser.post("/++etc++site/AllRolePermissions.html", ... """role_id=zope.Anonymous""" ... """&Deny%3Alist=zope.View""" ... """&Deny%3Alist=zope.app.dublincore.view""" ... """&SUBMIT_ROLE=Save+Changes""") Now, if we try to access the main page as an anonymous user, we'll be unauthorized: >>> anon_browser = Browser() >>> anon_browser.open("http://localhost/") >>> print(anon_browser.url) http://localhost/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F%40%40index.html We'll even be unauthorized if we try to access it as bob: >>> bob_browser = Browser() >>> bob_browser.open("http://localhost/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F") >>> bob_browser.getControl(name="login").value = 'bob' >>> bob_browser.getControl(name="password").value = 'bob' >>> bob_browser.getControl(name="SUBMIT").click() >>> print(bob_browser.url) http://localhost/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F%40%40index.html No, let's grant view to the authenticated group: >>> manager_browser.open("/@@grant.html") >>> 'principals.zcml' in manager_browser.contents True >>> manager_browser.getControl(name='field.principal.MQ__.search').click() Once we've found him, we see what roles are available: >>> manager_browser.getControl(name="field.principal.MQ__.selection").displayValue = ['Authenticated Users'] >>> manager_browser.getControl(name="field.principal.MQ__.apply").click() >>> 'zope.View' in manager_browser.contents True >>> manager_browser.post("/@@grant.html", ... """field.principal=em9wZS5BdXRoZW50aWNhdGVk&field.principal.displayed=y""" ... """&field.em9wZS5BdXRoZW50aWNhdGVk.permission.zope.View=allow""" ... """&field.em9wZS5BdXRoZW50aWNhdGVk.permission.zope.app.dublincore.view=allow""" ... """&GRANT_SUBMIT=Change""") Now, with this, we can access the main page as bob, but not as an anonymous user: >>> bob_browser.open("http://localhost/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F") >>> bob_browser.getControl(name="login").value = 'bob' >>> bob_browser.getControl(name="password").value = 'bob' >>> bob_browser.getControl(name="SUBMIT").click() >>> print(bob_browser.url) http://localhost/ >>> anon_browser.open("http://localhost/") >>> print(anon_browser.url) http://localhost/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F%40%40index.html ###401 Unauthorized Now, we'll grant to unauthenticated: >>> manager_browser.post("/@@grant.html", ... """field.principal=em9wZS5Bbnlib2R5""" ... """&field.em9wZS5Bbnlib2R5.permission.zope.View=allow""" ... """&field.em9wZS5Bbnlib2R5.permission.zope.app.dublincore.view=allow""" ... """&GRANT_SUBMIT=Change""") With this, we can access the page as either bob or anonymous: >>> bob_browser.open("/") >>> print(bob_browser.url) http://localhost/ >>> anon_browser.open("/") >>> print(anon_browser.url) http://localhost/ Now, we'll remove the authenticated group grant: >>> manager_browser.post("/@@grant.html", ... """field.principal=em9wZS5BdXRoZW50aWNhdGVk""" ... """&field.em9wZS5BdXRoZW50aWNhdGVk.permission.zope.View=unset""" ... """&field.em9wZS5BdXRoZW50aWNhdGVk.permission.zope.app.dublincore.view=unset""" ... """&GRANT_SUBMIT=Change""") And anonymous people will be able to access the page, but bob won't be able to: >>> bob_browser.open("/") >>> print(bob_browser.url) http://localhost/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F%40%40index.html >>> anon_browser.open("/") >>> print(anon_browser.url) http://localhost/ Now, we'll remove the unauthenticated group grant: >>> manager_browser.post("/@@grant.html", ... """field.principal=em9wZS5Bbnlib2R5""" ... """&field.em9wZS5Bbnlib2R5.permission.zope.View=unset""" ... """&field.em9wZS5Bbnlib2R5.permission.zope.app.dublincore.view=unset""" ... """&GRANT_SUBMIT=Change""") >>> bob_browser.open("/") >>> print(bob_browser.url) http://localhost/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F%40%40index.html >>> anon_browser.open("/") >>> print(anon_browser.url) http://localhost/@@loginForm.html?camefrom=http%3A%2F%2Flocalhost%2F%40%40index.html Finally, we'll grant to everybody: >>> manager_browser.post("/@@grant.html", ... """field.principal=em9wZS5FdmVyeWJvZHk_""" ... """&field.em9wZS5FdmVyeWJvZHk_.permission.zope.View=allow""" ... """&field.em9wZS5FdmVyeWJvZHk_.permission.zope.app.dublincore.view=allow""" ... """&GRANT_SUBMIT=Change""") and both bob and anonymous can access: >>> bob_browser.open("/") >>> print(bob_browser.url) http://localhost/ >>> anon_browser.open("/") >>> print(anon_browser.url) http://localhost/
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/special-groups.rst
special-groups.rst
The Query View for Schema Search Plugins ======================================== Placefull setup for making the search plugin IPhysicallyLocatable:: >>> from zope.component import provideAdapter >>> from zope.schema.interfaces import ITextLine >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.formlib.interfaces import IInputWidget >>> from zope.formlib.widgets import TextWidget >>> from zope.app.authentication.tests import placefulSetUp, placefulTearDown >>> site = placefulSetUp(True) >>> provideAdapter(TextWidget, (ITextLine, IDefaultBrowserLayer), ... IInputWidget) If a plugin supports `IQuerySchemaSearch`:: >>> from zope.interface import Interface >>> import zope.schema >>> class ISearchCriteria(Interface): ... search = zope.schema.TextLine(title=u"Search String") >>> from zope.interface import implements >>> class MySearchPlugin: ... __name__ = 'searchplugin' ... __parent__ = site ... schema = ISearchCriteria ... data = ['foo', 'bar', 'blah'] ... ... def get(self, id): ... if id in self.data: ... return {} ... ... def search(self, query, start=None, batch_size=None): ... search = query.get('search') ... if search is not None: ... i = 0 ... n = 0 ... for value in self.data: ... if search in value: ... if not ((start is not None and i < start) ... or ... (batch_size is not None and n > batch_size)): ... yield value then we can get a view:: >>> from zope.app.authentication.browser.schemasearch \ ... import QuerySchemaSearchView >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> view = QuerySchemaSearchView(MySearchPlugin(), request) This allows us to render a search form:: >>> print(view.render('test')) # doctest: +NORMALIZE_WHITESPACE <h4>searchplugin</h4> <div class="row"> <div class="label"> <label for="searchplugin" title="Path to the source utility"> Source path </label> </div> <div class="field"> /searchplugin </div> </div> <div class="row"> <div class="label"> <label for="test.field.search" title=""> Search String </label> </div> <div class="field"> <input class="textType" id="test.field.search" name="test.field.search" size="20" type="text" value="" /> </div> </div> <div class="row"> <div class="field"> <input type="submit" name="test.search" value="Search" /> </div> </div> If we ask for results:: >>> view.results('test') We don't get any, since we did not provide any. But if we give input:: >>> request.form['test.field.search'] = 'a' we still don't get any:: >>> view.results('test') because we did not press the button. So let's press the button:: >>> request.form['test.search'] = 'Search' so that we now get results (!):: >>> list(view.results('test')) ['bar', 'blah'] >>> placefulTearDown()
zope.app.authentication
/zope.app.authentication-5.0.tar.gz/zope.app.authentication-5.0/src/zope/app/authentication/browser/schemasearch.rst
schemasearch.rst
=============== The Boston Skin =============== The Boston skin is a new UI for the Zope Management Interface called ZMI. Feel free to write comments, ideas and wishes to the zope3-dev mailinglist. >>> from zope.testbrowser.testing import Browser >>> browser = Browser() >>> browser.addHeader('Authorization', 'Basic mgr:mgrpw') >>> browser.handleErrors = False Check if the css viewlet is available in the Boston skin. >>> browser.open('http://localhost/++skin++Boston/@@contents.html') >>> browser.url 'http://localhost/++skin++Boston/@@contents.html' >>> browser.contents '...href="http://localhost/++skin++Boston/@@/skin.css"...' >>> browser.contents '...href="http://localhost/++skin++Boston/@@/widget.css"...' >>> browser.contents '...href="http://localhost/++skin++Boston/@@/toolbar.css"...' >>> browser.contents '...href="http://localhost/++skin++Boston/@@/xmltree.css"...' Check if the javascript viewlet is available in the Boston skin. >>> browser.open('http://localhost/++skin++Boston/@@contents.html') >>> browser.url 'http://localhost/++skin++Boston/@@contents.html' >>> browser.contents '...src="http://localhost/++skin++Boston/@@/boston.js"...' >>> browser.contents '...src="http://localhost/++skin++Boston/@@/xmltree.js"...' Check if the left viewlet is available in the Boston skin. >>> browser.open('http://localhost/++skin++Boston/@@contents.html') >>> browser.url 'http://localhost/++skin++Boston/@@contents.html' >>> browser.contents '...id="ToolBar"...' >>> browser.contents '...id="xmltree"...' >>> browser.contents '...id="addinginfo"...' Make sure the edit form "works": >>> browser.open( ... 'http://localhost/++skin++Boston/+/zope.app.dtmlpage.DTMLPage=')
zope.app.boston
/zope.app.boston-3.5.1.tar.gz/zope.app.boston-3.5.1/src/zope/app/boston/README.txt
README.txt
import ZODB.broken import zope.interface import zope.location.interfaces import zope.security.checker from ZODB.interfaces import IBroken from zope.annotation.interfaces import IAnnotations @zope.interface.implementer( IBroken, zope.location.interfaces.ILocation, IAnnotations, ) class Broken(ZODB.broken.Broken): def __get_state(self, key, default=None): get = getattr(self.__Broken_state__, 'get', None) if get is None: def get(key, default): return default return get(key, default) @property def __parent__(self): return self.__get_state('__parent__') @property def __name__(self): return self.__get_state('__name__') def __getAnnotations(self): return self.__get_state('__annotations__', {}) def __getitem__(self, key): return self.__getAnnotations()[key] def __setitem__(self, key, value): raise ZODB.broken.BrokenModified("Can't modify broken objects") def __delitem__(self, key): raise ZODB.broken.BrokenModified("Can't modify broken objects") def get(self, key, default=None): annotations = self.__getAnnotations() return annotations.get(key, default) def installBroken(event): """Install a class factory that handled broken objects This method installs a custom class factory when it gets a database-opened event:: >>> import ZODB.tests.util >>> from zope.processlifetime import DatabaseOpened >>> db = ZODB.tests.util.DB() >>> installBroken(DatabaseOpened(db)) If someone tries to load an object for which there is no class, then they will get a `Broken` object. We can simulate that by calling the database's class factory directly with a connection (None will do for our purposes, since the class factory function we register ignores the connection argument), a non-existent module and class name:: >>> cls = db.classFactory(None, 'ZODB.not.there', 'atall') The class that comes back is a subclass of `Broken`:: >>> issubclass(cls, Broken) True It implements ILocation and IAnnotations:: >>> zope.location.interfaces.ILocation.implementedBy(cls) True >>> IAnnotations.implementedBy(cls) True and it has a security checker that is the same as the checker that `Broken` has:: >>> (cls.__Security_checker__ is ... zope.security.checker.getCheckerForInstancesOf(Broken)) True Cleanup: >>> ZODB.broken.broken_cache.clear() """ Broken_ = Broken # make it local for speed find_global = ZODB.broken.find_global def type_(name, bases, dict): cls = type(name, bases, dict) checker = zope.security.checker.getCheckerForInstancesOf(Broken_) cls.__Security_checker__ = checker return cls def classFactory(connection, modulename, globalname): return find_global(modulename, globalname, Broken_, type_) event.database.classFactory = classFactory
zope.app.broken
/zope.app.broken-5.0-py3-none-any.whl/zope/app/broken/broken.py
broken.py
__docformat__ = 'restructuredtext' from zope.component import getMultiAdapter from zope.publisher.browser import BrowserView from zope.annotation.interfaces import IAnnotatable from zope.app.cache.caching import getCacheForObject, getLocationForCache from zope.app.form.utility import setUpEditWidgets from zope.i18nmessageid import ZopeMessageFactory as _ from zope.app.cache.interfaces import ICacheable from zope.app.form.interfaces import WidgetInputError from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile class CacheableView(BrowserView): __used_for__ = IAnnotatable form = ViewPageTemplateFile("cacheableedit.pt") def __init__(self, *args): super(CacheableView, self).__init__(*args) self.cacheable = ICacheable(self.context) setUpEditWidgets(self, ICacheable, self.cacheable) def current_cache_id(self): "Returns the current cache ID." return self.cacheable.getCacheId() def current_cache_url(self): "Returns the current cache provider's URL." cache = getCacheForObject(self.context) absolute_url = getMultiAdapter((cache, self.request), name='absolute_url') try: return absolute_url() except TypeError: # In case the cache object is a global one and does not have a # location, then we just return None. return None def invalidate(self): "Invalidate the current cached value." cache = getCacheForObject(self.context) location = getLocationForCache(self.context) if cache and location: cache.invalidate(location) return self.form(message=_("cache-invalidated", u"Invalidated.")) else: return self.form(message=_("no-cache-associated", u"No cache associated with object.")) def action(self): "Change the cacheId" try: cacheId = self.cacheId_widget.getInputValue() except WidgetInputError, e: #return self.form(errors=e.errors) return repr(e.errors) else: self.cacheable.setCacheId(cacheId) return self.form(message=_(u"Saved changes."))
zope.app.cache
/zope.app.cache-3.7.0.zip/zope.app.cache-3.7.0/src/zope/app/cache/browser/cacheable.py
cacheable.py
======= CHANGES ======= 4.0.0 (2017-05-05) ------------------ - Add support for Python 3.4, 3.5, 3.6 and PyPy. - Remove test dependency on ``zope.app.testing`` and ``zope.app.zcmlfiles``, among others. 3.8.1 (2010-01-08) ------------------ - Removed unneeded dependencies on zope.app.publisher and zope.app.form, moved zope.app.intid to the test dependencies. - Import hooks functionality from zope.component after it was moved there from zope.site. This lifts the test dependency on zope.site. - Use new zope.publisher that requires zope.login. 3.8.0 (2009-02-01) ------------------ - Move most of this package's code to new ``zope.catalog`` package, leaving only ZMI-related views and backward-compatibility imports here. 3.7.0 (2009-01-31) ------------------ - Change catalog's addMenuItem permission to zope.ManageServices as it doesn't make any sense to add an empty catalog that you can't modify with zope.ManageContent permission and it's completely useless without indexes. So there's no need to show a menu item. - Replaced dependency on `zope.app.container` with a lighter-weight dependency upon the newly refactored `zope.container` package. 3.6.0 (2009-01-03) ------------------ - Make TextIndex addform use default values as specified in zope.app.catalog.text.ITextIndex interface. Also, change "searchableText" to "getSearchableText" there, as it's the right value. - Add Keyword (case-insensitive and case-sensitive) catalog indices. It's now possible to use them, because ones in zope.index now implement IIndexSearch interface. - Add support for sorting, reversing and limiting result set in the ``searchResults`` method, using new IIndexSort interface features of zope.index. 3.5.2 (2008-12-28) ------------------ - Remove testing dependencies from install_requires. 3.5.1 (2007-10-31) ------------------ - Resolve ``ZopeSecurityPolicy`` deprecation warning. 3.5.0 (2007-10-11) ------------------ - Updated some meta-data. - Move ``ftests.py`` to ``tests.py``. 3.5.0a3 (2007-09-27) -------------------- - removed some deprecations 3.5.0a2 (2007-09-21) -------------------- - bugfix: passing the context to getAllUtilitiesRegisteredFor in all eventhandlers because no catalog was found which was located in a sub site and for example the ObjectModifiesEvent get fired from somewhere in the root. 3.5.0a1 (2007-06-26) -------------------- - Added marker interfaces to prevent automatic indexing (see: ``event.txt``)
zope.app.catalog
/zope.app.catalog-4.0.0.tar.gz/zope.app.catalog-4.0.0/CHANGES.rst
CHANGES.rst
Catalogs ======== Catalogs are simple tools used to supppot searching. A catalog manages a collection of indexes, and aranges for objects to indexed with it's contained indexes. TODO: Filters Catalogs should provide the option to filter the objects the catalog. This would facilitate the use of separate catalogs for separate purposes. It should be possible to specify a a collection of types (interfaces) to be cataloged and a filtering expression. Perhaps another option would be to be the ability to specify a names filter adapter. Catalogs use a unique-id tool to assign short (integer) ids to objects. Before creating a catalog, you must create a intid tool: >>> print(http(r""" ... POST /++etc++site/default/@@+/action.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 78 ... Content-Type: application/x-www-form-urlencoded ... Referer: http://localhost:8081/++etc++site/default/@@+ ... ... type_name=BrowserAdd__zope.intid.IntIds&id=&add=+Add+""", ... handle_errors=False)) HTTP/1.1 303 ... And register it: >>> print(http(r""" ... POST /++etc++site/default/IntIds/addRegistration.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Referer: http://localhost:8081/++etc++site/default/IntIds/ ... Content-Type: multipart/form-data; boundary=----------CedQTrEQIEPbgfYhvcITAhQi2aJdgu3tYfJ0WYQmkpLQTt6OTOpd5GJ ... ... ------------CedQTrEQIEPbgfYhvcITAhQi2aJdgu3tYfJ0WYQmkpLQTt6OTOpd5GJ ... Content-Disposition: form-data; name="field.name" ... ... ... ------------CedQTrEQIEPbgfYhvcITAhQi2aJdgu3tYfJ0WYQmkpLQTt6OTOpd5GJ ... Content-Disposition: form-data; name="field.provided" ... ... zope.intid.interfaces.IIntIds ... ------------CedQTrEQIEPbgfYhvcITAhQi2aJdgu3tYfJ0WYQmkpLQTt6OTOpd5GJ ... Content-Disposition: form-data; name="field.provided-empty-marker" ... ... 1 ... ------------CedQTrEQIEPbgfYhvcITAhQi2aJdgu3tYfJ0WYQmkpLQTt6OTOpd5GJ ... Content-Disposition: form-data; name="field.comment" ... ... ... ------------CedQTrEQIEPbgfYhvcITAhQi2aJdgu3tYfJ0WYQmkpLQTt6OTOpd5GJ ... Content-Disposition: form-data; name="field.actions.register" ... ... Register ... ------------CedQTrEQIEPbgfYhvcITAhQi2aJdgu3tYfJ0WYQmkpLQTt6OTOpd5GJ-- ... """, handle_errors=False)) HTTP/1.1 303 ... ... Moving short-id management outside of catalogs make it possible to join searches accross multiple catalogs and indexing tools (e.g. relationship indexes). TODO: Filters? Maybe unique-id tools should be filtered as well, however, this would limit the value of unique id tools for providing cross-catalog/cross-index merging. At least the domain for a unique id tool would be broader than the domain of a catalog. The value of filtering in the unique id tool is that it limits the amount of work that needs to be done by catalogs. One obvious aplication is to provide separate domains for ordinary and meta content. If we did this, then we'd need to be able to select, and, perhaps, alter, the unique-id tool used by a catalog. Once we have a unique-id tool, you can add a catalog: >>> print(http(r""" ... POST /++etc++site/default/@@+/action.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 77 ... Content-Type: application/x-www-form-urlencoded ... Referer: http://localhost:8081/++etc++site/default/@@+ ... ... type_name=BrowserAdd__zope.catalog.catalog.Catalog&id=&add=+Add+""")) HTTP/1.1 303 ... and register it: >>> print(http(r""" ... POST /++etc++site/default/Catalog/addRegistration.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Referer: http://localhost:8081/++etc++site/default/Catalog/ ... Content-Type: multipart/form-data; boundary=----------61t9UJyoacebBevQVdNrlvXP6T9Ik3Xo4RyXkwJJWvuhao65RTuAPRa ... ... ------------61t9UJyoacebBevQVdNrlvXP6T9Ik3Xo4RyXkwJJWvuhao65RTuAPRa ... Content-Disposition: form-data; name="field.name" ... ... ... ------------61t9UJyoacebBevQVdNrlvXP6T9Ik3Xo4RyXkwJJWvuhao65RTuAPRa ... Content-Disposition: form-data; name="field.provided" ... ... zope.catalog.interfaces.ICatalog ... ------------61t9UJyoacebBevQVdNrlvXP6T9Ik3Xo4RyXkwJJWvuhao65RTuAPRa ... Content-Disposition: form-data; name="field.provided-empty-marker" ... ... 1 ... ------------61t9UJyoacebBevQVdNrlvXP6T9Ik3Xo4RyXkwJJWvuhao65RTuAPRa ... Content-Disposition: form-data; name="field.comment" ... ... ... ------------61t9UJyoacebBevQVdNrlvXP6T9Ik3Xo4RyXkwJJWvuhao65RTuAPRa ... Content-Disposition: form-data; name="field.actions.register" ... ... Register ... ------------61t9UJyoacebBevQVdNrlvXP6T9Ik3Xo4RyXkwJJWvuhao65RTuAPRa-- ... """)) HTTP/1.1 303 ... Once we have a catalog, we can add indexes to it. Before we add an index, let's add a templated page. When adding indexes, existing objects are indexed, so the document we add now will appear in the index: >>> print(http(r""" ... POST /+/zope.app.zptpage.ZPTPage%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 780 ... Content-Type: multipart/form-data; boundary=---------------------------1425445234777458421417366789 ... Referer: http://localhost:8081/+/zope.app.zptpage.ZPTPage= ... ... -----------------------------1425445234777458421417366789 ... Content-Disposition: form-data; name="field.source" ... ... <html> ... <body> ... Now is the time, for all good dudes to come to the aid of their country. ... </body> ... </html> ... -----------------------------1425445234777458421417366789 ... Content-Disposition: form-data; name="field.expand.used" ... ... ... -----------------------------1425445234777458421417366789 ... Content-Disposition: form-data; name="field.evaluateInlineCode.used" ... ... ... -----------------------------1425445234777458421417366789 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------1425445234777458421417366789 ... Content-Disposition: form-data; name="add_input_name" ... ... dudes ... -----------------------------1425445234777458421417366789-- ... """)) HTTP/1.1 303 ... Perhaps the most common type of index to be added is a text index. Most indexes require the specification of an interface, an attribute, and an indication of whether the attribute must be called. TODO: Simplify the UI for selecting interfaces and attributes There are a number of ways the UI for this could be made more user friendly: - If the user selects an interface, we could then provide a select list of possible attributes and we could determine the callability. Perhaps selection of an interface should be required. - An index should have a way to specify default values. In particular, text indexes usially use ISearchableText and searchableText. For text indexes, one generally uses `zope.index.text.interfaces.ISearchableText`, `getSearchableText` and True. >>> print(http(r""" ... POST /++etc++site/default/Catalog/+/AddTextIndex%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 1008 ... Content-Type: multipart/form-data; boundary=---------------------------12609588153518590761493918424 ... Referer: http://localhost:8081/++etc++site/default/Catalog/+/AddTextIndex= ... ... -----------------------------12609588153518590761493918424 ... Content-Disposition: form-data; name="field.interface" ... ... zope.index.text.interfaces.ISearchableText ... -----------------------------12609588153518590761493918424 ... Content-Disposition: form-data; name="field.interface-empty-marker" ... ... 1 ... -----------------------------12609588153518590761493918424 ... Content-Disposition: form-data; name="field.field_name" ... ... getSearchableText ... -----------------------------12609588153518590761493918424 ... Content-Disposition: form-data; name="field.field_callable.used" ... ... ... -----------------------------12609588153518590761493918424 ... Content-Disposition: form-data; name="field.field_callable" ... ... on ... -----------------------------12609588153518590761493918424 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------12609588153518590761493918424 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------12609588153518590761493918424-- ... """, handle_errors=False)) HTTP/1.1 303 ... We can visit the advanced tab of the catalog to get some index statistics. Doing so, we see that we have a single document and that the total word count is 8. The word count is only 8 because ssome stop words have been eliminated. >>> print(http(r""" ... GET /++etc++site/default/Catalog/@@advanced.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Referer: http://localhost:8081/++etc++site/default/Catalog/@@contents.html ... """)) HTTP/1.1 200 ... ... <table class="listing" summary="Indexes"> <tr><th>Index</th> <th>Document Count</th> <th>Word Count</th> </tr> <tr> <td>TextIndex</td> <td>1</td> <td>10</td> </tr> </table> ... We can ask the index to reindex the objects: >>> print(http(r""" ... POST /++etc++site/default/Catalog/@@reindex.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Referer: http://localhost:8081/++etc++site/default/Catalog/@@contents.html ... """)) HTTP/1.1 303 ... ... Location: @@advanced.html Now lets add some more pages: >>> print(http(r""" ... POST /+/zope.app.zptpage.ZPTPage%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 754 ... Content-Type: multipart/form-data; boundary=---------------------------1213614620286666602740364725 ... Referer: http://localhost:8081/+/zope.app.zptpage.ZPTPage= ... ... -----------------------------1213614620286666602740364725 ... Content-Disposition: form-data; name="field.source" ... ... <html> ... <body> ... Dudes, we really need to switch to Zope 3 now. ... </body> ... </html> ... -----------------------------1213614620286666602740364725 ... Content-Disposition: form-data; name="field.expand.used" ... ... ... -----------------------------1213614620286666602740364725 ... Content-Disposition: form-data; name="field.evaluateInlineCode.used" ... ... ... -----------------------------1213614620286666602740364725 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------1213614620286666602740364725 ... Content-Disposition: form-data; name="add_input_name" ... ... zope3 ... -----------------------------1213614620286666602740364725-- ... """)) HTTP/1.1 303 ... >>> print(http(r""" ... POST /+/zope.app.zptpage.ZPTPage%3D HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 838 ... Content-Type: multipart/form-data; boundary=---------------------------491825988706308579952614349 ... Referer: http://localhost:8081/+/zope.app.zptpage.ZPTPage= ... ... -----------------------------491825988706308579952614349 ... Content-Disposition: form-data; name="field.source" ... ... <html> ... <body> ... <p>Writing tests as doctests makes them much more understandable.</p> ... <p>Python 2.4 has major enhancements to the doctest module.</p> ... </body> ... </html> ... -----------------------------491825988706308579952614349 ... Content-Disposition: form-data; name="field.expand.used" ... ... ... -----------------------------491825988706308579952614349 ... Content-Disposition: form-data; name="field.evaluateInlineCode.used" ... ... ... -----------------------------491825988706308579952614349 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------491825988706308579952614349 ... Content-Disposition: form-data; name="add_input_name" ... ... doctest ... -----------------------------491825988706308579952614349-- ... """)) HTTP/1.1 303 ... Now, if we visit the catalog advanced tab, we can see that the 3 documents have been indexed and that the word count has increased to 30: >>> print(http(r""" ... GET /++etc++site/default/Catalog/@@advanced.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Referer: http://localhost:8081/++etc++site/default/Catalog/@@contents.html ... """)) HTTP/1.1 200 ... ... <table class="listing" summary="Indexes"> <tr><th>Index</th> <th>Document Count</th> <th>Word Count</th> </tr> <tr> <td>TextIndex</td> <td>3</td> <td>33</td> </tr> </table> ... Now that we have a catalog with some documents indexed, we can search it. The catalog is really meant to be used from Python: >>> root = getRootFolder() We'll make our root folder the site (this would normally be done by the publisher): >>> from zope.component.hooks import setSite >>> setSite(root) Now, we'll get the catalog: >>> import zope.component >>> from zope.catalog.interfaces import ICatalog >>> catalog = zope.component.getUtility(ICatalog) And search it to find the names of all of the documents that contain the word 'now': >>> results = catalog.searchResults(TextIndex='now') >>> [result.__name__ for result in results] ['dudes', 'zope3'] TODO This stuff needs a lot of work. The indexing interfaces, despite being rather elaborate are still a bit too simple. There really should be more provision for combining result. In particular, catalog should have a search interface that returns ranked docids, rather than documents. You don't have to use the search algorithm build into the catalog. You can implement your own search algorithms and use them with a catalog's indexes.
zope.app.catalog
/zope.app.catalog-4.0.0.tar.gz/zope.app.catalog-4.0.0/src/zope/app/catalog/browser/README.rst
README.rst
======= CHANGES ======= 5.0 (2023-02-21) ---------------- - Add support for Python 3.8, 3.9, 3.10, 3.11. - Drop support for Python 2.7, 3.4, 3.5, 3.6. - Remove deprecated: - ``zope.app.component.getNextUtility`` (import from ``zope.site``) - ``zope.app.component.queryNextUtility`` (import from ``zope.site``) - ``zope.app.component.getNextSiteManager`` (no replacement) - ``zope.app.component.queryNextSiteManager`` (no replacement) 4.1.0 (2018-10-22) ------------------ - Add support for Python 3.7. 4.0.0 (2017-05-02) ------------------ - Remove test dependencies on zope.app.testing, zope.app.zcmlfiles, and others. - Remove install dependency on zope.app.form, replaced with direct imports of zope.formlib. - Simplify ``zope.app.component.testing`` to remove the deprecated or broken functionality in ``testingNextUtility`` and ``SiteManagerStub``. ``PlacefulSetup`` is retained (and incorporates much of what was previously inherited from ``zope.app.testing``), although use of ``zope.component.testing.PlacelessSetup`` is suggested when possible. - Add support for PyPy and Python 3.4, 3.5 and 3.6. 3.9.3 (2011-07-27) ------------------ - Replaced an undeclared test dependency on ``zope.app.authentication`` with ``zope.password``. - Removed unneeded dependencies. 3.9.2 (2010-09-17) ------------------ - Replaced a testing dependency on ``zope.app.securitypolicy`` with one on ``zope.securitypolicy``. 3.9.1 (2010-09-01) ------------------ - No longer using deprecated ``zope.testing.doctest``. Use python's build-in ``doctest`` instead. - Replaced the dependency on ``zope.deferredimport`` with BBB imports. 3.9.0 (2010-07-19) ------------------ - Added missing BBB import in ``zope.app.component.metaconfigure``. - Requiring at least ``zope.component`` 3.8 where some modules have moved which are BBB imported here. 3.8.4 (2010-01-08) ------------------ - Import hooks functionality from zope.component after it was moved there from zope.site. - Import ISite and IPossibleSite from zope.component after they were moved there from zope.location. This lifts the direct dependency on zope.location. - Fix tests using a newer zope.publisher that requires zope.login. 3.8.3 (2009-07-11) ------------------ - Removed unnecessary dependency on ``zope.app.interface``. 3.8.2 (2009-05-22) ------------------ - Fix missing import in ``zope.app.component.metadirectives``. 3.8.1 (2009-05-21) ------------------ - Add deprecation note. 3.8.0 (2009-05-21) ------------------ - IMPORTANT: this package is now empty except for some ZMI definitions in zope.app.component.browser. Functionality from this package has been moved to ``zope.site``, ``zope.componentvocabulary`` and ``zope.component``, so preferably import from those locations. - zope.componentvocabulary has the vocabulary implementations that were in zope.app.componentvocabulary now, import them from there for backwards compatibility. - moved zope:resource and zope:view directive implementation and tests over into zope.component [zcml]. 3.7.0 (2009-04-01) ------------------ - Removed deprecated `zope:defaultView` directive and its implementation. New directive to set default view is `browser:defaultView`. 3.6.1 (2009-03-12) ------------------ - Make ``class`` directive schemas importable from old location, raising a deprecation warning. It was moved in the previous release, but some custom directives could possibly use its schemas. - Deprecate import of ClassDirective to announce about new location. - Change package's mailing list address to zope-dev at zope.org, because zope3-dev at zope.org is now retired. - Adapt to the move of IDefaultViewName from zope.component.interfaces to zope.publisher.interfaces. 3.6.0 (2009-01-31) ------------------ - Moved the implementation of the <class> directive from this package to `zope.security`. In particular, the module `zope.app.component.contentdirective` has moved to `zope.security.metaconfigure`, and a compatibility import has been left in its place. - Extracted `zope.site` from zope.app.component with backwards compatibility imports in place. Local site related functionality is now in `zope.site` and packages should import from there. - Remove more deprecated on 3.5 code: * zope.app.component.fields module that was pointing to the removed back35's LayerField. * zope.app.component.interface module that was moved to zope.component.interface ages ago. * zope:content and zope:localUtility directives. * zope:factory directive. * deprecated imports in zope.component.metaconfigure * browser:tool directive and all zope.component.browser meta.zcml stuff. - Remove "back35" extras_require as it doesn't make any sense now. - Remove zope.modulealias test dependency as it is not used anywhere. - Deprecate ISite and IPossibleSite imports from zope.app.component.interfaces. They were moved to zope.location.interfaces ages ago. Fix imports in zope.app.component itself. 3.5.0 (2008-10-13) ------------------ - Remove deprecated code slated for removal on 3.5. 3.4.1 (2007-10-31) ------------------ - Resolve ``ZopeSecurityPolicy`` deprecation warning. 3.4.0 (2007-10-11) ------------------ - Initial release independent of the main Zope tree.
zope.app.component
/zope.app.component-5.0.tar.gz/zope.app.component-5.0/CHANGES.rst
CHANGES.rst
"""General registry-related views """ import base64 import zope.app.pagetemplate import zope.component.interfaces import zope.publisher.interfaces.browser from zope.formlib import form from zope.publisher.browser import BrowserPage from zope.security.proxy import removeSecurityProxy from zope import component from zope import interface from zope import schema from zope.app.component.i18n import ZopeMessageFactory as _ def _registrations(context, comp): comp = removeSecurityProxy(comp) sm = component.getSiteManager(context) for meth, attrname in ((sm.registeredUtilities, 'component'), (sm.registeredAdapters, 'factory'), (sm.registeredSubscriptionAdapters, 'factory'), (sm.registeredHandlers, 'factory')): for registration in meth(): if getattr(registration, attrname) == comp or comp is None: yield registration class IRegistrationDisplay(interface.Interface): """Display registration information """ def id(): """Return an identifier suitable for use in mapping """ def render(): "Return an HTML view of a registration object" def unregister(): "Remove the registration by unregistering the component" class ISiteRegistrationDisplay(IRegistrationDisplay): """Display registration information, including the component registered """ @component.adapter(None, zope.publisher.interfaces.browser.IBrowserRequest) class RegistrationView(BrowserPage): render = zope.app.pagetemplate.ViewPageTemplateFile('registration.pt') def registrations(self): registrations = [ component.getMultiAdapter((r, self.request), IRegistrationDisplay) for r in sorted(_registrations(self.context, self.context)) ] return registrations def update(self): registrations = {r.id(): r for r in self.registrations()} for id in self.request.form.get('ids', ()): r = registrations.get(id) if r is not None: r.unregister() def __call__(self): self.update() return self.render() @component.adapter(zope.interface.interfaces.IUtilityRegistration, zope.publisher.interfaces.browser.IBrowserRequest) @interface.implementer(IRegistrationDisplay) class UtilityRegistrationDisplay: """Utility Registration Details""" def __init__(self, context, request): self.context = context self.request = request def provided(self): provided = self.context.provided return provided.__module__ + '.' + provided.__name__ def id(self): joined = "{} {}".format(self.provided(), self.context.name) joined_bytes = joined.encode("utf8") j64_bytes = base64.b64encode(joined_bytes) if not isinstance(j64_bytes, str): j_str = j64_bytes.decode('ascii') else: j_str = j64_bytes escaped = j_str.replace('+', '_').replace('=', '').replace('\n', '') return 'R' + escaped def _comment(self): comment = self.context.info or '' if comment: comment = _("comment: ${comment}", mapping={"comment": comment}) return comment def _provided(self): name = self.context.name provided = self.provided() if name: info = _("${provided} utility named '${name}'", mapping={"provided": provided, "name": name}) else: info = _("${provided} utility", mapping={"provided": provided}) return info def render(self): return { "info": self._provided(), "comment": self._comment() } def unregister(self): self.context.registry.unregisterUtility( self.context.component, self.context.provided, self.context.name, ) class SiteRegistrationView(RegistrationView): render = zope.app.pagetemplate.ViewPageTemplateFile('siteregistration.pt') def registrations(self): registrations = [ component.getMultiAdapter((r, self.request), ISiteRegistrationDisplay) for r in sorted(_registrations(self.context, None)) ] return registrations @interface.implementer_only(ISiteRegistrationDisplay) class UtilitySiteRegistrationDisplay(UtilityRegistrationDisplay): """Utility Registration Details""" def render(self): url = component.getMultiAdapter( (self.context.component, self.request), name='absolute_url') try: url = url() except TypeError: # pragma: no cover url = "" cname = getattr(self.context.component, '__name__', '') if not cname: # pragma: no cover cname = _("(unknown name)") if url: url += "/@@SelectedManagementView.html" return { "cname": cname, "url": url, "info": self._provided(), "comment": self._comment() } @component.adapter(None, zope.publisher.interfaces.browser.IBrowserRequest) class AddUtilityRegistration(form.Form): """View for registering utilities Normally, the provided interface and name are input. A subclass can provide an empty 'name' attribute if the component should always be registered without a name. A subclass can provide a 'provided' attribute if a component should always be registered with the same interface. """ form_fields = form.Fields( schema.Choice( __name__='provided', title=_("Provided interface"), description=_("The interface provided by the utility"), vocabulary="Utility Component Interfaces", required=True, ), schema.TextLine( __name__='name', title=_("Register As"), description=_("The name under which the utility will be known."), required=False, default='', missing_value='' ), schema.Text( __name__='comment', title=_("Comment"), required=False, default='', missing_value='' ), ) name = provided = None prefix = 'field' # in hopes of making old tests pass. :) def __init__(self, context, request): if self.name is not None: # pragma: no cover self.form_fields = self.form_fields.omit('name') if self.provided is not None: # pragma: no cover self.form_fields = self.form_fields.omit('provided') super().__init__(context, request) @property def label(self): return _("Register a $classname", mapping=dict(classname=self.context.__class__.__name__) ) @form.action(_("Register")) def register(self, action, data): sm = component.getSiteManager(self.context) name = self.name if name is None: name = data['name'] provided = self.provided if provided is None: provided = data['provided'] # We have to remove the security proxy to save the registration sm.registerUtility( removeSecurityProxy(self.context), provided, name, data['comment'] or '') self.request.response.redirect('@@registration.html')
zope.app.component
/zope.app.component-5.0.tar.gz/zope.app.component-5.0/src/zope/app/component/browser/registration.py
registration.py
Managing a Site --------------- Create the browser object we'll be using. >>> from zope.testbrowser.wsgi import Browser >>> browser = Browser() >>> browser.handleErrors = False >>> browser.addHeader("Authorization", "Basic mgr:mgrpw") >>> browser.addHeader("Accept-Language", "en-US") >>> browser.open('http://localhost/manage') When we originally enter a Zope instance, there is only a root folder that is already a site: >>> 'Manage Site' in browser.contents True Let's now add a new folder called ``samplesite`` and make it a site: >>> browser.getLink(url='folder.Folder').click() >>> browser.getControl(name='new_value').value = 'samplesite' >>> browser.getControl('Apply').click() >>> browser.getLink('samplesite').click() >>> browser.getLink('Make a site').click() We are automatically forwarded to the site manager of the site. The default site management folder is always available and initially empty: >>> 'default' in browser.contents True >>> browser.getLink(url="@@registrations.html").click() >>> 'Nothing is registered for this site' in browser.contents True We can add registrations to it: >>> browser.open("/samplesite/@@addRegistration.html") >>> browser.getControl(name="field.provided").value = 'zope.site.interfaces.IFolder' >>> browser.getControl(name="field.name").value = "A Folder" >>> browser.getControl(name="field.comment").value = "My comment" >>> browser.getControl(name="field.actions.register").click() >>> 'This object is registered' in browser.contents and 'A Folder' in browser.contents True >>> 'My comment' in browser.contents True We can view those registrations: >>> browser.open("/samplesite/++etc++site/@@registrations.html") >>> 'Registrations for this site' in browser.contents and 'A Folder' in browser.contents True We can also delete those registrations: >>> browser.getControl(name="ids:list").value = True >>> browser.getControl(name="deactivate").click() >>> 'Nothing is registered for this site' in browser.contents True Names are optional: >>> browser.open("/samplesite/@@addRegistration.html") >>> browser.getControl(name="field.provided").value = 'zope.site.interfaces.IFolder' >>> browser.getControl(name="field.comment").value = "No Name" >>> browser.getControl(name="field.actions.register").click() >>> 'This object is registered' in browser.contents and 'No Name' in browser.contents True There's another more limited way to add objects to the site management folder: >>> browser.open('/samplesite/++etc++site/default/@@+/index.html') >>> browser.getControl(name='type_name').value = "BrowserAdd__zope.app.component.browser.tests.Sample" >>> browser.getControl(name="add").click() >>> 'samplesite/++etc++site/default/Sample/' in browser.contents True >>> browser.open('/samplesite/++etc++site/default/@@=/index.html') >>> browser.getControl(name='type_name').value = "BrowserAdd__zope.app.component.browser.tests.Sample" >>> browser.getControl(name="add").click() >>> '@@addRegistration.html' in browser.contents True For testing, we've defined a way that filters to prevent creating objects: >>> browser.open('/samplesite/++etc++site/default/@@-/index.html') >>> browser.getControl(name='type_name').value = "BrowserAdd__zope.app.component.browser.tests.Sample" >>> browser.getControl(name="add").click() >>> "This object isn't yet registered" in browser.contents True Let's now delete the site again: >>> browser.getLink('[top]').click() >>> browser.getControl(name='ids:list').getControl( ... value='samplesite').selected = True >>> browser.handleErrors = False >>> browser.getControl('Delete').click() The site should be gone now. >>> 'samplesite' in browser.contents False
zope.app.component
/zope.app.component-5.0.tar.gz/zope.app.component-5.0/src/zope/app/component/browser/site.rst
site.rst
"""View support for adding and configuring utilities and adapters. """ import zope.component import zope.component.interfaces from zope.app.container.browser.adding import Adding from zope.component.interfaces import IFactory from zope.exceptions.interfaces import UserError from zope.publisher.browser import BrowserView from zope.security.proxy import removeSecurityProxy from zope.site.site import LocalSiteManager from zope.traversing.browser.absoluteurl import absoluteURL from zope.app.component.i18n import ZopeMessageFactory as _ class ComponentAdding(Adding): """Adding subclass used for registerable components.""" menu_id = "add_component" def add(self, content): # Override so as to save a reference to the added object self.added_object = super().add(content) return self.added_object def nextURL(self): v = zope.component.queryMultiAdapter( (self.added_object, self.request), name="registration.html") if v is not None: url = str(zope.component.getMultiAdapter( (self.added_object, self.request), name='absolute_url')) return url + "/@@registration.html" return super().nextURL() # pragma: no cover def action(self, type_name, id=''): # For special case of that we want to redirect to another adding view # (usually another menu such as AddUtility) if type_name.startswith("../"): # pragma: no cover # Special case url = type_name if id: url += "?id=" + id self.request.response.redirect(url) return # Call the superclass action() method. # As a side effect, self.added_object is set by add() above. super().action(type_name, id) _addFilterInterface = None def addingInfo(self): # A site management folder can have many things. We only want # things that implement a particular interface info = super().addingInfo() if self._addFilterInterface is None: return info out = [] for item in info: extra = item.get('extra') if extra: factoryname = extra.get('factory') if factoryname: factory = zope.component.getUtility(IFactory, factoryname) intf = factory.getInterfaces() if not intf.extends(self._addFilterInterface): # We only skip new addMenuItem style objects # that don't implement our wanted interface. continue out.append(item) return out class UtilityAdding(ComponentAdding): """Adding subclass used for adding utilities.""" menu_id = None title = _("Add Utility") def nextURL(self): v = zope.component.queryMultiAdapter( (self.added_object, self.request), name="addRegistration.html") if v is not None: url = absoluteURL(self.added_object, self.request) return url + "/@@addRegistration.html" return super().nextURL() # pragma: no cover class MakeSite(BrowserView): """View for converting a possible site to a site.""" def addSiteManager(self): """Convert a possible site to a site >>> from zope.traversing.interfaces import IContainmentRoot >>> from zope.interface import implementer >>> @implementer(IContainmentRoot) ... class PossibleSite(object): ... def setSiteManager(self, sm): ... from zope.interface import directlyProvides ... directlyProvides(self, zope.component.interfaces.ISite) >>> folder = PossibleSite() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() Now we'll make our folder a site: >>> MakeSite(folder, request).addSiteManager() Now verify that we have a site: >>> zope.component.interfaces.ISite.providedBy(folder) 1 Note that we've also redirected the request: >>> request.response.getStatus() 302 >>> request.response.getHeader('location') '++etc++site/@@SelectedManagementView.html' If we try to do it again, we'll fail: >>> MakeSite(folder, request).addSiteManager() Traceback (most recent call last): ... zope.exceptions.interfaces.UserError: This is already a site """ if zope.component.interfaces.ISite.providedBy(self.context): raise UserError(_('This is already a site')) # We don't want to store security proxies (we can't, # actually), so we have to remove proxies here before passing # the context to the SiteManager. bare = removeSecurityProxy(self.context) sm = LocalSiteManager(bare) self.context.setSiteManager(sm) self.request.response.redirect( "++etc++site/@@SelectedManagementView.html")
zope.app.component
/zope.app.component-5.0.tar.gz/zope.app.component-5.0/src/zope/app/component/browser/__init__.py
__init__.py
"""View Class for the Container's Contents view. """ import urllib from zope.annotation.interfaces import IAnnotations from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile from zope.component import queryMultiAdapter from zope.copypastemove.interfaces import IContainerItemRenamer from zope.copypastemove.interfaces import IObjectCopier from zope.copypastemove.interfaces import IObjectMover from zope.copypastemove.interfaces import IPrincipalClipboard from zope.dublincore.interfaces import IDCDescriptiveProperties from zope.dublincore.interfaces import IZopeDublinCore from zope.event import notify from zope.exceptions.interfaces import UserError from zope.lifecycleevent import Attributes from zope.lifecycleevent import ObjectModifiedEvent from zope.publisher.browser import BrowserView from zope.security import canWrite from zope.security.interfaces import Unauthorized from zope.size.interfaces import ISized from zope.traversing.api import getName from zope.traversing.api import getPath from zope.traversing.api import joinPath from zope.traversing.api import traverse from zope.traversing.interfaces import TraversalError from zope.app.container.browser.adding import Adding from zope.app.container.i18n import ZopeMessageFactory as _ from zope.app.container.interfaces import DuplicateIDError from zope.app.container.interfaces import IContainer from zope.app.container.interfaces import IContainerNamesContainer class Contents(BrowserView): __used_for__ = IContainer error = '' message = '' normalButtons = False specialButtons = False supportsRename = False def listContentInfo(self): request = self.request if "container_cancel_button" in request: if "type_name" in request: del request.form['type_name'] if "rename_ids" in request and "new_value" in request: del request.form['rename_ids'] if "retitle_id" in request and "new_value" in request: del request.form['retitle_id'] return self._normalListContentsInfo() elif "container_rename_button" in request and not request.get("ids"): self.error = _("You didn't specify any ids to rename.") elif "container_add_button" in request: if "single_type_name" in request \ and "single_new_value" in request: request.form['type_name'] = request['single_type_name'] request.form['new_value'] = request['single_new_value'] self.addObject() elif 'single_type_name' in request \ and 'single_new_value' not in request: request.form['type_name'] = request['single_type_name'] request.form['new_value'] = "" self.addObject() elif "type_name" in request and "new_value" in request: self.addObject() elif "rename_ids" in request and "new_value" in request: self.renameObjects() elif "retitle_id" in request and "new_value" in request: self.changeTitle() elif "container_cut_button" in request: self.cutObjects() elif "container_copy_button" in request: self.copyObjects() elif "container_paste_button" in request: self.pasteObjects() elif "container_delete_button" in request: self.removeObjects() else: return self._normalListContentsInfo() if self.error: return self._normalListContentsInfo() status = request.response.getStatus() if status not in (302, 303): # Only redirect if nothing else has request.response.redirect(request.URL) return () def normalListContentInfo(self): return self._normalListContentsInfo() def _normalListContentsInfo(self): request = self.request self.specialButtons = ( 'type_name' in request or 'rename_ids' in request or ('container_rename_button' in request and request.get("ids")) or 'retitle_id' in request ) self.normalButtons = not self.specialButtons info = [self._extractContentInfo(x) for x in self.context.items()] self.supportsCut = info self.supportsCopy = info self.supportsDelete = info self.supportsPaste = self.pasteable() self.supportsRename = ( self.supportsCut and not IContainerNamesContainer.providedBy(self.context) ) return info def _extractContentInfo(self, item): request = self.request rename_ids = {} if "container_rename_button" in request: for rename_id in request.get('ids', ()): rename_ids[rename_id] = rename_id elif "rename_ids" in request: for rename_id in request.get('rename_ids', ()): rename_ids[rename_id] = rename_id retitle_id = request.get('retitle_id') id, obj = item info = {} info['id'] = info['cb_id'] = id info['object'] = obj info['url'] = urllib.parse.quote(id.encode('utf-8')) info['rename'] = rename_ids.get(id) info['retitle'] = id == retitle_id zmi_icon = queryMultiAdapter((obj, self.request), name='zmi_icon') if zmi_icon is None: info['icon'] = None else: info['icon'] = zmi_icon() dc = IZopeDublinCore(obj, None) if dc is not None: info['retitleable'] = canWrite(dc, 'title') info['plaintitle'] = not info['retitleable'] title = self.safe_getattr(dc, 'title', None) if title: info['title'] = title formatter = self.request.locale.dates.getFormatter( 'dateTime', 'short') created = self.safe_getattr(dc, 'created', None) if created is not None: info['created'] = formatter.format(created) modified = self.safe_getattr(dc, 'modified', None) if modified is not None: info['modified'] = formatter.format(modified) else: info['retitleable'] = 0 info['plaintitle'] = 1 sized_adapter = ISized(obj, None) if sized_adapter is not None: info['size'] = sized_adapter return info def safe_getattr(self, obj, attr, default): """Attempts to read the attr, returning default if Unauthorized.""" try: return getattr(obj, attr, default) except Unauthorized: return default def renameObjects(self): """Given a sequence of tuples of old, new ids we rename""" request = self.request ids = request.get("rename_ids") newids = request.get("new_value") renamer = IContainerItemRenamer(self.context) for oldid, newid in zip(ids, newids): if newid != oldid: renamer.renameItem(oldid, newid) def changeTitle(self): """Given a sequence of tuples of old, new ids we rename""" request = self.request id = request.get("retitle_id") new = request.get("new_value") item = self.context[id] dc = IDCDescriptiveProperties(item) dc.title = new notify(ObjectModifiedEvent(item, Attributes(IZopeDublinCore, 'title'))) def hasAdding(self): """Returns true if an adding view is available.""" adding = queryMultiAdapter((self.context, self.request), name="+") return (adding is not None) def addObject(self): request = self.request if IContainerNamesContainer.providedBy(self.context): new = "" else: new = request["new_value"] adding = queryMultiAdapter((self.context, self.request), name="+") if adding is None: adding = Adding(self.context, request) else: # Set up context so that the adding can build a url # if the type name names a view. # Note that we can't so this for the "adding is None" case # above, because there is no "+" view. adding.__parent__ = self.context adding.__name__ = '+' adding.action(request['type_name'], new) def removeObjects(self): """Remove objects specified in a list of object ids""" request = self.request ids = request.get('ids') if not ids: self.error = _("You didn't specify any ids to remove.") return container = self.context for id in ids: del container[id] def copyObjects(self): """Copy objects specified in a list of object ids""" request = self.request ids = request.get('ids') if not ids: self.error = _("You didn't specify any ids to copy.") return container_path = getPath(self.context) # For each item, check that it can be copied; if so, save the # path of the object for later copying when a destination has # been selected; if not copyable, provide an error message # explaining that the object can't be copied. items = [] for id in ids: ob = self.context[id] copier = IObjectCopier(ob) if not copier.copyable(): m = {"name": id} title = getDCTitle(ob) if title: m["title"] = title self.error = _( "Object '${name}' (${title}) cannot be copied", mapping=m) else: self.error = _("Object '${name}' cannot be copied", mapping=m) return items.append(joinPath(container_path, id)) # store the requested operation in the principal annotations: clipboard = getPrincipalClipboard(self.request) clipboard.clearContents() clipboard.addItems('copy', items) def cutObjects(self): """move objects specified in a list of object ids""" request = self.request ids = request.get('ids') if not ids: self.error = _("You didn't specify any ids to cut.") return container_path = getPath(self.context) # For each item, check that it can be moved; if so, save the # path of the object for later moving when a destination has # been selected; if not movable, provide an error message # explaining that the object can't be moved. items = [] for id in ids: ob = self.context[id] mover = IObjectMover(ob) if not mover.moveable(): m = {"name": id} title = getDCTitle(ob) if title: m["title"] = title self.error = _( "Object '${name}' (${title}) cannot be moved", mapping=m) else: self.error = _("Object '${name}' cannot be moved", mapping=m) return items.append(joinPath(container_path, id)) # store the requested operation in the principal annotations: clipboard = getPrincipalClipboard(self.request) clipboard.clearContents() clipboard.addItems('cut', items) def pasteable(self): """Decide if there is anything to paste """ target = self.context clipboard = getPrincipalClipboard(self.request) items = clipboard.getContents() for item in items: try: obj = traverse(target, item['target']) except TraversalError: pass else: if item['action'] == 'cut': mover = IObjectMover(obj) moveableTo = self.safe_getattr(mover, 'moveableTo', None) if moveableTo is None or not moveableTo(target): return False elif item['action'] == 'copy': copier = IObjectCopier(obj) copyableTo = self.safe_getattr(copier, 'copyableTo', None) if copyableTo is None or not copyableTo(target): return False else: raise return True def pasteObjects(self): """Paste ojects in the user clipboard to the container """ target = self.context clipboard = getPrincipalClipboard(self.request) items = clipboard.getContents() moved = False not_pasteable_ids = [] for item in items: duplicated_id = False try: obj = traverse(target, item['target']) except TraversalError: pass else: if item['action'] == 'cut': mover = IObjectMover(obj) try: mover.moveTo(target) moved = True except DuplicateIDError: duplicated_id = True elif item['action'] == 'copy': copier = IObjectCopier(obj) try: copier.copyTo(target) except DuplicateIDError: duplicated_id = True else: raise if duplicated_id: not_pasteable_ids.append(getName(obj)) if moved: # Clear the clipboard if we do a move, but not if we only do a copy clipboard.clearContents() if not_pasteable_ids != []: # Show the ids of objects that can't be pasted because # their ids are already taken. # TODO Can't we add a 'copy_of' or something as a prefix # instead of raising an exception ? raise UserError( _("The given name(s) %s is / are already being used" % ( str(not_pasteable_ids)))) def hasClipboardContents(self): """Interogate the ``PrinicipalAnnotation`` to see if clipboard contents exist.""" if not self.supportsPaste: return False # touch at least one item to in clipboard confirm contents clipboard = getPrincipalClipboard(self.request) items = clipboard.getContents() for item in items: try: traverse(self.context, item['target']) except TraversalError: pass else: return True return False contents = ViewPageTemplateFile('contents.pt') contentsMacros = contents _index = ViewPageTemplateFile('index.pt') def index(self): if 'index.html' in self.context: self.request.response.redirect('index.html') return '' return self._index() class JustContents(Contents): """Like Contents, but does't delegate to item named index.html""" def index(self): return self._index() def getDCTitle(ob): dc = IDCDescriptiveProperties(ob, None) if dc is None: return None else: return dc.title def getPrincipalClipboard(request): """Return the clipboard based on the request.""" user = request.principal annotations = IAnnotations(user) return IPrincipalClipboard(annotations)
zope.app.container
/zope.app.container-5.0-py3-none-any.whl/zope/app/container/browser/contents.py
contents.py
__docformat__ = 'restructuredtext' from zope.browsermenu.metaconfigure import menuItemDirective from zope.browserpage.metaconfigure import page from zope.browserpage.metaconfigure import view from zope.component import queryMultiAdapter from zope.configuration.fields import GlobalInterface from zope.configuration.fields import GlobalObject from zope.interface import Interface from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.security.zcml import Permission from zope.app.container.browser.adding import Adding from zope.app.container.browser.contents import Contents from zope.app.container.i18n import ZopeMessageFactory as _ class IContainerViews(Interface): """Define several container views for an `IContainer` implementation.""" for_ = GlobalObject( title="The declaration this containerViews are for.", description=""" The containerViews will be available for all objects that provide this declaration. """, required=True) contents = Permission( title="The permission needed for content page.", required=False) index = Permission( title="The permission needed for index page.", required=False) add = Permission( title="The permission needed for add page.", required=False) layer = GlobalInterface( title=_("The layer the view is in."), description=_("""A skin is composed of layers. It is common to put skin specific views in a layer named after the skin. If the 'layer' attribute is not supplied, it defaults to 'default'."""), required=False ) def containerViews(_context, for_, contents=None, add=None, index=None, layer=IDefaultBrowserLayer): """Set up container views for a given content type.""" if for_ is None: raise ValueError("A for interface must be specified.") if contents is not None: from zope.app.menus import zmi_views page(_context, name='contents.html', permission=contents, for_=for_, layer=layer, class_=Contents, attribute='contents', menu=zmi_views, title=_('Contents')) if index is not None: page(_context, name='index.html', permission=index, for_=for_, layer=layer, class_=Contents, attribute='index') if add is not None: from zope.app.menus import zmi_actions viewObj = view(_context, name='+', layer=layer, for_=for_, permission=add, class_=Adding) menuItemDirective( _context, zmi_actions, for_, '+', _('Add'), permission=add, layer=layer, filter='python:modules["zope.app.container.browser.metaconfigure"].menuFilter(context, request)') # noqa: E501 line too long viewObj.page(_context, name='index.html', attribute='index') viewObj.page(_context, name='action.html', attribute='action') viewObj() def menuFilter(context, request): '''This is a function that filters the "Add" menu item''' adding = queryMultiAdapter((context, request), name="+") if adding is None: adding = Adding(context, request) adding.__parent__ = context adding.__name__ = '+' info = adding.addingInfo() return bool(info)
zope.app.container
/zope.app.container-5.0-py3-none-any.whl/zope/app/container/browser/metaconfigure.py
metaconfigure.py
__docformat__ = 'restructuredtext' import zope.security.checker from zope.browsermenu.menu import getMenu from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile from zope.component import getMultiAdapter from zope.component import getUtility from zope.component import queryAdapter from zope.component import queryMultiAdapter from zope.component import queryUtility from zope.component.interfaces import IFactory from zope.event import notify from zope.exceptions.interfaces import UserError from zope.i18n.interfaces.locales import ICollator from zope.i18n.locales.fallbackcollator import FallbackCollator from zope.interface import implementer from zope.lifecycleevent import ObjectCreatedEvent from zope.location import LocationProxy from zope.publisher.browser import BrowserView from zope.publisher.interfaces import IPublishTraverse from zope.security.proxy import removeSecurityProxy from zope.traversing.browser.absoluteurl import absoluteURL from zope.app.container.constraints import checkFactory from zope.app.container.constraints import checkObject from zope.app.container.i18n import ZopeMessageFactory as _ from zope.app.container.interfaces import IAdding from zope.app.container.interfaces import IContainerNamesContainer from zope.app.container.interfaces import INameChooser @implementer(IAdding, IPublishTraverse) class Adding(BrowserView): def add(self, content): """See zope.app.container.interfaces.IAdding """ container = self.context name = self.contentName chooser = INameChooser(container) # check precondition checkObject(container, name, content) if IContainerNamesContainer.providedBy(container): # The container picks its own names. # We need to ask it to pick one. name = chooser.chooseName(self.contentName or '', content) else: request = self.request name = request.get('add_input_name', name) if name is None: name = chooser.chooseName(self.contentName or '', content) elif name == '': name = chooser.chooseName('', content) chooser.checkName(name, content) container[name] = content self.contentName = name # Set the added object Name return container[name] contentName = None # usually set by Adding traverser def nextURL(self): """See zope.app.container.interfaces.IAdding""" return absoluteURL(self.context, self.request) + '/@@contents.html' # set in BrowserView.__init__ request = None context = None def publishTraverse(self, request, name): """See zope.publisher.interfaces.IPublishTraverse""" if '=' in name: view_name, content_name = name.split("=", 1) self.contentName = content_name if view_name.startswith('@@'): view_name = view_name[2:] return getMultiAdapter((self, request), name=view_name) if name.startswith('@@'): view_name = name[2:] else: view_name = name view = queryMultiAdapter((self, request), name=view_name) if view is not None: return view factory = queryUtility(IFactory, name) if factory is None: return super().publishTraverse(request, name) return factory def action(self, type_name='', id=''): if not type_name: raise UserError(_("You must select the type of object to add.")) if type_name.startswith('@@'): type_name = type_name[2:] if '/' in type_name: view_name = type_name.split('/', 1)[0] else: view_name = type_name if queryMultiAdapter((self, self.request), name=view_name) is not None: url = "{}/{}={}".format( absoluteURL(self, self.request), type_name, id) self.request.response.redirect(url) return if not self.contentName: self.contentName = id # TODO: If the factory wrapped by LocationProxy is already a Proxy, # then ProxyFactory does not do the right thing and the # original's checker info gets lost. No factory that was # registered via ZCML and was used via addMenuItem worked # here. (SR) factory = getUtility(IFactory, type_name) if not isinstance(factory, zope.security.checker.Proxy): factory = LocationProxy(factory, self, type_name) factory = zope.security.checker.ProxyFactory(factory) content = factory() # Can't store security proxies. # Note that it is important to do this here, rather than # in add, otherwise, someone might be able to trick add # into unproxying an existing object, content = removeSecurityProxy(content) notify(ObjectCreatedEvent(content)) self.add(content) self.request.response.redirect(self.nextURL()) def nameAllowed(self): """Return whether names can be input by the user.""" return not IContainerNamesContainer.providedBy(self.context) menu_id = None index = ViewPageTemplateFile("add.pt") def addingInfo(self): """Return menu data. This is sorted by title. """ container = self.context result = [] for menu_id in (self.menu_id, 'zope.app.container.add'): if not menu_id: continue for item in getMenu(menu_id, self, self.request): extra = item.get('extra') if extra: factory = extra.get('factory') if factory: factory = getUtility(IFactory, factory) if not checkFactory(container, None, factory): continue elif item['extra']['factory'] != item['action']: item['has_custom_add_view'] = True # translate here to have a localized sorting item['title'] = zope.i18n.translate(item['title'], context=self.request) result.append(item) # sort the adding info with a collator instead of a basic unicode sort collator = queryAdapter(self.request.locale, ICollator) if collator is None: collator = FallbackCollator(self.request.locale) result.sort(key=lambda x: collator.key(x['title'])) return result def isSingleMenuItem(self): "Return whether there is single menu item or not." return len(self.addingInfo()) == 1 def hasCustomAddView(self): "This should be called only if there is `singleMenuItem` else return 0" if self.isSingleMenuItem(): menu_item = self.addingInfo()[0] if 'has_custom_add_view' in menu_item: return True return False
zope.app.container
/zope.app.container-5.0-py3-none-any.whl/zope/app/container/browser/adding.py
adding.py
"""Content Type convenience lookup functions.""" from zope.componentvocabulary.vocabulary import UtilityVocabulary from zope.interface import providedBy from zope.interface import provider from zope.schema.interfaces import IVocabularyFactory from zope.security.proxy import removeSecurityProxy from zope.app.content.interfaces import IContentType def queryType(object, interface): """Returns the object's interface which implements interface. >>> from zope.interface import Interface >>> class IContentType(Interface): ... pass >>> from zope.interface import Interface, implementer, directlyProvides >>> class I(Interface): ... pass >>> class J(Interface): ... pass >>> directlyProvides(I, IContentType) >>> @implementer(I) ... class C(object): ... pass >>> @implementer(J, I) ... class D(object): ... pass >>> obj = C() >>> c1_ctype = queryType(obj, IContentType) >>> c1_ctype.__name__ 'I' >>> class I1(I): ... pass >>> class I2(I1): ... pass >>> class I3(Interface): ... pass >>> @implementer(I1) ... class C1(object): ... pass >>> obj1 = C1() >>> c1_ctype = queryType(obj1, IContentType) >>> c1_ctype.__name__ 'I' >>> @implementer(I2) ... class C2(object): ... pass >>> obj2 = C2() >>> c2_ctype = queryType(obj2, IContentType) >>> c2_ctype.__name__ 'I' >>> @implementer(I3) ... class C3(object): ... pass >>> obj3 = C3() If Interface doesn't provide `IContentType`, `queryType` returns ``None``. >>> c3_ctype = queryType(obj3, IContentType) >>> c3_ctype >>> c3_ctype is None True >>> class I4(I): ... pass >>> directlyProvides(I4, IContentType) >>> @implementer(I4) ... class C4(object): ... pass >>> obj4 = C4() >>> c4_ctype = queryType(obj4, IContentType) >>> c4_ctype.__name__ 'I4' """ # Remove the security proxy, so that we can introspect the type of the # object's interfaces. naked = removeSecurityProxy(object) object_iro = providedBy(naked).__iro__ for iface in object_iro: if interface.providedBy(iface): return iface return None def queryContentType(object): """Returns the interface implemented by object which implements :class:`zope.app.content.interfaces.IContentType`. >>> from zope.interface import Interface, implementer, directlyProvides >>> class I(Interface): ... pass >>> directlyProvides(I, IContentType) >>> @implementer(I) ... class C(object): ... pass >>> obj = C() >>> c1_ctype = queryContentType(obj) >>> c1_ctype.__name__ 'I' """ return queryType(object, IContentType) @provider(IVocabularyFactory) class ContentTypesVocabulary(UtilityVocabulary): interface = IContentType
zope.app.content
/zope.app.content-5.0.tar.gz/zope.app.content-5.0/src/zope/app/content/__init__.py
__init__.py
__docformat__ = 'restructuredtext' from zope.interface import Interface, implements from zope.schema import Text from zope.schema.interfaces import IText from zope.app.form.interfaces import IInputWidget class IXMLText(IText): """A Text field that can optionally contain has its value a minidom DOM Node. """ class XMLText(Text): implements(IXMLText) class IDAVNamespace(Interface): """Represents a namespace available in WebDAV XML documents. DAV namespaces and their associated interface are utilities that fullfill provide this interface """ class IDAVCreationDate(Interface): creationdate = Text( title=u'''Records the time and date the resource was created''', description=u'''The creationdate property should be defined on all DAV compliant resources. If present, it contains a timestamp of the moment when the resource was created (i.e., the moment it had non- null state).''', readonly=True) class IDAVDisplayName(Interface): displayname = Text( title=u'''Provides a name for the resource that is suitable for\ presentation to a user''', description=u'''The displayname property should be defined on all DAV compliant resources. If present, the property contains a description of the resource that is suitable for presentation to a user.''') class IDAVSource(Interface): source = Text( title=u'''The destination of the source link\ identifies the resource that contains\ the unprocessed source of the link\ source''', description=u'''The source of the link (src) is typically the URI of the output resource on which the link is defined, and there is typically only one destination (dst) of the link, which is the URI where the unprocessed source of the resource may be accessed. When more than one link destination exists, this specification asserts no policy on ordering.''') class IOptionalDAVSchema(IDAVCreationDate, IDAVDisplayName, IDAVSource): """DAV properties that SHOULD be present but are not required""" class IGETDependentDAVSchema(Interface): """DAV properties that are dependent on GET support of the resource""" getcontentlanguage = Text( title=u'''Contains the Content-Language\ header returned by a GET without\ accept headers''', description=u'''The getcontentlanguage property MUST be defined on any DAV compliant resource that returns the Content-Language header on a GET.''') getcontentlength = Text( title=u'''Contains the Content-Length header\ returned by a GET without accept\ headers''', description=u'''The getcontentlength property MUST be defined on any DAV compliant resource that returns the Content-Length header in response to a GET.''', readonly=True) getcontenttype = Text( title=u'''Contains the Content-Type header\ returned by a GET without accept\ headers''', description=u'''This getcontenttype property MUST be defined on any DAV compliant resource that returns the Content-Type header in response to a GET.''') getetag = Text( title=u'''Contains the ETag header returned by a GET\ without accept headers''', description=u'''The getetag property MUST be defined on any DAV compliant resource that returns the Etag header.''', readonly=True) getlastmodified = Text( title=u'''Contains the Last-Modified header\ returned by a GET method without\ accept headers''', description=u'''Note that the last-modified date on a resource may reflect changes in any part of the state of the resource, not necessarily just a change to the response to the GET method. For example, a change in a property may cause the last-modified date to change. The getlastmodified property MUST be defined on any DAV compliant resource that returns the Last-Modified header in response to a GET.''', readonly=True) class IDAV1Schema(IGETDependentDAVSchema): """DAV properties required for Level 1 compliance""" resourcetype = XMLText(title=u'''Specifies the nature of the resource''', description=u''' The resourcetype property MUST be defined on all DAV compliant resources. The default value is empty.''', readonly=True) class IDAV2Schema(IDAV1Schema): """DAV properties required for Level 2 compliance""" lockdiscovery = Text( title=u'''Describes the active locks on a resource''', description=u'''The lockdiscovery property returns a listing of who has a lock, what type of lock he has, the timeout type and the time remaining on the timeout, and the associated lock token. The server is free to withhold any or all of this information if the requesting principal does not have sufficient access rights to see the requested data.''', readonly=True) supportedlock = Text( title=u'''To provide a listing of the lock\ capabilities supported by the resource''', description=u'''The supportedlock property of a resource returns a listing of the combinations of scope and access types which may be specified in a lock request on the resource. Note that the actual contents are themselves controlled by access controls so a server is not required to provide information the client is not authorized to see.''', readonly=True) class IDAVSchema(IOptionalDAVSchema, IDAV2Schema): """Full DAV properties schema""" class IDAVWidget(IInputWidget): """A specialized widget used to convert to and from DAV properties.""" def __call__(): """Render the widget. This method should not contain a minidom DOM Node as its value; if its value is a minidom DOM Node then its value will be normalized to a string. If a value should be a minidom DOM Node then use the XMLDAVWidget for inserting its value into the DAV XML response. """ def setRenderedValue(value): """Set the DAV value for the property """ class ITextDAVWidget(IDAVWidget): """A DAV widget for text values.""" class ISequenceDAVWidget(IDAVWidget): """A DAV widget for sequences.""" class IXMLDAVWidget(IDAVWidget): """A DAV widget for rendering XML values. This widget should be used if you want to insert any minidom DOM Nodes into the DAV XML response. It it receives something other then a minidom DOM Node has its value then it just renders has an empty string. """
zope.app.dav
/zope.app.dav-3.5.3.tar.gz/zope.app.dav-3.5.3/src/zope/app/dav/interfaces.py
interfaces.py
__docformat__ = 'restructuredtext' from xml.dom import minidom from xml.parsers import expat from zope.component import getUtilitiesFor, queryMultiAdapter, queryUtility from zope.schema import getFieldNamesInOrder, getFields from zope.container.interfaces import IReadContainer from zope.app.form.utility import setUpWidgets from zope.security import proxy from zope.traversing.browser.absoluteurl import absoluteURL from interfaces import IDAVWidget, IDAVNamespace from opaquenamespaces import IDAVOpaqueNamespaces class PROPFIND(object): """PROPFIND handler for all objects""" def __init__(self, context, request): self.context = context self.request = request self.setDepth(request.getHeader('depth', 'infinity')) ct = request.getHeader('content-type', 'text/xml') if ';' in ct: parts = ct.split(';', 1) self.content_type = parts[0].strip().lower() self.content_type_params = parts[1].strip() else: self.content_type = ct.lower() self.content_type_params = None self.default_ns = 'DAV:' self.oprops = IDAVOpaqueNamespaces(self.context, None) _avail_props = {} # List all *registered* DAV interface namespaces and their properties for ns, iface in getUtilitiesFor(IDAVNamespace): _avail_props[ns] = getFieldNamesInOrder(iface) # List all opaque DAV namespaces and the properties we know of if self.oprops: for ns, oprops in self.oprops.items(): _avail_props[ns] = list(oprops.keys()) self.avail_props = _avail_props # The xmldoc attribute will be set later, if needed. self.xmldoc = None def getDepth(self): return self._depth def setDepth(self, depth): self._depth = depth.lower() def PROPFIND(self, xmldoc=None): if self.content_type not in ['text/xml', 'application/xml']: self.request.response.setStatus(400) return '' if self.getDepth() not in ['0', '1', 'infinity']: self.request.response.setStatus(400) return '' resource_url = absoluteURL(self.context, self.request) if IReadContainer.providedBy(self.context): resource_url += '/' if xmldoc is None: try: xmldoc = minidom.parse(self.request.bodyStream) except expat.ExpatError: pass self.xmldoc = xmldoc resp = minidom.Document() ms = resp.createElement('multistatus') ms.setAttribute('xmlns', self.default_ns) resp.appendChild(ms) ms.appendChild(resp.createElement('response')) ms.lastChild.appendChild(resp.createElement('href')) ms.lastChild.lastChild.appendChild(resp.createTextNode(resource_url)) if xmldoc is not None: propname = xmldoc.getElementsByTagNameNS( self.default_ns, 'propname') if propname: self._handlePropname(resp) else: source = xmldoc.getElementsByTagNameNS(self.default_ns, 'prop') self._handlePropvalues(source, resp) else: self._handlePropvalues(None, resp) self._depthRecurse(ms) body = resp.toxml('utf-8') self.request.response.setResult(body) self.request.response.setStatus(207) self.request.response.setHeader('content-type', 'text/xml') return body def _depthRecurse(self, ms): depth = self.getDepth() if depth == '0' or not IReadContainer.providedBy(self.context): return subdepth = (depth == '1') and '0' or 'infinity' for id, obj in self.context.items(): pfind = queryMultiAdapter((obj, self.request), name='PROPFIND') if pfind is None: continue pfind.setDepth(subdepth) value = pfind.PROPFIND(self.xmldoc) parsed = minidom.parseString(value) responses = parsed.getElementsByTagNameNS( self.default_ns, 'response') for r in responses: ms.appendChild(ms.ownerDocument.importNode(r, True)) def _handleProp(self, source): props = {} source = source[0] childs = [e for e in source.childNodes if e.nodeType == e.ELEMENT_NODE] for node in childs: ns = node.namespaceURI iface = queryUtility(IDAVNamespace, ns) value = props.get(ns, {'iface': iface, 'props': []}) value['props'].append(node.localName) props[ns] = value return props def _handleAllprop(self): props = {} for ns, properties in self.avail_props.items(): iface = queryUtility(IDAVNamespace, ns) props[ns] = {'iface': iface, 'props': properties} return props def _handlePropname(self, resp): re = resp.lastChild.lastChild re.appendChild(resp.createElement('propstat')) prop = resp.createElement('prop') re.lastChild.appendChild(prop) count = 0 for ns, props in self.avail_props.items(): attr_name = 'a%s' % count if ns is not None and ns != self.default_ns: count += 1 prop.setAttribute('xmlns:%s' % attr_name, ns) for p in props: el = resp.createElement(p) prop.appendChild(el) if ns is not None and ns != self.default_ns: el.setAttribute('xmlns', attr_name) re.lastChild.appendChild(resp.createElement('status')) re.lastChild.lastChild.appendChild( resp.createTextNode('HTTP/1.1 200 OK')) def _handlePropvalues(self, source, resp): if not source: _props = self._handleAllprop() else: _props = self._handleProp(source) avail, not_avail = self._propertyResolver(_props) if avail: self._renderAvail(avail, resp, _props) if not_avail: self._renderNotAvail(not_avail, resp) def _propertyResolver(self, _props): avail = {} not_avail = {} for ns in _props.keys(): iface = _props[ns]['iface'] for p in _props[ns]['props']: if iface is None: # The opaque property case if (self.oprops is not None and self.oprops.get(ns, {}).has_key(p)): l = avail.setdefault(ns, []) l.append(p) else: l = not_avail.setdefault(ns, []) l.append(p) continue # The registered namespace case adapter = iface(self.context, None) if adapter is None: # Registered interface but no adapter? Maybe log this? l = not_avail.setdefault(ns, []) l.append(p) continue l = avail.setdefault(ns, []) l.append(p) return avail, not_avail def _renderAvail(self, avail, resp, _props): re = resp.lastChild.lastChild re.appendChild(resp.createElement('propstat')) prop = resp.createElement('prop') re.lastChild.appendChild(prop) re.lastChild.appendChild(resp.createElement('status')) re.lastChild.lastChild.appendChild( resp.createTextNode('HTTP/1.1 200 OK')) count = 0 for ns, props in avail.items(): attr_name = 'a%s' % count if ns is not None and ns != self.default_ns: count += 1 prop.setAttribute('xmlns:%s' % attr_name, ns) iface = _props[ns]['iface'] if not iface: # The opaque properties case, hand it off for name in props: self.oprops.renderProperty(ns, attr_name, name, prop) continue # The registered namespace case initial = {} adapted = iface(self.context) for name, field in getFields(iface).items(): try: value = field.get(adapted) except AttributeError: # Interface says the attribute exists but it # couldn't be found on the adapted object. value = field.missing_value if value is not field.missing_value: initial[name] = value setUpWidgets(self, iface, IDAVWidget, ignoreStickyValues=True, initial=initial, names=initial.keys()) for p in props: el = resp.createElement('%s' % p ) if ns is not None and ns != self.default_ns: el.setAttribute('xmlns', attr_name) prop.appendChild(el) widget = getattr(self, p + '_widget', None) if widget is None: # A widget wasn't generated for this property # because the attribute was missing on the adapted # object, which actually means that the adapter # didn't fully implement the interface ;( el.appendChild(resp.createTextNode('')) continue value = widget() if isinstance(value, (unicode, str)): # Get the widget value here el.appendChild(resp.createTextNode(value)) else: if proxy.isinstance(value, minidom.Node): el.appendChild( el.ownerDocument.importNode(value, True)) else: # Try to string-ify value = str(widget) # Get the widget value here el.appendChild(resp.createTextNode(value)) def _renderNotAvail(self, not_avail, resp): re = resp.lastChild.lastChild re.appendChild(resp.createElement('propstat')) prop = resp.createElement('prop') re.lastChild.appendChild(prop) re.lastChild.appendChild(resp.createElement('status')) re.lastChild.lastChild.appendChild( resp.createTextNode('HTTP/1.1 404 Not Found')) count = 0 for ns, props in not_avail.items(): attr_name = 'a%s' % count if ns is not None and ns != self.default_ns: count += 1 prop.setAttribute('xmlns:%s' % attr_name, ns) for p in props: el = resp.createElement('%s' % p ) prop.appendChild(el) if ns is not None and ns != self.default_ns: el.setAttribute('xmlns', attr_name)
zope.app.dav
/zope.app.dav-3.5.3.tar.gz/zope.app.dav-3.5.3/src/zope/app/dav/propfind.py
propfind.py
__docformat__ = 'restructuredtext' from xml.dom import minidom from zope.interface import implements from zope.size.interfaces import ISized from zope.dublincore.interfaces import IDCTimes from zope.filerepresentation.interfaces import IReadDirectory from zope.traversing.api import getName from zope.app.dav.interfaces import IDAVSchema from zope.app.file.interfaces import IFile class DAVSchemaAdapter(object): """An adapter for all content objects that provides the basic DAV schema/namespace.""" implements(IDAVSchema) def __init__(self, object): self.context = object def displayname(self): value = getName(self.context) if IReadDirectory(self.context, None) is not None: value = value + '/' return value displayname = property(displayname) def creationdate(self): dc = IDCTimes(self.context, None) if dc is None or dc.created is None: return '' return dc.created.strftime('%Y-%m-%d %Z') creationdate = property(creationdate) def resourcetype(self): value = IReadDirectory(self.context, None) xml = minidom.Document() if value is not None: node = xml.createElement('collection') return node return '' resourcetype = property(resourcetype) def getcontentlength(self): sized = ISized(self.context, None) if sized is None: return '' units, size = sized.sizeForSorting() if units == 'byte': return str(size) return '' getcontentlength = property(getcontentlength) def getlastmodified(self): dc = IDCTimes(self.context, None) if dc is None or dc.created is None: return '' return dc.modified.strftime('%a, %d %b %Y %H:%M:%S GMT') getlastmodified = property(getlastmodified) def executable(self): return '' executable = property(executable) def getcontenttype(self): file = IFile(self.context, None) if file is not None: return file.contentType return '' getcontenttype = property(getcontenttype)
zope.app.dav
/zope.app.dav-3.5.3.tar.gz/zope.app.dav-3.5.3/src/zope/app/dav/adapter.py
adapter.py
from xml.dom import minidom import transaction from zope.component import getUtilitiesFor from zope.component import queryUtility from zope.schema import getFieldNamesInOrder from zope.schema import getFields from zope.publisher.http import status_reasons from zope.traversing.browser.absoluteurl import absoluteURL from zope.app.container.interfaces import IReadContainer from zope.app.form.utility import no_value from zope.app.form.utility import setUpWidget from zope.app.dav.interfaces import IDAVNamespace from zope.app.dav.interfaces import IDAVWidget from zope.app.dav.opaquenamespaces import IDAVOpaqueNamespaces class PROPPATCH(object): """PROPPATCH handler for all objects """ def __init__(self, context, request): self.context = context self.request = request self._dav_ns_adapters = {} ct = request.getHeader('content-type', 'text/xml') if ';' in ct: parts = ct.split(';', 1) self.content_type = parts[0].strip().lower() self.content_type_params = parts[1].strip() else: self.content_type = ct.lower() self.content_type_params = None self.default_ns = 'DAV:' self.oprops = IDAVOpaqueNamespaces(self.context, None) _avail_props = {} # List all *registered* DAV interface namespaces and their properties for ns, iface in getUtilitiesFor(IDAVNamespace): _avail_props[ns] = getFieldNamesInOrder(iface) # List all opaque DAV namespaces and the properties we know of if self.oprops: for ns, oprops in self.oprops.items(): _avail_props[ns] = list(oprops.keys()) self.avail_props = _avail_props def _getDAVAdapter(self, ns): if ns not in self._dav_ns_adapters: iface = queryUtility(IDAVNamespace, ns) if iface: adapter = self._dav_ns_adapters[ns] = iface(self.context) else: adapter = self._dav_ns_adapters[ns] = None return self._dav_ns_adapters[ns] def PROPPATCH(self): if self.content_type not in ['text/xml', 'application/xml']: self.request.response.setStatus(400) return '' resource_url = absoluteURL(self.context, self.request) if IReadContainer.providedBy(self.context): resource_url += '/' xmldoc = minidom.parse(self.request.bodyStream) resp = minidom.Document() ms = resp.createElement('multistatus') ms.setAttribute('xmlns', self.default_ns) resp.appendChild(ms) ms.appendChild(resp.createElement('response')) ms.lastChild.appendChild(resp.createElement('href')) ms.lastChild.lastChild.appendChild(resp.createTextNode(resource_url)) updateel = xmldoc.getElementsByTagNameNS(self.default_ns, 'propertyupdate') if not updateel: self.request.response.setStatus(422) return '' updates = [node for node in updateel[0].childNodes if node.nodeType == node.ELEMENT_NODE and node.localName in ('set', 'remove')] if not updates: self.request.response.setStatus(422) return '' self._handlePropertyUpdate(resp, updates) body = resp.toxml('utf-8') self.request.response.setResult(body) self.request.response.setStatus(207) return body def _handlePropertyUpdate(self, resp, updates): _propresults = {} for update in updates: prop = update.getElementsByTagNameNS(self.default_ns, 'prop') if not prop: continue for node in prop[0].childNodes: if not node.nodeType == node.ELEMENT_NODE: continue if update.localName == 'set': status = self._handleSet(node) else: status = self._handleRemove(node) results = _propresults.setdefault(status, {}) props = results.setdefault(node.namespaceURI, []) if node.localName not in props: props.append(node.localName) if _propresults.keys() != [200]: # At least some props failed, abort transaction transaction.abort() # Move 200 succeeded props to the 424 status if _propresults.has_key(200): failed = _propresults.setdefault(424, {}) for ns, props in _propresults[200].items(): failed_props = failed.setdefault(ns, []) failed_props.extend(props) del _propresults[200] # Create the response document re = resp.lastChild.lastChild for status, results in _propresults.items(): re.appendChild(resp.createElement('propstat')) prop = resp.createElement('prop') re.lastChild.appendChild(prop) count = 0 for ns in results.keys(): attr_name = 'a%s' % count if ns is not None and ns != self.default_ns: count += 1 prop.setAttribute('xmlns:%s' % attr_name, ns) for p in results.get(ns, []): el = resp.createElement(p) prop.appendChild(el) if ns is not None and ns != self.default_ns: el.setAttribute('xmlns', attr_name) reason = status_reasons.get(status, '') re.lastChild.appendChild(resp.createElement('status')) re.lastChild.lastChild.appendChild( resp.createTextNode('HTTP/1.1 %d %s' % (status, reason))) def _handleSet(self, prop): ns = prop.namespaceURI iface = queryUtility(IDAVNamespace, ns) if not iface: # opaque DAV properties if self.oprops is not None: self.oprops.setProperty(prop) # Register the new available property, because we need to be # able to remove it again in the same request! props = self.avail_props.setdefault(ns, []) if prop.localName not in props: props.append(prop.localName) return 200 return 403 if not prop.localName in self.avail_props[ns]: return 403 # Cannot add propeties to a registered schema fields = getFields(iface) field = fields[prop.localName] if field.readonly: return 409 # RFC 2518 specifies 409 for readonly props dav_adapter = self._getDAVAdapter(ns) value = field.get(dav_adapter) if value is field.missing_value: value = no_value setUpWidget(self, prop.localName, field, IDAVWidget, value=value, ignoreStickyValues=True) widget = getattr(self, prop.localName + '_widget') widget.setRenderedValue(prop) if not widget.hasValidInput(): return 409 # Didn't match the widget validation if widget.applyChanges(dav_adapter): return 200 return 422 # Field didn't accept the value def _handleRemove(self, prop): ns = prop.namespaceURI if not prop.localName in self.avail_props.get(ns, []): return 200 iface = queryUtility(IDAVNamespace, ns) if not iface: # opaque DAV properties if self.oprops is None: return 200 self.oprops.removeProperty(ns, prop.localName) return 200 # Registered interfaces fields = getFields(iface) field = fields[prop.localName] if field.readonly: return 409 # RFC 2518 specifies 409 for readonly props dav_adapter = self._getDAVAdapter(ns) if field.required: if field.default is None: return 409 # Clearing a required property is a conflict # Reset the field to the default if a value is required field.set(dav_adapter, field.default) return 200 # Reset the field to it's defined missing_value field.set(dav_adapter, field.missing_value) return 200
zope.app.dav
/zope.app.dav-3.5.3.tar.gz/zope.app.dav-3.5.3/src/zope/app/dav/proppatch.py
proppatch.py
__docformat__ = 'restructuredtext' from UserDict import DictMixin from xml.dom import minidom from zope.interface import implements from zope.interface.common.mapping import IMapping from zope.location import Location from zope.annotation.interfaces import IAnnotations, IAnnotatable from BTrees.OOBTree import OOBTree DANkey = "zope.app.dav.DAVOpaqueProperties" class IDAVOpaqueNamespaces(IMapping): """Opaque storage for non-registered DAV namespace properties. Any unknown (no interface registered) DAV properties are stored opaquely keyed on their namespace URI, so we can return them later when requested. Thus this is a mapping of a mapping. """ def renderProperty(ns, nsprefix, prop, propel): """Render the named property to a DOM subtree ns and prop are keys defining the property, nsprefix is the namespace prefix used in the DOM for the namespace of the property, and propel is the <prop> element in the target DOM to which the property DOM elements need to be added. """ def setProperty(propel): """Store a DOM property in the opaque storage propel is expected to be a DOM element from which the namespace and property name are taken to be stored. """ def removeProperty(ns, prop): """Remove the indicated property altogether""" class DAVOpaqueNamespacesAdapter(DictMixin, Location): """Adapt annotatable objects to DAV opaque property storage.""" implements(IDAVOpaqueNamespaces) __used_for__ = IAnnotatable annotations = None def __init__(self, context): annotations = IAnnotations(context) oprops = annotations.get(DANkey) if oprops is None: self.annotations = annotations oprops = OOBTree() self._mapping = oprops def _changed(self): if self.annotations is not None: self.annotations[DANkey] = self._mapping self.annotations = None def get(self, key, default=None): return self._mapping.get(key, default) def __getitem__(self, key): return self._mapping[key] def keys(self): return self._mapping.keys() def __setitem__(self, key, value): self._mapping[key] = value self._changed() def __delitem__(self, key): del self._mapping[key] self._changed() # # Convenience methods; storing and retrieving properties through WebDAV # It may be better to use specialised IDAWWidget implementatins for this. # def renderProperty(self, ns, nsprefix, prop, propel): """Render a property as DOM elements""" value = self.get(ns, {}).get(prop) if value is None: return value = minidom.parseString(value) el = propel.ownerDocument.importNode(value.documentElement, True) el.setAttribute('xmlns', nsprefix) propel.appendChild(el) def setProperty(self, propel): ns = propel.namespaceURI props = self.setdefault(ns, OOBTree()) propel = makeDOMStandalone(propel) props[propel.nodeName] = propel.toxml('utf-8') def removeProperty(self, ns, prop): if self.get(ns, {}).get(prop) is None: return del self[ns][prop] if not self[ns]: del self[ns] def makeDOMStandalone(element): """Make a DOM Element Node standalone The DOM tree starting at element is copied to a new DOM tree where: - Any prefix used for the element namespace is removed from the element and all attributes and decendant nodes. - Any other namespaces used on in the DOM tree is explcitly declared on the root element. So, if the root element to be transformed is defined with a prefix, that prefix is removed from the whole tree: >>> dom = minidom.parseString('''<?xml version="1.0"?> ... <foo xmlns:bar="http://bar.com"> ... <bar:spam><bar:eggs /></bar:spam> ... </foo>''') >>> element = dom.documentElement.getElementsByTagName('bar:spam')[0] >>> standalone = makeDOMStandalone(element) >>> standalone.toxml() u'<spam><eggs/></spam>' Prefixes are of course also removed from attributes: >>> element.setAttributeNS(element.namespaceURI, 'bar:vikings', ... 'singing') >>> standalone = makeDOMStandalone(element) >>> standalone.toxml() u'<spam vikings="singing"><eggs/></spam>' Any other namespace used will be preserved, with the prefix definitions for these renamed and moved to the root element: >>> dom = minidom.parseString('''<?xml version="1.0"?> ... <foo xmlns:bar="http://bar.com" xmlns:mp="uri://montypython"> ... <bar:spam> ... <bar:eggs mp:song="vikings" /> ... <mp:holygrail xmlns:c="uri://castle"> ... <c:camelot place="silly" /> ... </mp:holygrail> ... <lancelot xmlns="uri://montypython" /> ... </bar:spam> ... </foo>''') >>> element = dom.documentElement.getElementsByTagName('bar:spam')[0] >>> standalone = makeDOMStandalone(element) >>> print standalone.toxml() <spam xmlns:p0="uri://montypython" xmlns:p1="uri://castle"> <eggs p0:song="vikings"/> <p0:holygrail> <p1:camelot place="silly"/> </p0:holygrail> <p0:lancelot/> </spam> """ return DOMTransformer(element).makeStandalone() def _numberGenerator(i=0): while True: yield i i += 1 class DOMTransformer(object): def __init__(self, el): self.source = el self.ns = el.namespaceURI self.prefix = el.prefix self.doc = minidom.getDOMImplementation().createDocument( self.ns, el.localName, None) self.dest = self.doc.documentElement self.prefixes = {} self._seq = _numberGenerator() def seq(self): return self._seq.next() seq = property(seq) def _prefixForURI(self, uri): if not uri or uri == self.ns: return '' if not self.prefixes.has_key(uri): self.prefixes[uri] = 'p%d' % self.seq return self.prefixes[uri] + ':' def makeStandalone(self): self._copyElement(self.source, self.dest) for ns, prefix in self.prefixes.items(): self.dest.setAttribute('xmlns:%s' % prefix, ns) return self.dest def _copyElement(self, source, dest): for i in range(source.attributes.length): attr = source.attributes.item(i) if attr.prefix == 'xmlns' or attr.nodeName == 'xmlns': continue ns = attr.prefix and attr.namespaceURI or source.namespaceURI qname = attr.localName if ns != dest.namespaceURI: qname = '%s%s' % (self._prefixForURI(ns), qname) dest.setAttributeNS(ns, qname, attr.value) for node in source.childNodes: if node.nodeType == node.ELEMENT_NODE: ns = node.namespaceURI qname = '%s%s' % (self._prefixForURI(ns), node.localName) copy = self.doc.createElementNS(ns, qname) self._copyElement(node, copy) else: copy = self.doc.importNode(node, True) dest.appendChild(copy)
zope.app.dav
/zope.app.dav-3.5.3.tar.gz/zope.app.dav-3.5.3/src/zope/app/dav/opaquenamespaces.py
opaquenamespaces.py
import os import shutil import sys import tempfile from optparse import OptionParser __version__ = '2015-07-01' # See zc.buildout's changelog if this version is up to date. tmpeggs = tempfile.mkdtemp(prefix='bootstrap-') usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("--version", action="store_true", default=False, help=("Return bootstrap.py version.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) parser.add_option("--buildout-version", help="Use a specific zc.buildout version") parser.add_option("--setuptools-version", help="Use a specific setuptools version") parser.add_option("--setuptools-to-dir", help=("Allow for re-use of existing directory of " "setuptools versions")) options, args = parser.parse_args() if options.version: print("bootstrap.py version %s" % __version__) sys.exit(0) ###################################################################### # load/install setuptools try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} if os.path.exists('ez_setup.py'): exec(open('ez_setup.py').read(), ez) else: exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): # Strip all site-packages directories from sys.path that # are not sys.prefix; this is because on Windows # sys.prefix is a site-package directory. if sitepackage_path != sys.prefix: sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) if options.setuptools_version is not None: setup_args['version'] = options.setuptools_version if options.setuptools_to_dir is not None: setup_args['to_dir'] = options.setuptools_to_dir ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location # Fix sys.path here as easy_install.pth added before PYTHONPATH cmd = [sys.executable, '-c', 'import sys; sys.path[0:0] = [%r]; ' % setuptools_path + 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) requirement = 'zc.buildout' version = options.buildout_version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): try: return not parsed_version.is_prerelease except AttributeError: # Older setuptools for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zope.app.debug
/zope.app.debug-4.0.0.tar.gz/zope.app.debug-4.0.0/bootstrap.py
bootstrap.py
from __future__ import print_function __docformat__ = 'restructuredtext' import base64 import time try: import urllib.parse as urllib except ImportError: import urllib import sys from pdb import Pdb from io import BytesIO from zope.publisher.publish import publish as _publish, debug_call from zope.publisher.browser import TestRequest, setDefaultSkin from zope.app.publication.browser import BrowserPublication from zope.app.appsetup import config, database try: text_type = unicode except NameError: text_type = str class Debugger(object): pdb = Pdb def __init__(self, db=None, config_file=None, stdout=None): if db is None and config_file is None: db = 'Data.fs' config_file = 'site.zcml' if config_file is not None: config(config_file) self.db = database(db) self.stdout = stdout @classmethod def fromDatabase(cls, db): inst = cls.__new__(cls) inst.db = db return inst def root(self): """Get the top-level application object The object returned is connected to an open database connection. """ from zope.app.publication.zopepublication import ZopePublication return self.db.open().root()[ZopePublication.root_name] def _request(self, path='/', stdin='', basic=None, environment = None, form=None, request=None, publication=BrowserPublication): """Create a request """ env = {} if isinstance(stdin, text_type): stdin = stdin.encode("utf-8") if isinstance(stdin, bytes): stdin = BytesIO(stdin) p = path.split('?') if len(p) == 1: env['PATH_INFO'] = p[0] elif len(p) == 2: env['PATH_INFO'], env['QUERY_STRING'] = p else: raise ValueError("Too many ?s in path", path) env['PATH_INFO'] = urllib.unquote(env['PATH_INFO']) if environment is not None: env.update(environment) if basic: basic_bytes = basic.encode('ascii') if not isinstance(basic, bytes) else basic basic64_bytes = base64.b64encode(basic_bytes) basic64 = basic64_bytes.decode('ascii').strip() env['HTTP_AUTHORIZATION'] = "Basic %s" % basic64 pub = publication(self.db) if request is not None: request = request(stdin, env) else: request = TestRequest(stdin, env) setDefaultSkin(request) request.setPublication(pub) if form: request.form.update(form) return request def publish(self, path='/', stdin='', *args, **kw): t, c = time.time(), time.clock() request = self._request(path, stdin, *args, **kw) # agroszer: 2008.feb.1.: if a retry occurs in the publisher, # the response will be LOST, so we must accept the returned request request = _publish(request) getStatus = getattr(request.response, 'getStatus', lambda: None) headers = sorted(request.response.getHeaders()) print( 'Status %s\r\n%s\r\n\r\n%s' % ( request.response.getStatusString(), '\r\n'.join([("%s: %s" % h) for h in headers]), request.response.consumeBody(), ), file=self.stdout or sys.stdout) return time.time()-t, time.clock()-c, getStatus() def run(self, *args, **kw): t, c = time.time(), time.clock() request = self._request(*args, **kw) # agroszer: 2008.feb.1.: if a retry occurs in the publisher, # the response will be LOST, so we must accept the returned request request = _publish(request, handle_errors=False) getStatus = getattr(request.response, 'getStatus', lambda: None) return time.time()-t, time.clock()-c, getStatus() def debug(self, *args, **kw): out = self.stdout or sys.stdout class ZopePdb(self.Pdb): done_pub = False done_ob = False def do_pub(self, arg): if self.done_pub: print('pub already done.', file=out) return self.do_s('') self.do_s('') self.do_c('') self.done_pub = True def do_ob(self, arg): if self.done_ob: print('ob already done.', file=out) return self.do_pub('') self.do_c('') self.done_ob = True dbg = ZopePdb() request = self._request(*args, **kw) fbreak(dbg, _publish) fbreak(dbg, debug_call) print('* Type c<cr> to jump to published object call.', file=out) dbg.runcall(_publish, request) return dbg def fbreak(db, meth): try: meth = meth.__func__ except AttributeError: pass code = meth.__code__ lineno = getlineno(code) filename = code.co_filename db.set_break(filename,lineno) try: from codehack import getlineno except: def getlineno(code): return code.co_firstlineno
zope.app.debug
/zope.app.debug-4.0.0.tar.gz/zope.app.debug-4.0.0/src/zope/app/debug/debug.py
debug.py
========= CHANGES ========= 5.0 (2023-02-20) ================ - Drop support for Python 2.7, 3.4, 3.5, 3.6. - Add support for Python 3.8, 3.9, 3.10, 3.11. - Drop support for deprecated ``python setup.py test``. 4.1.0 (2018-10-22) ================== - Add support for Python 3.7. 4.0.0 (2017-04-22) ================== - Add support for Python 3.4, 3.5, and 3.6 and PyPy. - Removed support for Python 2.6. - Added ``tox.ini`` and manifest. - Removed zope.app.testing dependency. 3.5.1 (2009-12-15) ================== - Added missing zcml namespace to the configure file. 3.5.0 (2009-12-15) ================== - Moved CheckDependency event handler and its tests into this package from its former place in zope.container. 3.4.0 (2007-10-23) ================== - Initial release independent of the main Zope tree.
zope.app.dependable
/zope.app.dependable-5.0.tar.gz/zope.app.dependable-5.0/CHANGES.rst
CHANGES.rst
__docformat__ = 'restructuredtext' from zope.annotation.interfaces import IAnnotations from zope.interface import implementer from zope.traversing.api import canonicalPath from zope.traversing.api import getParent from zope.traversing.api import getPath from zope.app.dependable.interfaces import IDependable class PathSetAnnotation: """Abstract base class for annotations that are sets of paths. To make this into a concrete class, a subclass must set the class attribute `key` to a unique annotation key. A subclass may also choose to rename the methods. """ def __init__(self, context): self.context = context try: parent = getParent(self.context) except TypeError: parent = None if parent is not None: try: pp = getPath(parent) except TypeError: pp = "" if not pp.endswith("/"): pp += "/" self.pp = pp # parentpath else: self.pp = "" self.pplen = len(self.pp) def addPath(self, path): path = self._make_relative(path) annotations = IAnnotations(self.context) old = annotations.get(self.key, ()) fixed = [self._make_relative(o) for o in old] if path not in fixed: fixed.append(path) new = tuple(fixed) if new != old: annotations[self.key] = new def removePath(self, path): path = self._make_relative(path) annotations = IAnnotations(self.context) old = annotations.get(self.key, ()) if old: fixed = [self._make_relative(o) for o in old] fixed = [loc for loc in fixed if loc != path] new = tuple(fixed) if new != old: if new: annotations[self.key] = new else: del annotations[self.key] def getPaths(self): annotations = IAnnotations(self.context) locs = annotations.get(self.key, ()) return tuple(map(self._make_absolute, locs)) def _make_relative(self, path): if path.startswith("/") and self.pp: path = canonicalPath(path) if path.startswith(self.pp): path = path[self.pplen:] # Now, the path should not actually begin with a /. # canonicalPath doesn't allow trailing / in a path # segment, and we already cut off the whole length of # the parent, which we guaranteed to begin and end # with a /. But it's possible that older dependencies # than we test with could produce this scenario, so we # leave it for BWC. path = path.lstrip("/") return path def _make_absolute(self, path): if not path.startswith("/") and self.pp: path = self.pp + path return path @implementer(IDependable) class Dependable(PathSetAnnotation): """See `IDependable`.""" key = "zope.app.dependable.Dependents" addDependent = PathSetAnnotation.addPath removeDependent = PathSetAnnotation.removePath dependents = PathSetAnnotation.getPaths
zope.app.dependable
/zope.app.dependable-5.0.tar.gz/zope.app.dependable-5.0/src/zope/app/dependable/__init__.py
__init__.py
======= CHANGES ======= 4.1.0 (2021-11-17) ------------------ - Add support for Python 3.7, 3.8, 3.9 and 3.10. - Drop support for Python 3.4. 4.0.0 (2017-05-16) ------------------ - Add support for Python 3.4, 3.5, 3.6 and PyPy. 3.5.3 (2010-09-01) ------------------ - Removed the dependency on zope.app.publisher, added missing dependencies. - Replaced the use of zope.deferredimport with direct imports. 3.5.2 (2009-01-22) ------------------ - Removed zope.app.zapi from dependencies, replacing its uses with direct imports. - Clean dependencies. - Changed mailing list address to [email protected], changed url from cheeseshop to pypi. - Use zope.ManageServices permission instead of zope.ManageContent for errorRedirect view and menu item, because all IErrorReportingUtility views are registered for zope.ManageServices as well. - Fix package's README.txt 3.5.1 (2007-09-27) ------------------ - rebumped to replace faulty egg 3.5.0 ----- - Move core components to ``zope.error`` 3.4.0 (2007-09-24) ------------------ - Initial documented release
zope.app.error
/zope.app.error-4.1.0.tar.gz/zope.app.error-4.1.0/CHANGES.rst
CHANGES.rst
====== README ====== This package provides an error reporting utility which is able to store errors. (Notice that the implementation classes have been moved to the ``zope.error`` package.) Let's create one: >>> from zope.app.error.error import ErrorReportingUtility >>> util = ErrorReportingUtility() >>> util <zope.error.error.ErrorReportingUtility object at ...> >>> from zope.app.error.interfaces import IErrorReportingUtility >>> IErrorReportingUtility.providedBy(util) True >>> IErrorReportingUtility <InterfaceClass zope.error.interfaces.IErrorReportingUtility> This package contains ZMI views in the ``browser`` sub-package: >>> from zope.app.error.browser import EditErrorLog, ErrorRedirect >>> EditErrorLog <class 'zope.app.error.browser.EditErrorLog'> >>> ErrorRedirect <class 'zope.app.error.browser.ErrorRedirect'> These are configured when the configuration for this package is executed (as long as the right dependencies are available). Certain ZMI menus must first be available: >>> from zope.configuration import xmlconfig >>> _ = xmlconfig.string(r""" ... <configure xmlns="http://namespaces.zope.org/browser" i18n_domain="zope"> ... <include package="zope.browsermenu" file="meta.zcml" /> ... <menu ... id="zmi_views" ... title="Views" ... /> ... ... <menu ... id="zmi_actions" ... title="Actions" ... /> ... </configure> ... """) Now we can configure the package: >>> _ = xmlconfig.string(r""" ... <configure xmlns="http://namespaces.zope.org/zope"> ... <include package="zope.app.error" /> ... </configure> ... """)
zope.app.error
/zope.app.error-4.1.0.tar.gz/zope.app.error-4.1.0/src/zope/app/error/README.rst
README.rst
System Errors ============= System Errors are errors representing a system failure. At the application level, they are errors that are uncaught by the application and that a developer hasn't provided a custom error view for. Zope provides a default system error view that prints an obnoxius terse message and that sets the response status. There is a simple view registered in ``ftesting.zcml`` which raises ``Exception()``: >>> print(http(r""" ... GET /error.html HTTP/1.1 ... """)) HTTP/1.1 500 Internal Server Error ... A system error occurred. ... Another way of getting a system error is the occurrence of a system error, such as ``ComponentLookupError``. I have registered a simple view in ``ftesting.zcml``, too, that will raise a component lookup error. So if we call ``componentlookuperror.html``, we should get the error message: >>> print(http(r""" ... GET /componentlookuperror.html HTTP/1.1 ... """)) HTTP/1.1 500 Internal Server Error ... A system error occurred. ...
zope.app.exception
/zope.app.exception-5.0-py3-none-any.whl/zope/app/exception/browser/systemerror.rst
systemerror.rst
Changes ======= 4.0.0 (2017-05-16) ------------------ - Add support for Python 3.4, 3.5, 3.6 and PyPy. - Remove test dependency on ``zope.app.testing`` and ``zope.app.zcmlfiles``, among others. - Change dependency from ZODB3 to persistent and add missing dependencies on ``zope.app.content``. 3.6.1 (2010-09-17) ------------------ - Removed ZPKG slugs and ZCML ones. - Moved a functional test here from `zope.app.http`. - Using Python's ``doctest`` instead of deprecated ``zope.testing.doctest``. 3.6.0 (2010-08-19) ------------------ - Updated ``ftesting.zcml`` to use the new permission names exported by ``zope.dublincore`` 3.7. - Using python's `doctest` instead of deprecated `zope.testing.doctest`. 3.5.1 (2010-01-08) ------------------ - Fix ftesting.zcml due to zope.securitypolicy update. - Added missing dependency on transaction. - Import content-type parser from zope.contenttype, reducing zope.publisher to a test dependency. - Fix tests using a newer zope.publisher that requires zope.login. 3.5.0 (2009-01-31) ------------------ - Replace ``zope.app.folder`` use by ``zope.site``. Add missing dependency in ``setup.py``. 3.4.6 (2009-01-27) ------------------ - Remove zope.app.zapi dependency again. Previous release was wrong. We removed the zope.app.zapi uses before, so we don't need it anymore. 3.4.5 (2009-01-27) ------------------ - added missing dependency: zope.app.zapi 3.4.4 (2008-09-05) ------------------ - Bug: Get actual filename instead of full filesystem path when adding file/image using Internet Explorer. 3.4.3 (2008-06-18) ------------------ - Using IDCTimes interface instead of IZopeDublinCore to determine the modification date of a file. 3.4.2 (2007-11-09) ------------------ - Include information about which attributes changed in the ``IObjectModifiedEvent`` after upload. This fixes https://bugs.launchpad.net/zope3/+bug/98483. 3.4.1 (2007-10-31) ------------------ - Resolve ``ZopeSecurityPolicy`` deprecation warning. 3.4.0 (2007-10-24) ------------------ - Initial release independent of the main Zope tree.
zope.app.file
/zope.app.file-4.0.0.tar.gz/zope.app.file-4.0.0/CHANGES.rst
CHANGES.rst
"""File content component """ __docformat__ = 'restructuredtext' from persistent import Persistent import transaction from zope.interface import implementer import zope.app.publication.interfaces from zope.app.file import interfaces # set the size of the chunks MAXCHUNKSIZE = 1 << 16 try: text_type = unicode except NameError: text_type = str @implementer(zope.app.publication.interfaces.IFileContent, interfaces.IFile) class File(Persistent): """A persistent content component storing binary file data Let's test the constructor: >>> file = File() >>> file.contentType '' >>> file.data == b'' True >>> file = File(b'Foobar') >>> file.contentType '' >>> file.data == b'Foobar' True >>> file = File(b'Foobar', 'text/plain') >>> file.contentType 'text/plain' >>> file.data == b'Foobar' True >>> file = File(data=b'Foobar', contentType='text/plain') >>> file.contentType 'text/plain' >>> file.data == b'Foobar' True Let's test the mutators: >>> file = File() >>> file.contentType = 'text/plain' >>> file.contentType 'text/plain' >>> file.data = b'Foobar' >>> file.data == b'Foobar' True >>> file.data = None Traceback (most recent call last): ... TypeError: Cannot set None data on a file. Let's test large data input: >>> file = File() Insert as string: >>> file.data = b'Foobar'*60000 >>> file.getSize() 360000 >>> file.data == b'Foobar'*60000 True Insert data as FileChunk: >>> fc = FileChunk(b'Foobar'*4000) >>> file.data = fc >>> file.getSize() 24000 >>> file.data == b'Foobar'*4000 True Insert data from file object: >>> from io import BytesIO >>> sio = BytesIO() >>> _ = sio.write(b'Foobar'*100000) >>> _ = sio.seek(0) >>> file.data = sio >>> file.getSize() == 600000 True >>> file.data == b'Foobar'*100000 True Last, but not least, verify the interface: >>> from zope.interface.verify import verifyClass >>> interfaces.IFile.implementedBy(File) True >>> verifyClass(interfaces.IFile, File) True """ _data = None _size = 0 def __init__(self, data=b'', contentType=''): self.data = data self.contentType = contentType def _getData(self): if isinstance(self._data, FileChunk): return bytes(self._data) return self._data def _setData(self, data): # Handle case when data is a string if isinstance(data, text_type): data = data.encode('UTF-8') if isinstance(data, bytes): self._data, self._size = FileChunk(data), len(data) return # Handle case when data is None if data is None: raise TypeError('Cannot set None data on a file.') # Handle case when data is already a FileChunk if isinstance(data, FileChunk): size = len(data) self._data, self._size = data, size return # Handle case when data is a file object seek = data.seek read = data.read seek(0, 2) size = end = data.tell() if size <= 2 * MAXCHUNKSIZE: seek(0) if size < MAXCHUNKSIZE: self._data, self._size = read(size), size return self._data, self._size = FileChunk(read(size)), size return # Make sure we have an _p_jar, even if we are a new object, by # doing a sub-transaction commit. transaction.savepoint(optimistic=True) jar = self._p_jar if jar is None: # Ugh seek(0) self._data, self._size = FileChunk(read(size)), size return # Now we're going to build a linked list from back # to front to minimize the number of database updates # and to allow us to get things out of memory as soon as # possible. next = None while end > 0: pos = end - MAXCHUNKSIZE if pos < MAXCHUNKSIZE: pos = 0 # we always want at least MAXCHUNKSIZE bytes seek(pos) data = FileChunk(read(end - pos)) # Woooop Woooop Woooop! This is a trick. # We stuff the data directly into our jar to reduce the # number of updates necessary. jar.add(data) # This is needed and has side benefit of getting # the thing registered: data.next = next # Now make it get saved in a sub-transaction! transaction.savepoint(optimistic=True) # Now make it a ghost to free the memory. We # don't need it anymore! data._p_changed = None next = data end = pos self._data, self._size = next, size return def getSize(self): '''See `IFile`''' return self._size # See IFile. data = property(_getData, _setData) class FileChunk(Persistent): """Wrapper for possibly large data""" next = None def __init__(self, data): self._data = data def __getitem__(self, i): return self._data[i] def __len__(self): data = bytes(self) return len(data) def __bytes__(self): next = self.next if next is None: return self._data result = [self._data] while next is not None: self = next result.append(self._data) next = self.next return b''.join(result) if str is bytes: __str__ = __bytes__ else: def __str__(self): return self.__bytes__().decode("iso-8859-1", errors='ignore') class FileReadFile(object): '''Adapter for file-system style read access. >>> file = File() >>> content = b"This is some file\\ncontent." >>> file.data = content >>> file.contentType = "text/plain" >>> FileReadFile(file).read() == content True >>> FileReadFile(file).size() == len(content) True ''' def __init__(self, context): self.context = context def read(self): return self.context.data def size(self): return len(self.context.data) class FileWriteFile(object): """Adapter for file-system style write access. >>> file = File() >>> content = b"This is some file\\ncontent." >>> FileWriteFile(file).write(content) >>> file.data == content True """ def __init__(self, context): self.context = context def write(self, data): self.context.data = data
zope.app.file
/zope.app.file-4.0.0.tar.gz/zope.app.file-4.0.0/src/zope/app/file/file.py
file.py
__docformat__ = 'restructuredtext' import struct from io import BytesIO from zope.interface import implementer from zope.size.interfaces import ISized from zope.size import byteDisplay from zope.contenttype import guess_content_type from zope.app.file.i18n import ZopeMessageFactory as _ from zope.app.file.file import File from zope.app.file.interfaces import IImage @implementer(IImage) class Image(File): def __init__(self, data=b''): '''See interface `IFile`''' contentType, self._width, self._height = getImageInfo(data) super(Image, self).__init__(data, contentType) def _setData(self, data): super(Image, self)._setData(data) contentType, self._width, self._height = getImageInfo(self._data) if contentType: self.contentType = contentType def getImageSize(self): '''See interface `IImage`''' return (self._width, self._height) data = property(File._getData, _setData) @implementer(ISized) class ImageSized(object): def __init__(self, image): self._image = image def sizeForSorting(self): '''See `ISized`''' return ('byte', self._image.getSize()) def sizeForDisplay(self): '''See `ISized`''' w, h = self._image.getImageSize() if w < 0: w = '?' if h < 0: h = '?' bytes = self._image.getSize() byte_size = byteDisplay(bytes) mapping = byte_size.mapping if mapping is None: mapping = {} mapping.update({'width': str(w), 'height': str(h)}) #TODO the way this message id is defined, it won't be picked up by # i18nextract and never show up in message catalogs return _(byte_size + ' ${width}x${height}', mapping=mapping) class FileFactory(object): def __init__(self, context): self.context = context def __call__(self, name, content_type, data): if not content_type and data: content_type, _width, _height = getImageInfo(data) if not content_type: content_type, _encoding = guess_content_type(name, data, '') if content_type.startswith('image/'): return Image(data) return File(data, content_type) def getImageInfo(data): data = bytes(data) size = len(data) height = -1 width = -1 content_type = '' # handle GIFs if (size >= 10) and data[:6] in (b'GIF87a', b'GIF89a'): # Check to see if content_type is correct content_type = 'image/gif' w, h = struct.unpack(b"<HH", data[6:10]) width = int(w) height = int(h) # See PNG 2. Edition spec (http://www.w3.org/TR/PNG/) # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR' # and finally the 4-byte width, height elif ((size >= 24) and data.startswith(b'\211PNG\r\n\032\n') and (data[12:16] == b'IHDR')): content_type = 'image/png' w, h = struct.unpack(b">LL", data[16:24]) width = int(w) height = int(h) # Maybe this is for an older PNG version. elif (size >= 16) and data.startswith(b'\211PNG\r\n\032\n'): # pragma: no cover # Check to see if we have the right content type content_type = 'image/png' w, h = struct.unpack(">LL", data[8:16]) width = int(w) height = int(h) # handle JPEGs elif (size >= 2) and data.startswith(b'\xff\xd8'): content_type = 'image/jpeg' jpeg = BytesIO(data) jpeg.read(2) b = jpeg.read(1) try: w = -1 h = -1 while b and ord(b) != 0xDA: while ord(b) != 0xFF: b = jpeg.read(1) while ord(b) == 0xFF: b = jpeg.read(1) if 0xC0 <= ord(b) <= 0xC3: jpeg.read(3) h, w = struct.unpack(b">HH", jpeg.read(4)) break else: jpeg.read(int(struct.unpack(b">H", jpeg.read(2))[0])-2) b = jpeg.read(1) width = int(w) height = int(h) except (struct.error, ValueError): # pragma: no cover pass # handle BMPs elif (size >= 30) and data.startswith(b'BM'): kind = struct.unpack(b"<H", data[14:16])[0] if kind == 40: # Windows 3.x bitmap content_type = 'image/x-ms-bmp' width, height = struct.unpack(b"<LL", data[18:26]) return content_type, width, height
zope.app.file
/zope.app.file-4.0.0.tar.gz/zope.app.file-4.0.0/src/zope/app/file/image.py
image.py
from __future__ import print_function import zope.event from zope import lifecycleevent from zope.contenttype import guess_content_type import zope.contenttype.parse from zope.schema import Text from zope.exceptions.interfaces import UserError from zope.app.file.file import File from zope.app.file.interfaces import IFile from zope.app.file.i18n import ZopeMessageFactory as _ from zope.dublincore.interfaces import IDCTimes import zope.datetime from datetime import datetime __docformat__ = 'restructuredtext' class FileView(object): request = None context = None def show(self): """Sets various headers if the request is present and returns the data of the file. If the "If-Modified-Since" header is set and the context is adaptable to IDCTimes, data is only returned if the modification date of the context is newer than the date in the "If-Modified-Since" header >>> from zope.publisher.browser import BrowserView, TestRequest >>> class FileTestView(FileView, BrowserView): pass >>> import pytz >>> class MyFile(object): ... contentType = 'text/plain' ... data = b"data of file" ... modified = datetime(2006,1,1,tzinfo=pytz.utc) ... def getSize(self): ... return len(self.data) >>> aFile = MyFile() >>> request = TestRequest() >>> view = FileTestView(aFile,request) >>> view.show() == MyFile.data True >>> request.response.getHeader('Content-Type') 'text/plain' >>> request.response.getHeader('Content-Length') '12' If the file is adaptable to IDCTimes the "Last-Modified" header is also set. >>> request.response.getHeader('Last-Modified') is None True For the test we just declare that our file provides IZopeDublinCore >>> from zope.dublincore.interfaces import IZopeDublinCore >>> from zope.interface import directlyProvides >>> directlyProvides(aFile,IZopeDublinCore) >>> request = TestRequest() >>> view = FileTestView(aFile,request) >>> view.show() == MyFile.data True >>> request.response.getHeader('Last-Modified') 'Sun, 01 Jan 2006 00:00:00 GMT' If the "If-Modified-Since" header is set and is newer a 304 status is returned and the value is empty. >>> modified = datetime(2007,12,31,tzinfo=pytz.utc) >>> modHeader = zope.datetime.rfc1123_date(zope.datetime.time(modified.isoformat())) >>> request = TestRequest(IF_MODIFIED_SINCE=modHeader) >>> view = FileTestView(aFile,request) >>> view.show() == b'' True >>> request.response.getStatus() 304 An invalid value for that header is ignored. >>> request = TestRequest(IF_MODIFIED_SINCE="Not Valid") >>> view = FileTestView(aFile,request) >>> view.show() == MyFile.data True """ if self.request is not None: self.request.response.setHeader('Content-Type', self.context.contentType) self.request.response.setHeader('Content-Length', self.context.getSize()) try: modified = IDCTimes(self.context).modified except TypeError: modified = None if modified is None or not isinstance(modified,datetime): return self.context.data header = self.request.getHeader('If-Modified-Since', None) lmt = zope.datetime.time(modified.isoformat()) if header is not None: header = header.split(';')[0] try: mod_since = int(zope.datetime.time(header)) except zope.datetime.SyntaxError: mod_since = None if mod_since is not None: if lmt <= mod_since: self.request.response.setStatus(304) return b'' self.request.response.setHeader('Last-Modified', zope.datetime.rfc1123_date(lmt)) return self.context.data def cleanupFileName(filename): return filename.split('\\')[-1].split('/')[-1] class FileUpdateView(object): def __init__(self, context, request): self.context = context self.request = request def errors(self): form = self.request.form if "UPDATE_SUBMIT" in form: filename = getattr(form["field.data"], "filename", None) contenttype = form.get("field.contentType") if filename: filename = cleanupFileName(filename) if not contenttype: contenttype = guess_content_type(filename)[0] if not form.get("add_input_name"): form["add_input_name"] = filename return self.update_object(form["field.data"], contenttype) return '' class FileAdd(FileUpdateView): """View that adds a new File object based on a file upload. >>> class FauxAdding(object): ... def add(self, content): ... self.content = content ... def nextURL(self): ... return 'next url' >>> from zope.publisher.browser import TestRequest >>> from io import BytesIO >>> sio = BytesIO(b"some data") >>> sio.filename = 'abc.txt' Let's make sure we can use the uploaded file name if one isn't specified by the user, and can use the content type when specified. >>> request = TestRequest(form={'field.data': sio, ... 'field.contentType': 'text/foobar', ... 'UPDATE_SUBMIT': 'Add'}) >>> adding = FauxAdding() >>> view = FileAdd(adding, request) >>> view.errors() '' >>> adding.content.contentType 'text/foobar' >>> adding.content.data == b'some data' True >>> request.form['add_input_name'] 'abc.txt' Now let's guess the content type, but also use a provided file name for adding the new content object: >>> request = TestRequest(form={'field.data': sio, ... 'field.contentType': '', ... 'add_input_name': 'splat.txt', ... 'UPDATE_SUBMIT': 'Add'}) >>> adding = FauxAdding() >>> view = FileAdd(adding, request) >>> view.errors() '' >>> adding.content.contentType 'text/plain' >>> request.form['add_input_name'] 'splat.txt' """ def update_object(self, data, contenttype): f = File(data, contenttype) zope.event.notify(lifecycleevent.ObjectCreatedEvent(f)) self.context.add(f) self.request.response.redirect(self.context.nextURL()) return '' class FileUpload(FileUpdateView): """View that updates an existing File object with a new upload. Fires an ObjectModifiedEvent. >>> from zope.publisher.browser import TestRequest >>> from io import BytesIO >>> sio = BytesIO(b"some data") >>> sio.filename = 'abc.txt' Before we instanciate the request, we need to make sure that the ``IUserPreferredLanguages`` adapter exists, so that the request's locale exists. This is necessary because the ``update_object`` method uses the locale formatter for the status message: >>> from zope import component as ztapi >>> from zope.publisher.browser import BrowserLanguages >>> from zope.publisher.interfaces.http import IHTTPRequest >>> from zope.i18n.interfaces import IUserPreferredLanguages >>> ztapi.provideAdapter(BrowserLanguages, (IHTTPRequest,), IUserPreferredLanguages) We install an event logger so we can see the events generated: >>> def eventLog(event): ... print('ModifiedEvent:', event.descriptions[0].attributes) >>> zope.event.subscribers.append(eventLog) Let's make sure we can use the uploaded file name if one isn't specified by the user, and can use the content type when specified. >>> request = TestRequest(form={'field.data': sio, ... 'field.contentType': 'text/foobar', ... 'UPDATE_SUBMIT': 'Update'}) >>> file = File() >>> view = FileUpload(file, request) >>> view.errors() ModifiedEvent: ('contentType', 'data') u'Updated on ${date_time}' >>> file.contentType 'text/foobar' >>> file.data == b'some data' True Now let's guess the content type, but also use a provided file name for adding the new content object: >>> request = TestRequest(form={'field.data': sio, ... 'field.contentType': '', ... 'add_input_name': 'splat.txt', ... 'UPDATE_SUBMIT': 'Update'}) >>> file = File() >>> view = FileUpload(file, request) >>> view.errors() ModifiedEvent: ('contentType', 'data') u'Updated on ${date_time}' >>> file.contentType 'text/plain' The ObjectModifiedEvent lists only the contentType if the data are omitted: >>> request = TestRequest(form={'field.data': None, ... 'field.contentType': '', ... 'add_input_name': 'splat.txt', ... 'UPDATE_SUBMIT': 'Update'}) >>> file = File() >>> view = FileUpload(file, request) >>> view.errors() ModifiedEvent: ('contentType',) u'Updated on ${date_time}' Cleanup: >>> zope.event.subscribers.remove(eventLog) """ def update_object(self, data, contenttype): self.context.contentType = contenttype descriptor = lifecycleevent.Attributes(IFile, "contentType") # Update *only* if a new value is specified if data: self.context.data = data descriptor.attributes += ("data",) event = lifecycleevent.ObjectModifiedEvent(self.context, descriptor) zope.event.notify(event) formatter = self.request.locale.dates.getFormatter( 'dateTime', 'medium') return _("Updated on ${date_time}", mapping={'date_time': formatter.format(datetime.utcnow())}) class IFileEditForm(IFile): """Schema for the File edit form. Replaces the Bytes `data` field with a Text field. """ data = Text( title=_(u'Data'), description=_(u'The actual content of the object.'), default=u'', missing_value=u'', required=False, ) class UnknownCharset(Exception): """Unknown character set.""" class CharsetTooWeak(Exception): """Character set cannot encode all characters in text.""" class FileEdit(object): r"""File edit form mixin. Lets the user edit a text file directly via a browser form. Converts between Unicode strings used in browser forms and 8-bit strings stored internally. >>> from zope.publisher.browser import BrowserView, TestRequest >>> class FileEditView(FileEdit, BrowserView): pass >>> view = FileEditView(File(), TestRequest()) >>> view.getData()['data'] u'' >>> view.getData()['contentType'] '' We install an event logger so we can see the events generated. >>> def eventLog(event): ... print(event.__class__.__name__, event.descriptions[0].attributes) >>> zope.event.subscribers.append(eventLog) >>> view.setData({'contentType': 'text/plain; charset=ISO-8859-13', ... 'data': u'text \u0105'}) # doctest:+ELLIPSIS ObjectModifiedEvent ('data', 'contentType') u'Updated on ${date_time}' >>> view.context.contentType 'text/plain; charset=ISO-8859-13' >>> view.context.data == b'text \xe0' True >>> view.getData()['data'] u'text \u0105' Cleanup eventlog. >>> zope.event.subscribers.remove(eventLog) You will get an error if you try to specify a charset that cannot encode all the characters >>> view.setData({'contentType': 'text/xml; charset=ISO-8859-1', ... 'data': u'text \u0105'}) Traceback (most recent call last): ... zope.app.file.browser.file.CharsetTooWeak: ISO-8859-1 You will get a different error if you try to specify an invalid charset >>> view.setData({'contentType': 'text/xml; charset=UNKNOWN', ... 'data': u'text \u0105'}) Traceback (most recent call last): ... zope.app.file.browser.file.UnknownCharset: UNKNOWN The update method catches those errors and replaces them with error messages >>> from zope.i18n import translate >>> class FakeFormView(BrowserView): ... def update(self): ... raise CharsetTooWeak('ASCII') >>> class FileEditView(FileEdit, FakeFormView): pass >>> view = FileEditView(File(), TestRequest()) >>> translate(view.update()) u'The character set you specified (ASCII) cannot encode all characters in text.' >>> translate(view.update_status) u'The character set you specified (ASCII) cannot encode all characters in text.' >>> class FakeFormView(BrowserView): ... def update(self): ... raise UnknownCharset('UNKNOWN') >>> class FileEditView(FileEdit, FakeFormView): pass >>> view = FileEditView(File(), TestRequest()) >>> translate(view.update()) u'The character set you specified (UNKNOWN) is not supported.' >>> translate(view.update_status) u'The character set you specified (UNKNOWN) is not supported.' Speaking about errors, if you trick the system and upload a file with incorrect charset designation, you will get a UserError when you visit the view: >>> view.context.contentType = 'text/plain; charset=UNKNOWN' >>> view.context.data = b'\xff' >>> view.getData() Traceback (most recent call last): ... zope.exceptions.interfaces.UserError: The character set specified in the content type ($charset) is not supported. >>> view.context.contentType = 'text/plain; charset=UTF-8' >>> view.context.data = b'\xff' >>> view.getData() Traceback (most recent call last): ... zope.exceptions.interfaces.UserError: The character set specified in the content type ($charset) does not match file content. """ context = None request = None error = None def getData(self): charset = extractCharset(self.context.contentType) try: return {'contentType': self.context.contentType, 'data': self.context.data.decode(charset)} except LookupError: msg = _("The character set specified in the content type" " ($charset) is not supported.", mapping={'charset': charset}) raise UserError(msg) except UnicodeDecodeError: msg = _("The character set specified in the content type" " ($charset) does not match file content.", mapping={'charset': charset}) raise UserError(msg) def setData(self, data): charset = extractCharset(data['contentType']) try: encodeddata = data['data'].encode(charset) except LookupError: raise UnknownCharset(charset) except UnicodeEncodeError: raise CharsetTooWeak(charset) modified = [] if encodeddata != self.context.data: self.context.data = encodeddata modified.append('data') if self.context.contentType != data['contentType']: self.context.contentType = data['contentType'] modified.append('contentType') formatter = self.request.locale.dates.getFormatter('dateTime', 'medium') if modified: event = lifecycleevent.ObjectModifiedEvent( self.context, lifecycleevent.Attributes(IFile, *modified)) zope.event.notify(event) return _("Updated on ${date_time}", mapping={'date_time': formatter.format(datetime.utcnow())}) def update(self): try: return super(FileEdit, self).update() except CharsetTooWeak as charset: self.update_status = _("The character set you specified ($charset)" " cannot encode all characters in text.", mapping={'charset': charset}) return self.update_status except UnknownCharset as charset: self.update_status = _("The character set you specified ($charset)" " is not supported.", mapping={'charset': charset}) return self.update_status def extractCharset(content_type): """Extract charset information from a MIME type. >>> extractCharset('text/plain; charset=US-ASCII') 'US-ASCII' >>> extractCharset('text/html; charset=ISO-8859-1') 'ISO-8859-1' >>> extractCharset('text/plain') 'UTF-8' """ if content_type and content_type.strip(): _major, _minor, params = zope.contenttype.parse.parse(content_type) return params.get("charset", "UTF-8") return "UTF-8"
zope.app.file
/zope.app.file-4.0.0.tar.gz/zope.app.file-4.0.0/src/zope/app/file/browser/file.py
file.py
Special URL handling for DTML pages =================================== When an HTML File page containing a head tag is visited, without a trailing slash, the base href isn't set. When visited with a slash, it is: >>> print(http(r""" ... POST /+/zope.app.file.File%3D HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Length: 610 ... Content-Type: multipart/form-data; boundary=---------------------------32826232819858510771857533856 ... Referer: http://localhost:8081/+/zope.app.file.File= ... ... -----------------------------32826232819858510771857533856 ... Content-Disposition: form-data; name="field.contentType" ... ... text/html ... -----------------------------32826232819858510771857533856 ... Content-Disposition: form-data; name="field.data"; filename="" ... Content-Type: application/octet-stream ... ... ... -----------------------------32826232819858510771857533856 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------32826232819858510771857533856 ... Content-Disposition: form-data; name="add_input_name" ... ... file.html ... -----------------------------32826232819858510771857533856-- ... """)) HTTP/1.1 303 See Other ... >>> print(http(r""" ... POST /file.html/edit.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Length: 507 ... Content-Type: multipart/form-data; boundary=---------------------------10196264131256436092131136054 ... Referer: http://localhost:8081/file.html/edit.html ... ... -----------------------------10196264131256436092131136054 ... Content-Disposition: form-data; name="field.contentType" ... ... text/html ... -----------------------------10196264131256436092131136054 ... Content-Disposition: form-data; name="field.data" ... ... <html> ... <head></head> ... <body> ... <a href="eek.html">Eek</a> ... </body> ... </html> ... -----------------------------10196264131256436092131136054 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Change ... -----------------------------10196264131256436092131136054-- ... """)) HTTP/1.1 200 OK ... >>> print(http(r""" ... GET /file.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... """)) HTTP/1.1 200 OK ... <html> <head></head> <body> <a href="eek.html">Eek</a> </body> </html> >>> print(http(r""" ... GET /file.html/ HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... """)) HTTP/1.1 200 OK ... <html> <head> <base href="http://localhost/file.html" /> </head> <body> <a href="eek.html">Eek</a> </body> </html>
zope.app.file
/zope.app.file-4.0.0.tar.gz/zope.app.file-4.0.0/src/zope/app/file/browser/url.rst
url.rst
File objects ============ Adding Files ------------ You can add File objects from the common tasks menu in the ZMI. >>> result = http(r""" ... GET /@@contents.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... """) >>> "http://localhost/@@+/action.html?type_name=zope.app.file.File" in str(result) True Let's follow that link. >>> print(http(r""" ... GET /@@+/action.html?type_name=zope.app.file.File HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... """, handle_errors=False)) HTTP/1.1 303 See Other Content-Length: ... Location: http://localhost/+/zope.app.file.File= <BLANKLINE> The file add form lets you specify the content type, the object name, and optionally upload the contents of the file. >>> print(http(r""" ... GET /+/zope.app.file.File= HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... """)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/html;charset=utf-8 <BLANKLINE> ... <title>Z3: +</title> ... ... <form action="http://localhost/+/zope.app.file.File%3D" method="post" enctype="multipart/form-data"> <h3>Add a File</h3> ...<input class="textType" id="field.contentType" name="field.contentType" size="20" type="text" value="" />... ...<input class="fileType" id="field.data" name="field.data" size="20" type="file" />... <div class="controls"><hr /> <input type="submit" value="Refresh" /> <input type="submit" value="Add" name="UPDATE_SUBMIT" /> &nbsp;&nbsp;<b>Object Name</b>&nbsp;&nbsp; <input type="text" name="add_input_name" value="" /> </div> ... </form> ... Binary Files ------------ Let us upload a binary file. >>> print(http(b""" ... POST /+/zope.app.file.File%3D HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Type: multipart/form-data; boundary=---------------------------73793505419963331401738523176 ... ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="field.contentType" ... ... application/octet-stream ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="field.data"; filename="hello.txt.gz" ... Content-Type: application/x-gzip ... ... \x1f\x8b\x08\x08\xcb\x48\xea\x42\x00\x03\x68\x65\x6c\x6c\x6f\x2e\ ... \x74\x78\x74\x00\xcb\x48\xcd\xc9\xc9\xe7\x02\x00\x20\x30\x3a\x36\ ... \x06\x00\x00\x00 ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------73793505419963331401738523176-- ... """)) HTTP/1.1 303 See Other Content-Length: ... Content-Type: text/html;charset=utf-8 Location: http://localhost/@@contents.html <BLANKLINE> ... Since we did not specify the object name in the form, Zope 3 will use the filename. >>> response = http(""" ... GET /hello.txt.gz HTTP/1.1 ... """) >>> print(response) HTTP/1.1 200 OK Content-Length: 36 Content-Type: application/octet-stream <BLANKLINE> ... Let's make sure the (binary) content of the file is correct >>> response.getBody() == b'\x1f\x8b\x08\x08\xcbH\xeaB\x00\x03hello.txt\x00\xcbH\xcd\xc9\xc9\xe7\x02\x00 0:6\x06\x00\x00\x00' True Also, lets test a (bad) filename with full path that generates MS Internet Explorer, Zope should process it successfully and get the actual filename. Let's upload the same file with bad filename. >>> print(http(b""" ... POST /+/zope.app.file.File%3D HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Type: multipart/form-data; boundary=---------------------------73793505419963331401738523176 ... ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="field.contentType" ... ... application/octet-stream ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="field.data"; filename="c:\\windows\\test.gz" ... Content-Type: application/x-gzip ... ... \x1f\x8b\x08\x08\xcb\x48\xea\x42\x00\x03\x68\x65\x6c\x6c\x6f\x2e\ ... \x74\x78\x74\x00\xcb\x48\xcd\xc9\xc9\xe7\x02\x00\x20\x30\x3a\x36\ ... \x06\x00\x00\x00 ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------73793505419963331401738523176-- ... """)) HTTP/1.1 303 See Other Content-Length: ... Content-Type: text/html;charset=utf-8 Location: http://localhost/@@contents.html <BLANKLINE> ... The file should be saved as "test.gz", let's check it name and contents. >>> response = http(""" ... GET /test.gz HTTP/1.1 ... """) >>> print(response) HTTP/1.1 200 OK Content-Length: 36 Content-Type: application/octet-stream <BLANKLINE> ... >>> response.getBody() == b'\x1f\x8b\x08\x08\xcbH\xeaB\x00\x03hello.txt\x00\xcbH\xcd\xc9\xc9\xe7\x02\x00 0:6\x06\x00\x00\x00' True Text Files ---------- Let us now create a text file. >>> print(http(r""" ... POST /+/zope.app.file.File%3D HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Type: multipart/form-data; boundary=---------------------------167769037320366690221542301033 ... ... -----------------------------167769037320366690221542301033 ... Content-Disposition: form-data; name="field.contentType" ... ... text/plain ... -----------------------------167769037320366690221542301033 ... Content-Disposition: form-data; name="field.data"; filename="" ... Content-Type: application/octet-stream ... ... ... -----------------------------167769037320366690221542301033 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------167769037320366690221542301033 ... Content-Disposition: form-data; name="add_input_name" ... ... sample.txt ... -----------------------------167769037320366690221542301033-- ... """)) HTTP/1.1 303 See Other Content-Length: ... Content-Type: text/html;charset=utf-8 Location: http://localhost/@@contents.html <BLANKLINE> ... The file is initially empty, since we did not upload anything. >>> print(http(""" ... GET /sample.txt HTTP/1.1 ... """)) HTTP/1.1 200 OK Content-Length: 0 Content-Type: text/plain Last-Modified: ... <BLANKLINE> Since it is a text file, we can edit it directly in a web form. >>> print(http(r""" ... GET /sample.txt/edit.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... """, handle_errors=False)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/html;charset=utf-8 <BLANKLINE> ... <title>Z3: sample.txt</title> ... <form action="http://localhost/sample.txt/edit.html" method="post" enctype="multipart/form-data"> <div> <h3>Change a file</h3> ...<input class="textType" id="field.contentType" name="field.contentType" size="20" type="text" value="text/plain" />... ...<textarea cols="60" id="field.data" name="field.data" rows="15" ></textarea>... ... <div class="controls"> <input type="submit" value="Refresh" /> <input type="submit" name="UPDATE_SUBMIT" value="Change" /> </div> ... </form> ... Files of type text/plain without any charset information can contain UTF-8 text. So you can use ASCII text. >>> print(http(r""" ... POST /sample.txt/edit.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Type: multipart/form-data; boundary=---------------------------165727764114325486311042046845 ... ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="field.contentType" ... ... text/plain ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="field.data" ... ... This is a sample text file. ... ... It can contain US-ASCII characters. ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Change ... -----------------------------165727764114325486311042046845-- ... """, handle_errors=False)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/html;charset=utf-8 <BLANKLINE> ... <title>Z3: sample.txt</title> ... <form action="http://localhost/sample.txt/edit.html" method="post" enctype="multipart/form-data"> <div> <h3>Change a file</h3> <BLANKLINE> <p>Updated on ...</p> <BLANKLINE> <div class="row"> ...<input class="textType" id="field.contentType" name="field.contentType" size="20" type="text" value="text/plain" />... <div class="row"> ...<textarea cols="60" id="field.data" name="field.data" rows="15" >This is a sample text file. <BLANKLINE> It can contain US-ASCII characters.</textarea></div> ... <div class="controls"> <input type="submit" value="Refresh" /> <input type="submit" name="UPDATE_SUBMIT" value="Change" /> </div> ... </form> ... Here's the file >>> print(http(r""" ... GET /sample.txt HTTP/1.1 ... """)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/plain Last-Modified: ... <BLANKLINE> This is a sample text file. <BLANKLINE> It can contain US-ASCII characters. Non-ASCII Text Files -------------------- We can also use non-ASCII charactors in text file. >>> print(http(""" ... POST /sample.txt/edit.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Type: multipart/form-data; boundary=---------------------------165727764114325486311042046845 ... ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="field.contentType" ... ... text/plain ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="field.data" ... ... This is a sample text file. ... ... It can contain non-ASCII(UTF-8) characters, e.g. \xe2\x98\xbb (U+263B BLACK SMILING FACE). ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Change ... -----------------------------165727764114325486311042046845-- ... """)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/html;charset=utf-8 <BLANKLINE> ... <title>Z3: sample.txt</title> ... <form action="http://localhost/sample.txt/edit.html" method="post" enctype="multipart/form-data"> <div> <h3>Change a file</h3> <BLANKLINE> <p>Updated on ...</p> <BLANKLINE> <div class="row"> ...<input class="textType" id="field.contentType" name="field.contentType" size="20" type="text" value="text/plain" />... <div class="row"> ...<textarea cols="60" id="field.data" name="field.data" rows="15" >This is a sample text file. <BLANKLINE> It can contain non-ASCII(UTF-8) characters, e.g. ... (U+263B BLACK SMILING FACE).</textarea></div> ... <div class="controls"> <input type="submit" value="Refresh" /> <input type="submit" name="UPDATE_SUBMIT" value="Change" /> </div> ... </form> ... Here's the file >>> response = http(r""" ... GET /sample.txt HTTP/1.1 ... """) >>> print(response) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/plain Last-Modified: ... <BLANKLINE> This is a sample text file. <BLANKLINE> It can contain non-ASCII(UTF-8) characters, e.g. ... (U+263B BLACK SMILING FACE). >>> u'\u263B' in response.getBody().decode('UTF-8') True And you can explicitly specify the charset. Note that the browser form is always UTF-8. >>> print(http(""" ... POST /sample.txt/edit.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Type: multipart/form-data; boundary=---------------------------165727764114325486311042046845 ... ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="field.contentType" ... ... text/plain; charset=ISO-8859-1 ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="field.data" ... ... This is a sample text file. ... ... It now contains Latin-1 characters, e.g. \xc2\xa7 (U+00A7 SECTION SIGN). ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Change ... -----------------------------165727764114325486311042046845-- ... """)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/html;charset=utf-8 <BLANKLINE> ... <title>Z3: sample.txt</title> ... <form action="http://localhost/sample.txt/edit.html" method="post" enctype="multipart/form-data"> <div> <h3>Change a file</h3> <BLANKLINE> <p>Updated on ...</p> <BLANKLINE> <div class="row"> ...<input class="textType" id="field.contentType" name="field.contentType" size="20" type="text" value="text/plain; charset=ISO-8859-1" />... <div class="row"> ...<textarea cols="60" id="field.data" name="field.data" rows="15" >This is a sample text file. <BLANKLINE> It now contains Latin-1 characters, e.g. ... (U+00A7 SECTION SIGN).</textarea></div> ... <div class="controls"> <input type="submit" value="Refresh" /> <input type="submit" name="UPDATE_SUBMIT" value="Change" /> </div> ... </form> ... Here's the file >>> response = http(r""" ... GET /sample.txt HTTP/1.1 ... """) >>> print(response) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/plain; charset=ISO-8859-1 Last-Modified: ... <BLANKLINE> This is a sample text file. <BLANKLINE> It now contains Latin-1 characters, e.g. ... (U+00A7 SECTION SIGN). Body is actually encoded in ISO-8859-1, and not UTF-8 >>> response.getBody().splitlines()[-1].decode('latin-1') 'It now contains Latin-1 characters, e.g. \xa7 (U+00A7 SECTION SIGN).' The user is not allowed to specify a character set that cannot represent all the characters. >>> print(http(""" ... POST /sample.txt/edit.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Type: multipart/form-data; boundary=---------------------------165727764114325486311042046845 ... ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="field.contentType" ... ... text/plain; charset=US-ASCII ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="field.data" ... ... This is a slightly changed sample text file. ... ... It now contains Latin-1 characters, e.g. \xc2\xa7 (U+00A7 SECTION SIGN). ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Change ... -----------------------------165727764114325486311042046845-- ... """, handle_errors=False)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/html;charset=utf-8 <BLANKLINE> ... <title>Z3: sample.txt</title> ... <form action="http://localhost/sample.txt/edit.html" method="post" enctype="multipart/form-data"> <div> <h3>Change a file</h3> <BLANKLINE> <p>The character set you specified (US-ASCII) cannot encode all characters in text.</p> <BLANKLINE> <div class="row"> ...<input class="textType" id="field.contentType" name="field.contentType" size="20" type="text" value="text/plain; charset=US-ASCII" />... <div class="row"> ...<textarea cols="60" id="field.data" name="field.data" rows="15" >This is a slightly changed sample text file. <BLANKLINE> It now contains Latin-1 characters, e.g. ... (U+00A7 SECTION SIGN).</textarea></div> ... <div class="controls"> <input type="submit" value="Refresh" /> <input type="submit" name="UPDATE_SUBMIT" value="Change" /> </div> ... </form> ... Likewise, the user is not allowed to specify a character set that is not supported by Python. >>> print(http(""" ... POST /sample.txt/edit.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Type: multipart/form-data; boundary=---------------------------165727764114325486311042046845 ... ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="field.contentType" ... ... text/plain; charset=I-INVENT-MY-OWN ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="field.data" ... ... This is a slightly changed sample text file. ... ... It now contains just ASCII characters. ... -----------------------------165727764114325486311042046845 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Change ... -----------------------------165727764114325486311042046845-- ... """, handle_errors=False)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/html;charset=utf-8 <BLANKLINE> ... <title>Z3: sample.txt</title> ... <form action="http://localhost/sample.txt/edit.html" method="post" enctype="multipart/form-data"> <div> <h3>Change a file</h3> <BLANKLINE> <p>The character set you specified (I-INVENT-MY-OWN) is not supported.</p> <BLANKLINE> <div class="row"> ...<input class="textType" id="field.contentType" name="field.contentType" size="20" type="text" value="text/plain; charset=I-INVENT-MY-OWN" />... <div class="row"> ...<textarea cols="60" id="field.data" name="field.data" rows="15" >This is a slightly changed sample text file. <BLANKLINE> It now contains just ASCII characters.</textarea></div> ... <div class="controls"> <input type="submit" value="Refresh" /> <input type="submit" name="UPDATE_SUBMIT" value="Change" /> </div> ... </form> ... If you trick Zope and upload a file with a content type that does not match the file contents, you will not be able to access the edit view: >>> print(http(r""" ... GET /hello.txt.gz/@@edit.html HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... """, handle_errors=True)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/html;charset=utf-8 <BLANKLINE> ... <li>The character set specified in the content type (UTF-8) does not match file content.</li> ... Non-ASCII Filenames ------------------- Filenames are not restricted to ASCII. >>> print(http(b""" ... POST /+/zope.app.file.File%3D HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... Content-Type: multipart/form-data; boundary=---------------------------73793505419963331401738523176 ... ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="field.contentType" ... ... application/octet-stream ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="field.data"; filename="bj\xc3\xb6rn.txt.gz" ... Content-Type: application/x-gzip ... ... \x1f\x8b\x08\x08\xcb\x48\xea\x42\x00\x03\x68\x65\x6c\x6c\x6f\x2e\ ... \x74\x78\x74\x00\xcb\x48\xcd\xc9\xc9\xe7\x02\x00\x20\x30\x3a\x36\ ... \x06\x00\x00\x00 ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Add ... -----------------------------73793505419963331401738523176 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------73793505419963331401738523176-- ... """)) HTTP/1.1 303 See Other Content-Length: ... Content-Type: text/html;charset=utf-8 Location: http://localhost/@@contents.html <BLANKLINE> ... Since we did not specify the object name in the form, Zope 3 will use the filename. >>> response = http(""" ... GET /bj%C3%B6rn.txt.gz HTTP/1.1 ... """) >>> print(response) HTTP/1.1 200 OK Content-Length: 36 Content-Type: application/octet-stream <BLANKLINE> ...
zope.app.file
/zope.app.file-4.0.0.tar.gz/zope.app.file-4.0.0/src/zope/app/file/browser/file.rst
file.rst
__docformat__ = 'restructuredtext' from zope.size.interfaces import ISized from zope.app.file.browser.file import FileView, cleanupFileName from zope.traversing.browser.absoluteurl import absoluteURL class ImageData(FileView): def __call__(self): return self.show() def tag(self, height=None, width=None, alt=None, scale=0, xscale=0, yscale=0, css_class=None, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to ``self.tag()`` can be any valid attributes of an IMG tag. `src` will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for `height`, `width`, and `alt`. If specified, the `scale`, `xscale`, and `yscale` keyword arguments will be used to automatically adjust the output height and width values of the image tag. Since 'class' is a Python reserved word, it cannot be passed in directly in keyword arguments which is a problem if you are trying to use ``tag()`` to include a CSS class. The `tag()` method will accept a `css_class` argument that will be converted to ``class`` in the output tag to work around this. """ if width is None: width = self.context.getImageSize()[0] if height is None: height = self.context.getImageSize()[1] # Auto-scaling support xdelta = xscale or scale ydelta = yscale or scale if xdelta and width: width = str(int(round(int(width) * xdelta))) if ydelta and height: height = str(int(round(int(height) * ydelta))) result = '<img ' if self.request is not None: result = '<img src="%s"' % absoluteURL(self.context, self.request) if alt is None: alt = getattr(self, 'title', '') result = '%s alt="%s"' % (result, alt) if height is not None: result = '%s height="%s"' % (result, height) if width is not None: result = '%s width="%s"' % (result, width) if not 'border' in [a.lower() for a in args]: result = '%s border="0"' % result if css_class is not None: result = '%s class="%s"' % (result, css_class) for key, value in args.items(): result = '%s %s="%s"' % (result, key, value) return '%s />' % result class ImageUpload(object): """Image edit view mix-in that provides access to image size info""" def size(self): sized = ISized(self.context) return sized.sizeForDisplay() class ImageAdd(object): def update(self): if self.update_status is not None: # We've been called before. Just return the previous result. return self.update_status # set the name of the image if not defined if not self.request.form.get('add_input_name'): filename = getattr(self.request.form.get("field.data"), "filename", None) if filename is not None: self.request.form["add_input_name"] = cleanupFileName(filename) return super(ImageAdd,self).update()
zope.app.file
/zope.app.file-4.0.0.tar.gz/zope.app.file-4.0.0/src/zope/app/file/browser/image.py
image.py
======= CHANGES ======= 5.0 (2023-02-07) ---------------- - 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.0.0 (2017-05-09) ------------------ - Add support for Python 3.4. 3.5, 3.6 and PyPy. 3.5.2 (2010-12-28) ------------------ - Removed testing.py. There are no functional tests and ftesting.zcml now. - Removed unneeded dependencies. 3.5.1 (2009-02-14) ------------------ - Added missing dependency to zope.app.content. - Fixed e-mail address and homepage. - Fixed buildout.cfg, as there is no test extra. 3.5.0 (2009-01-31) ------------------ - Everything except zope.app.folder.browser moved to zope.site and zope.container. - Import IPossibleSite from zope.location.interfaces instead of deprecated place in zope.app.component.interfaces. - Use zope.container instead of zope.app.container. 3.4.0 (2007-10-24) ------------------ - Initial release independent of the main Zope tree.
zope.app.folder
/zope.app.folder-5.0.tar.gz/zope.app.folder-5.0/CHANGES.rst
CHANGES.rst
__docformat__ = 'restructuredtext' from zope.formlib.interfaces import IDisplayWidget from zope.formlib.interfaces import IInputWidget from zope.formlib.interfaces import InputErrors from zope.formlib.interfaces import MissingInputError from zope.formlib.interfaces import WidgetsError # BBB from zope.formlib.utility import _fieldlist from zope.formlib.utility import _widgetHasStickyValue from zope.formlib.utility import applyWidgetsChanges from zope.formlib.utility import no_value from zope.formlib.utility import setUpWidget from zope.formlib.utility import setUpWidgets from zope.interface.interfaces import IMethod from zope.proxy import isProxy from zope.security.interfaces import ForbiddenAttribute from zope.security.interfaces import Unauthorized from zope.security.proxy import Proxy from zope import security def setUpEditWidgets(view, schema, source=None, prefix=None, ignoreStickyValues=False, names=None, context=None, degradeInput=False, degradeDisplay=False): """Sets up widgets to collect input on a view. See `setUpWidgets` for details on `view`, `schema`, `prefix`, `ignoreStickyValues`, `names`, and `context`. `source`, if specified, is an object from which initial widget values are read. If source is not specified, the view context is used as the source. `degradeInput` is a flag that changes the behavior when a user does not have permission to edit a field in the names. By default, the function raises Unauthorized. If degradeInput is True, the field is changed to an IDisplayWidget. `degradeDisplay` is a flag that changes the behavior when a user does not have permission to access a field in the names. By default, the function raises Unauthorized. If degradeDisplay is True, the field is removed from the form. Returns a list of names, equal to or a subset of the names that were supposed to be drawn, with uninitialized undrawn fields missing. """ if context is None: context = view.context if source is None: source = view.context security_proxied = isProxy(source, Proxy) res_names = [] for name, field in _fieldlist(names, schema): try: value = field.get(source) except ForbiddenAttribute: raise except AttributeError: value = no_value except Unauthorized: if degradeDisplay: continue else: raise if field.readonly: viewType = IDisplayWidget else: if security_proxied: is_accessor = IMethod.providedBy(field) if is_accessor: set_name = field.writer.__name__ authorized = security.canAccess(source, set_name) else: set_name = name authorized = security.canWrite(source, name) if not authorized: if degradeInput: viewType = IDisplayWidget else: raise Unauthorized(set_name) else: viewType = IInputWidget else: # if object is not security proxied, might be a standard # adapter without a registered checker. If the feature of # paying attention to the users ability to actually set a # field is decided to be a must-have for the form machinery, # then we ought to change this case to have a deprecation # warning. viewType = IInputWidget setUpWidget(view, name, field, viewType, value, prefix, ignoreStickyValues, context) res_names.append(name) return res_names def setUpDisplayWidgets(view, schema, source=None, prefix=None, ignoreStickyValues=False, names=None, context=None, degradeDisplay=False): """Sets up widgets to display field values on a view. See `setUpWidgets` for details on `view`, `schema`, `prefix`, `ignoreStickyValues`, `names`, and `context`. `source`, if specified, is an object from which initial widget values are read. If source is not specified, the view context is used as the source. `degradeDisplay` is a flag that changes the behavior when a user does not have permission to access a field in the names. By default, the function raises Unauthorized. If degradeDisplay is True, the field is removed from the form. Returns a list of names, equal to or a subset of the names that were supposed to be drawn, with uninitialized undrawn fields missing. """ if context is None: context = view.context if source is None: source = view.context res_names = [] for name, field in _fieldlist(names, schema): try: value = field.get(source) except ForbiddenAttribute: raise except AttributeError: value = no_value except Unauthorized: if degradeDisplay: continue else: raise setUpWidget(view, name, field, IDisplayWidget, value, prefix, ignoreStickyValues, context) res_names.append(name) return res_names def viewHasInput(view, schema, names=None): """Returns ``True`` if the any of the view's widgets contain user input. `schema` specifies the set of fields that correspond to the view widgets. `names` can be specified to provide a subset of these fields. """ for name, field in _fieldlist(names, schema): if getattr(view, name + '_widget').hasInput(): return True return False def getWidgetsData(view, schema, names=None): """Returns user entered data for a set of `schema` fields. The return value is a map of field names to data values. `view` is the view containing the widgets. `schema` is the schema that defines the widget fields. An optional `names` argument can be provided to specify an alternate list of field values to return. If `names` is not specified, or is ``None``, `getWidgetsData` will attempt to return values for all of the fields in the schema. A requested field value may be omitted from the result for one of two reasons: - The field is read only, in which case its widget will not have user input. - The field is editable and not required but its widget does not contain user input. If a field is required and its widget does not have input, `getWidgetsData` raises an error. A widget may raise a validation error if it cannot return a value that satisfies its field's contraints. Errors, if any, are collected for all fields and reraised as a single `WidgetsError`. """ result = {} errors = [] for name, field in _fieldlist(names, schema): widget = getattr(view, name + '_widget') if IInputWidget.providedBy(widget): if widget.hasInput(): try: result[name] = widget.getInputValue() except InputErrors as error: errors.append(error) elif field.required: errors.append(MissingInputError( name, widget.label, 'the field is required')) if errors: raise WidgetsError(errors, widgetsData=result) return result __all__ = [ # BBB '_widgetHasStickyValue', 'applyWidgetsChanges', 'setUpWidget', 'setUpWidgets', # From this module 'getWidgetsData', 'setUpDisplayWidgets', 'setUpEditWidgets', 'viewHasInput', ]
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/utility.py
utility.py
============================================================ Simple example showing ObjectWidget and SequenceWidget usage ============================================================ The following implements a Poll product (add it as zope/app/demo/poll) which has poll options defined as: label A `TextLine` holding the label of the option description Another `TextLine` holding the description of the option Simple stuff. Our Poll product holds an editable list of the `PollOption` instances. First the Schemas are defined in the ``interfaces.py`` file below:: >>> from zope.interface import Interface >>> from zope.schema import Object, Tuple, TextLine >>> from zope.schema.interfaces import ITextLine >>> from zope.i18nmessageid import MessageFactory >>> _ = MessageFactory("poll") >>> class IPollOption(Interface): ... label = TextLine(title=u'Label', min_length=1) ... description = TextLine(title=u'Description', min_length=1) >>> class IPoll(Interface): ... options = Tuple(title=u'Options', ... value_type=Object(IPollOption, title=u'Poll Option')) ... ... def getResponse(option): "get the response for an option" ... ... def choose(option): 'user chooses an option' The implementation is shown in the ``poll.py`` source below:: >>> from persistent import Persistent >>> from zope.interface import implementer, classImplements >>> @implementer(IPollOption) ... class PollOption(Persistent, object): ... pass >>> @implementer(IPoll) ... class Poll(Persistent, object): ... ... def getResponse(self, option): ... return self._responses[option] ... ... def choose(self, option): ... self._responses[option] += 1 ... self._p_changed = 1 ... ... @property ... def options(self): ... return self._options ... ... @options.setter ... def set_options(self, options): ... self._options = options ... self._responses = {} ... for option in self._options: ... self._responses[option.label] = 0 Note the use of the `Tuple` and `Object` schema fields above. The `Tuple` could optionally have restrictions on the min or max number of items - these will be enforced by the `SequenceWidget` form handling code. The `Object` must specify the schema that is used to generate its data. Now we have to specify the actual add and edit views. We use the existing AddView and EditView, but we pre-define the widget for the sequence because we need to pass in additional information. This is given in the ``browser.py`` file:: from zope.app.form.browser.editview import EditView from zope.app.form.browser.add import AddView from zope.formlib.widget import CustomWidgetFactory from zope.app.form.browser import SequenceWidget, ObjectWidget from interfaces import IPoll from poll import Poll, PollOption class PollVoteView: __used_for__ = IPoll def choose(self, option): self.context.choose(option) self.request.response.redirect('.') ow = CustomWidgetFactory(ObjectWidget, PollOption) sw = CustomWidgetFactory(SequenceWidget, subwidget=ow) class PollEditView(EditView): __used_for__ = IPoll options_widget = sw class PollAddView(AddView): __used_for__ = IPoll options_widget = sw Note the creation of the widget via a `CustomWidgetFactory`. So, whenever the options_widget is used, a new ``SequenceWidget(subwidget=CustomWidgetFactory(ObjectWidget, PollOption))`` is created. The subwidget argument indicates that each item in the sequence should be represented by the indicated widget instead of their default. If the contents of the sequence were just `Text` fields, then the default would be just fine - the only odd cases are Sequence and Object Widgets because they need additional arguments when they're created. Each item in the sequence will be represented by a ``CustomWidgetFactory(ObjectWidget, PollOption)`` - thus a new ``ObjectWidget(context, request, PollOption)`` is created for each one. The `PollOption` class ("factory") is used to create new instances when new data is created in add forms (or edit forms when we're adding new items to a Sequence). Tying all this together is the ``configure.zcml``:: <configure xmlns='http://namespaces.zope.org/zope' xmlns:browser='http://namespaces.zope.org/browser'> <content class=".poll.Poll"> <factory id="zope.app.demo.poll" permission="zope.ManageContent" /> <implements interface="zope.annotation.interfaces.IAttributeAnnotatable" /> <require permission="zope.View" interface=".interfaces.IPoll" /> <require permission="zope.ManageContent" set_schema=".interfaces.IPoll" /> </content> <content class=".poll.PollOption"> <require permission="zope.View" interface=".interfaces.IPollOption" /> </content> <browser:page for=".interfaces.IPoll" name="index.html" template="results.zpt" permission="zope.View" /> <browser:pages for=".interfaces.IPoll" class=".browser.PollVoteView" permission="zope.ManageContent"> <browser:page name="vote.html" template="vote.zpt" /> <browser:page name="choose" attribute="choose" /> </browser:pages> <browser:addform schema=".interfaces.IPoll" label="Add a Poll" content_factory=".poll.Poll" name="AddPoll.html" class=".browser.PollAddView" permission="zope.ManageContent" /> <browser:addMenuItem title="Poll Demo" description="Poll Demo" content_factory=".poll.Poll" view="AddPoll.html" permission="zope.ManageContent" /> <browser:editform schema=".interfaces.IPoll" class=".browser.PollEditView" label="Change a Poll" name="edit.html" permission="zope.ManageContent" /> </configure> Note the use of the ``class`` attribute on the ``addform`` and ``editform`` elements. Otherwise, nothing much exciting here. Finally, we have some additional views... ``results.zpt``:: <html metal:use-macro="context/@@standard_macros/page"> <title metal:fill-slot="title">Poll results</title> <div metal:fill-slot="body"> <table border="1"> <caption>Poll results</caption> <thead> <tr><th>Option</th><th>Results</th><th>Description</th></tr> </thead> <tbody> <tr tal:repeat="option context/options"> <td tal:content="option/label">Option</td> <td tal:content="python:context.getResponse(option.label)">Result</td> <td tal:content="option/description">Option</td> </tr> </tbody> </table> </div> </html> ``vote.zpt``:: <html metal:use-macro="context/@@standard_macros/page"> <title metal:fill-slot="title">Poll voting</title> <div metal:fill-slot="body"> <form action="choose"> <table border="1"> <caption>Poll voting</caption> <tbody> <tr tal:repeat="option context/options"> <td><input type="radio" name="option" tal:attributes="value option/label"></td> <td tal:content="option/label">Option</td> <td tal:content="option/description">Option</td> </tr> </tbody> </table> <input type="submit"> </form> </div> </html>
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/widgets.rst
widgets.rst
"""Form View Classes""" __docformat__ = 'restructuredtext' import transaction from zope.formlib.interfaces import IInputWidget from zope.formlib.interfaces import WidgetsError from zope.app.form.browser.editview import EditView from zope.app.form.browser.i18n import _ from zope.app.form.browser.submit import Update from zope.app.form.utility import applyWidgetsChanges from zope.app.form.utility import setUpWidgets class Data(dict): """Dictionary wrapper to make keys available as attributes.""" def __getattr__(self, name): return self[name] def __setattr__(self, name, value): self[name] = value class FormView(EditView): def getData(self): """Get the data for the form. This method should return a dictionary mapping field names to values. """ raise NotImplementedError( 'Must be implemented by a specific form class') def setData(self, data): """Set the data gotten from a form. The data will be a dictionary of fieldnames to values. May return a status message. """ raise NotImplementedError( 'Must be implemented by a specific form class') def _setUpWidgets(self): self.data = Data(self.getData()) setUpWidgets( self, self.schema, IInputWidget, initial=self.data, names=self.fieldNames) def update(self): if self.update_status is not None: # We've been called before. Just return the status we previously # computed. return self.update_status status = '' if Update in self.request: try: changed = applyWidgetsChanges( self, self.schema, target=self.data, names=self.fieldNames) except WidgetsError as errors: # pragma: no cover self.errors = errors status = _("An error occurred.") transaction.doom() else: if changed: status = self.setData(self.data) setUpWidgets( self, self.schema, IInputWidget, initial=self.data, ignoreStickyValues=True, names=self.fieldNames) self.update_status = status return status
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/formview.py
formview.py
"""Form and Widget Interfaces""" __docformat__ = 'restructuredtext' # BBB: ITerms are also used by z3c.form and possibly other form # frameworks, so it was moved to zope.browser.interfaces and it's # preferred to import from there now. from zope.browser.interfaces import ITerms from zope.formlib.interfaces import IBrowserWidget from zope.formlib.interfaces import IInputWidget from zope.formlib.interfaces import ISimpleInputWidget from zope.formlib.interfaces import ISourceQueryView from zope.formlib.interfaces import ITextBrowserWidget from zope.formlib.interfaces import IWidget from zope.formlib.interfaces import IWidgetInputErrorView from zope.interface import Interface class IFormCollaborationView(Interface): """Views that collaborate to create a single form. When a form is applied, the changes in the form need to be applied to individual views, which update objects as necessary. """ def __call__(): """Render the view as a part of a larger form. Form input elements should be included, prefixed with the prefix given to setPrefix. `form` and `submit` elements should not be included. They will be provided for the larger form. """ def setPrefix(prefix): """Set the `prefix` used for names of input elements Element names should begin with the given `prefix`, followed by a dot. """ def update(): """Update the form with data from the request.""" class IAddFormCustomization(Interface): """API for add form customization. Classes supplied when defining add forms may need to override some of these methods. In particular, when the context of an add form is not an `IAdding`, a subclass needs to override `nextURL` and one of `add` or `createAndAdd`. To see how all this fits together, here's pseudo code for the update() method of the form: def update(self): data = <get data from widgets> # a dict self.createAndAdd(data) self.request.response.redirect(self.nextURL()) def createAndAdd(self, data): content = <create the content from the data> content = self.add(content) <set after-add attributes on content> """ def createAndAdd(data): """Create a new object from the given data and the resulting object. The data argument is a dictionary with values supplied by the form. If any user errors occur, they should be collected into a list and raised as a ``WidgetsError``. (For the default implementation, see pseudo-code in class docs.) """ def add(content): """Add the given content. This method is overridden when the context of the add form is not an `IAdding`. In this case, the class that customizes the form must take over adding the object. The default implementation returns `self.context.add(content)`, i.e. it delegates to the `IAdding` view. """ def nextURL(): """Return the URL to be displayed after the add operation. This can be relative to the view's context. The default implementation returns `self.context.nextURL()`, i.e. it delegates to the `IAdding` view. """ __all__ = [ 'IAddFormCustomization', 'IFormCollaborationView', # BBB 'IBrowserWidget', 'ISimpleInputWidget', 'ISourceQueryView', 'ITerms', 'ITextBrowserWidget', 'IWidget', 'IWidgetInputErrorView', 'IInputWidget', ]
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/interfaces.py
interfaces.py
"""Edit View Classes""" __docformat__ = 'restructuredtext' from datetime import datetime import transaction import zope.component from zope.browserpage import ViewPageTemplateFile from zope.browserpage.simpleviewclass import SimpleViewClass from zope.event import notify from zope.formlib.interfaces import WidgetsError from zope.interface import Interface from zope.lifecycleevent import Attributes from zope.lifecycleevent import ObjectModifiedEvent from zope.publisher.browser import BrowserView from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.schema import getFieldNamesInOrder from zope.security.checker import NamesChecker from zope.security.checker import defineChecker from zope.app.form.browser.i18n import _ from zope.app.form.browser.submit import Update from zope.app.form.utility import applyWidgetsChanges from zope.app.form.utility import setUpEditWidgets class EditView(BrowserView): """Simple edit-view base class Subclasses should provide a `schema` attribute defining the schema to be edited. The automatically generated widgets are available by name through the attributes `*_widget`. (E.g. ``view.title_widget for the title widget``) """ errors = () update_status = None label = '' # Fall-back field names computes from schema fieldNames = property(lambda self: getFieldNamesInOrder(self.schema)) # Fall-back template generated_form = ViewPageTemplateFile('edit.pt') def __init__(self, context, request): super().__init__(context, request) self._setUpWidgets() def _setUpWidgets(self): self.adapted = self.schema(self.context) setUpEditWidgets(self, self.schema, source=self.adapted, names=self.fieldNames) def setPrefix(self, prefix): for widget in self.widgets(): widget.setPrefix(prefix) def widgets(self): return [getattr(self, name + '_widget') for name in self.fieldNames] def changed(self): # This method is overridden to execute logic *after* changes # have been made. pass def update(self): if self.update_status is not None: # We've been called before. Just return the status we previously # computed. return self.update_status status = '' content = self.adapted if Update in self.request: changed = False try: changed = applyWidgetsChanges( self, self.schema, target=content, names=self.fieldNames) # We should not generate events when an adapter is used. # That's the adapter's job. if changed and self.context is self.adapted: description = Attributes(self.schema, *self.fieldNames) notify(ObjectModifiedEvent(content, description)) except WidgetsError as errors: self.errors = errors status = _("An error occurred.") transaction.doom() else: setUpEditWidgets(self, self.schema, source=self.adapted, ignoreStickyValues=True, names=self.fieldNames) if changed: self.changed() formatter = self.request.locale.dates.getFormatter( 'dateTime', 'medium') status = _("Updated on ${date_time}", mapping={'date_time': formatter.format(datetime.utcnow())}) self.update_status = status return status def EditViewFactory(name, schema, label, permission, layer, template, default_template, bases, for_, fields, fulledit_path=None, fulledit_label=None): class_ = SimpleViewClass(template, used_for=schema, bases=bases, name=name) class_.schema = schema class_.label = label class_.fieldNames = fields class_.fulledit_path = fulledit_path if fulledit_path and (fulledit_label is None): fulledit_label = "Full edit" class_.fulledit_label = fulledit_label class_.generated_form = ViewPageTemplateFile(default_template) defineChecker(class_, NamesChecker(("__call__", "__getitem__", "browserDefault", "publishTraverse"), permission)) if layer is None: layer = IDefaultBrowserLayer s = zope.component.getGlobalSiteManager() s.registerAdapter(class_, (for_, layer), Interface, name)
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/editview.py
editview.py