package
stringlengths 1
122
| pacakge-description
stringlengths 0
1.3M
|
---|---|
zoom-us | Python client library for Zoom.us REST API v1 and v2 |
zoomus2 | Python client library for Zoom.us REST API v1 and v2 |
zoomwrap | zoomwrapA module containing classes that can be easily serialized to JSON for use with Zoom's APIs.importzoomwrapclient=zoomwrap.WebhookClient("your_endpoint_url","your_auth_str")msg=zoomwrap.Message(head=zoomwrap.messageElements.Head("hello, world"))client.send(msg)I have only tested this with Zoom'sincoming webhook APIbut it should work with the Chatbot API as well since they use the same object structures.For convenience, there is aWebhookClientclass with methods for sending API requests using your credentials.DocumentationCurrently, there is no documentaion for this module because it is still a heavy work in progress.For now, have a loop at Zoom'sincoming webhook API docsand their more detailed docs for both the Chatbot and Webhook APIshere.Most of the different types of messages and their attributes have been implemented in this module, with the exception of messages with buttons, because they only work with the Chatbot API.ContributionsThis is my first pypi package and it is not very sophisticated (or neat, for that matter).
Contributions are certainly welcome but may not get checked often. |
zoomy | Zoomy - a Zoom utility for the terminalMade with Python, April 2020.Created byKewbish.Available onPyPi as Zoomy.
Released under theGPLv3 License.Issues are welcome!:camera: Why Zoomy?For the developer, the power user, the student who's just tired of going through countless emails to find a link, then flip through for passwords, and finally try to join the call.Zoomy is for you. Quick to use, light, and besides,cool automation.Also works in signed-out mode - just in case (like me) you don't want to give Zoom your personal information!:movie_camera: UsageRunzmy [alias]to open youraliasmeeting. For example,zmy mathto open your math meeting.Runzmy add [alias] [confno] [*pwd]orzmy a [alias] [confno] [*pwd]to add a meeting calledaliaswith the conference numberconfnoand the passwordpwd. Adding a password is optional. Your meetings cannot be calledadd,delete,list, orpath(ora/d/l/p). This option can also be used to edit currently saved meetings.Runzmy delete [alias]orzmy d [alias]to delete youraliasmeeting. For example,zmy d mathto delete your math meeting.Runzmy listorzmy lto list all your available meetings.Runzmy pathorzmy pto print yourconfig.zmyfilepath.Runzmy --helporzmy --hto get help.:wrench: InstallationInstall via PyPi by runningpip install zoomy. This requires Python to be installed.Alternatively, build from source by running thesetup.pyafter downloading the ZIP.:gear: How it worksZoom actually comes with acustom URL scheme, most of which is technically deprecated, but still works well.Your conference number is passed in from a saved configuration file, and passed to the URL, which is then started with your system's equivalent ofstart.It simplifies the process of remembering all those links and passwords, especially if you don't use Zoom signed in or if you don't keep passwords saved.:warning: - This does expose your meeting IDs and passwords (if you choose to supply them), and itispossible, if a hacker decided, togrepyour entire system for a.zmyfile and infiltrate your meeting. Use at your own risk.:fast_forward: Changelog0.5:Feature: Add success messages0.4:Feature: Changezoomyalias tozmy0.4.1:Feature: Add path print0.4.2:Feature: Disallow invalid names0.3:Bugfix: Add meeting checks (breaks more elegantly)0.3.1:Feature: Add a help flagRestructure elif blocksDocs: Update for help flag0.3.2:Bugfix: Revert conference logic0.2:Feature: Add list meetings functionDocs: Update docs with additional instructions for list and warning about commasDocs: Add long description to PyPiDocs: Add changelog0.2.1:Bugfix: Implement file generator if fresh install0.2.2:Feature: Add support for passwords with commas0.2.3:Delete requirements.txt0.2.4:Bugfix: Fix logic if password added0.1:Started project!Docs: Create docs |
zoonado | UNKNOWN |
zooniverse-dump | No description available on PyPI. |
zoonomia | ## ZoonomiaZoonomia is a library for multi-objective strongly typed genetic programming.
The aim is to unify some ideas from various sub-fields of evolutionary
optimization under a simple yet sufficiently expressive API. At this stage this
project is much more an autodidactic exploration of this kind of system than a
“stable”, “performant”, or “useful” artifact. Everything here is subject to
change, there are no guarantees. |
zoop | Zookeeperis a highly reliable distributed coordination service.Zoopgives you a Pythonic API for accessing ZooKeeper instances, as well as
implementations of some common ZooKeeper patterns. This leaves you free to
concentrate on whatever it was you were originally doing:>>> zk = zoop.ZooKeeper('localhost:2181')
>>> zk.connect()
>>> q = zk.Queue('/howdy')
>>> def gotit(data):
... print "Gotit got data:", data
>>> q.watch(gotit)
>>> q.put("frist!")
Gotit got data: frist!Check out:DocumentationSourceIssuesHistory0.1.1Expanding the Filesystem metaphor:
Client now has rm_rf() and rm() methodsQueues now have variable item prefix (Useful for watching Queues created by other libraries)
Queues now have multiple watch options - watch for lists of items, or data added.0.1 (2012-05-07)Initial release with
* complete CRUD
* Lock Implementation
* Queue Implementation |
zooper-client | No description available on PyPI. |
zooper-common | No description available on PyPI. |
zooper-datasets | No description available on PyPI. |
zooper-premium-handbags-dataset | No description available on PyPI. |
zooper-sport-cars-brand-dataset | No description available on PyPI. |
zoopla | A python wrapper for the Zoopla API.Zoopla has launched an open API to allow developers to create
applications using hyper local data on 27m homes, over 1m sale and
rental listings, and 15 years of sold price data.Registerfor a user account and apply for an instant API key.Browse thedocumentationto understand how to use the API and the
specifications for the individual APIs.Installation$ pip install zooplaTestsInstall the dev requirements:$pipinstall-rrequirements.txtRun py.test with your developer key (otherwise you won’t be able to
hit the liveAPI upon which these tests depend).$py.test--api_key=<your-api-key>tests/# pytest under Python 3+ExamplesRetrieve property listings for a given area.fromzooplaimportZooplazoopla=Zoopla(api_key='your_api_key')search=zoopla.property_listings({'maximum_beds':2,'page_size':100,'listing_status':'sale','area':'Blackley, Greater Manchester'})forresultinsearch.listing:print(result.price)print(result.description)print(result.image_url)Retrieve a list of house price estimates for the requested area.zed_indices=zoopla.area_zed_indices({'area':'Blackley, Greater Manchester','output_type':'area','area_type':'streets','order':'ascending','page_number':1,'page_size':10})print(zed_indices.town)print(zed_indices.results_url)Generate a graph of values for an outcode over the previous 3 months and
return the URL to the generated image.area_graphs=zoopla.area_value_graphs({'area':'SW11'})print(area_graphs.average_values_graph_url)print(area_graphs.value_trend_graph_url)Retrieve the average sale price for houses in a particular area.average=zoopla.average_area_sold_price({'area':'SW11'})print(average.average_sold_price_7year)print(average.average_sold_price_5year)Submit a viewing request to an agent regarding a particular listing.session_id=zoopla.get_session_id()arrange_viewing=zoopla.arrange_viewing({'session_id':session_id,'listing_id':44863256,'name':'Tester','email':"[email protected]",'phone':'01010101','phone_type':'work','best_time_to_call':'anytime','message':'Hi, I seen your listing on zoopla.co.uk and I would love to arrange a viewing!'})ContributingFork the project and clone locally.Create a new branch for what you’re going to work on.Push to your origin repository.Include tests and update documentation if necessary.Create a new pull request in GitHub. |
zoopla-scraper-test | No description available on PyPI. |
zoopt | No description available on PyPI. |
zoop-wrapper | .. |br| raw:: html|br|.. image::https://zoop.com.br/wp-content/themes/zoop/img/logo.svg:target: #
:alt: Zoop Logo
:height: 130
:align: center|br|.. container::.. image:: https://img.shields.io/pypi/v/zoop-wrapper
:target: https://pypi.org/project/zoop-wrapper/
:alt: PyPI Version
:height: 23
.. image:: https://img.shields.io/pypi/pyversions/zoop-wrapper
:target: https://pypi.org/project/zoop-wrapper/
:alt: PyPI - Python Version
:height: 23.. container::.. image:: https://img.shields.io/github/workflow/status/imobanco/zoop-wrapper/tests
:target: https://github.com/imobanco/zoop-wrapper/actions?query=workflow%3Atests
:alt: Test status
:height: 23
.. image:: https://readthedocs.org/projects/zoop-wrapper/badge/?version=latest
:target: https://zoop-wrapper.readthedocs.io/pt_BR/latest/?badge=latest
:alt: Documentation Status
:height: 23.. container::.. image:: https://img.shields.io/github/license/imobanco/zoop-wrapper
:target: https://github.com/imobanco/zoop-wrapper/blob/dev/LICENSE
:alt: Licença
:height: 23
.. image:: https://img.shields.io/github/contributors/imobanco/zoop-wrapper
:target: https://github.com/imobanco/zoop-wrapper/graphs/contributors
:alt: Contributors
:height: 23.. container::.. image:: https://codecov.io/gh/imobanco/zoop-wrapper/branch/master/graph/badge.svg
:target: https://codecov.io/gh/imobanco/zoop-wrapper
:alt: Coverage
:height: 21
.. image:: https://snyk.io/test/github/imobanco/zoop-wrapper/badge.svg?targetFile=requirements.txt
:target: https://snyk.io/test/github/imobanco/zoop-wrapper?targetFile=requirements.txt
:alt: Known Vulnerabilities
:height: 23|br|Cliente não oficial da Zoop feito em Python, para realizar integração com o gateway de pagamento.Documentação oficial da Zoop <https://docs.zoop.co>_InstalandoNosso pacote está hospedado noPyPI <https://pypi.org/project/zoop-wrapper/>_.. code-block:: bashpip install zoop-wrapperConfiguraçãoPara utilizar ozoop-wrapperé necessário ter duas constantes/variáveis. sendo elas:.. code-block:: pythonZOOP_KEY='chave de autenticação recebida da zoop'
MARKETPLACE_ID='ID do market place'Recomendamos criar um arquivo.envcontendo essas varíaveis de ambiente.Podem ser criadas diretamente no terminal utilizando (não recomendado):.. code-block:: bashexport ZOOP_KEY='chave de autenticação recebida da zoop'
export MARKETPLACE_ID='ID do market place'Podem ser criadas também diretamente noarquivo.py.. danger::Fazer isso além de não ser recomendado é uma **FALHA** de segurança.Documentação da ZoopA Zoop fornece diversas formas de comunicação. Sendo uma telas API's baseadas na tecnologia REST.
A documentação da API da zoop não é uma das melhores, mas está disponível abertamente... warning::Não temos conhecimento se TODOS os testes podem ser realizados sem ônus ao desenvolvedor.
As transações de cartão podem ser extornadas e não há problema em gerar boletos (não paga a baixa).Saiba mais nadocumentação oficial da Zoop <https://docs.zoop.co/docs/introdu%C3%A7%C3%A3o-a-zoop>_Recursos disponíveisMarket Place☐ detalhesWebhooks☑ Cadastro☑ listagem☑ detalhes☑ remoçãoBuyer☑ Atualização☑ Cadastro☑ listagem☑ detalhes☑ remoçãoSeller☑ Atualização☑ Cadastro☑ listagem☑ detalhes☑ remoçãoToken☑ Cadastro de token cartão de crédito☑ Cadastro de token conta bancária☐ detalhesCartão de crédito☑ Conexão☑ detalhes☐ remoçãoConta bancária☐ Atualização☑ Conexão☑ listagem☑ detalhes☐ remoçãoBoleto☑ detalhesTransação☑ listagem☑ detalhes☑ cancelamento☑ Cadastro transação boleto☑ Cadastro transação cartão de crédito |
zoort | A Python script for automatic MongoDB backupsFeaturesBackup for just one or all your MongoDB Databases.Encrypt and Decrypt output dump file.Upload file to S3 bucket.RequirementsPython 2.6 | 2.7LicenseMIT licensed. See the bundledLICENSEfile for more details. |
zoosrv | No description available on PyPI. |
zoosync | ZoosyncZoosync is a simple service discovery tool using Zookeeper as database backend.UsageSeezoosync –helpfor brief usage or manual page for more detailed usage.The output is in the form of shell variable assignement. Tool could be used this way:ZOO='zoo1.example.com,zoo2.example.com,zoo3.example.com'
REQ_SERVICES='impala,hadoop-hdfs,test,test2,test3'
zoosync --zookeeper ${ZOO} --services ${REQ_SERVICES} cleanup
eval `zoosync --zookeeper ${ZOO} --services ${REQ_SERVICES} --wait 1800 wait`
echo "active: ${SERVICES}"
echo "missing: ${MISSING}"Deployment# install
pip install zoosync
# configure (/etc/zoosynrc and startup scripts)
zoosync -z zoo1,zoo2,zoo3 -s service1,service2 -u user -p password deployTestsTests require running zookeeper and proper configuration of zoosync (see Usage).Launch:python setup.py test |
zoot | No description available on PyPI. |
zoox-base-py-metrics | Failed to fetch description. HTTP Status Code: 404 |
zooxBasePythonMetrics | Failed to fetch description. HTTP Status Code: 404 |
zooz-python | UNKNOWN |
zop | 📦 setup.py (for humans)This repo exists to providean example setup.pyfile, that can be used
to bootstrap your next Python project. It includes some advanced
patterns and best practices forsetup.py, as well as some
commented–out nice–to–haves.For example, thissetup.pyprovides a$ python setup.py uploadcommand, which creates auniversal wheel(andsdist) and uploads
your package toPyPiusingTwine, without the need for an annoyingsetup.cfgfile. It also creates/uploads a new git tag, automatically.In short,setup.pyfiles can be daunting to approach, when first
starting out — even Guido has been heard saying, "everyone cargo cults
thems". It's true — so, I want this repo to be the best place to
copy–paste from :)Check out the example!Installationcdyour_project# Download the setup.py file:# download with wgetwgethttps://raw.githubusercontent.com/navdeep-G/setup.py/master/setup.py-Osetup.py# download with curlcurl-Ohttps://raw.githubusercontent.com/navdeep-G/setup.py/master/setup.pyTo DoTests via$ setup.py test(if it's concise).Pull requests are encouraged!More ResourcesWhat is setup.py?on Stack OverflowOfficial Python Packaging User GuideThe Hitchhiker's Guide to PackagingCookiecutter template for a Python packageLicenseThis is free and unencumbered software released into the public domain.Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any means. |
zopache.pagetemplate | Zopache Page TemplatesPage Templates content type.CHANGES0.1.0 (2013-05-21)Initial release.Copied code from abandoned ZPT Page code. |
zopache.pythonscript | Zopache Python ScriptsZopache Python Scripts are a port of Zoep 2 Python scripts, which allows
users to write Python functions via a Web UI.CHANGES0.1.0 (2013-05-23)Initial release.A simple Python Script implementation behaving similar to Zope 2’s version. |
zop-cms | 📦 setup.py (for humans)This repo exists to providean example setup.pyfile, that can be used
to bootstrap your next Python project. It includes some advanced
patterns and best practices forsetup.py, as well as some
commented–out nice–to–haves.For example, thissetup.pyprovides a$ python setup.py uploadcommand, which creates auniversal wheel(andsdist) and uploads
your package toPyPiusingTwine, without the need for an annoyingsetup.cfgfile. It also creates/uploads a new git tag, automatically.In short,setup.pyfiles can be daunting to approach, when first
starting out — even Guido has been heard saying, "everyone cargo cults
thems". It's true — so, I want this repo to be the best place to
copy–paste from :)Check out the example!Installationcdyour_project# Download the setup.py file:# download with wgetwgethttps://raw.githubusercontent.com/navdeep-G/setup.py/master/setup.py-Osetup.py# download with curlcurl-Ohttps://raw.githubusercontent.com/navdeep-G/setup.py/master/setup.pyTo DoTests via$ setup.py test(if it's concise).Pull requests are encouraged!More ResourcesWhat is setup.py?on Stack OverflowOfficial Python Packaging User GuideThe Hitchhiker's Guide to PackagingCookiecutter template for a Python packageLicenseThis is free and unencumbered software released into the public domain.Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any means. |
zope2_bootstrap | IntroductionThe Zope Management Interface, withBootstrap.Installation$ virtualenv-2.7 .
$ bin/pip install zc.buildout
$ cat > buildout.cfg << EOF
[buildout]
extends = https://raw.githubusercontent.com/plock/pins/master/plone-4-3
[plone]
eggs =
Zope2
zope2_bootstrap
zcml =
zope2_bootstrap
EOF
$ bin/buildout
$ bin/plone fgChangelog0.3.0 (2016-08-31)Upgrade Bootstrap 3.3.5 -> 3.3.70.2.0 (2015-07-19)Upgrade Bootstrap 3.1.1 -> 3.3.50.1.0 - 2014-02-26Adjust button styles0.0.9 - 2014-02-26Bump Bootstrap version to 3.1.10.0.8 - 2013-12-08Upgrade to Bootstrap 3Add Zope2-only splash screen based on Plone’sFix JavaScript0.0.7 - 2012-06-11Use SERVER_URL and SERVER_URL for logo src and href respectively (instead of SERVER_URL, ACTUAL_URL)0.0.6 - 2012-06-11Use SERVER_URL and ACTUAL_URL for logo src and href respectively (instead of URLX, BASEX)Add ZMI warning (suggested by vangheem)0.0.5 - 2012-06-11Add contextual logo above manage_tabs0.0.4 - 2012-06-01Re-apply Plone ZMI hacks0.0.3 - 2012-06-01Fix brown bag0.0.2 - 2012-06-01Add table styles0.0.1 - 2012-06-01Initial release |
zope2instance | This package provides abuildoutrecipe for creating a Zope 2
instance based around adeployment.Thedeploymentconcept originates fromzc.recipe.deploymentand
allows the deployment to control where resources of a particular type
are created.Whilezc.recipe.deploymentis suited to production use, you will
likely find thatgocept.recipe.deploymentsandboxis more useful for
development.This recipe is only compatible with Zope 2.12+. |
zope2.sessioncookie | zope2.sessioncookieBridge to allow using Pyramid’scookie session implementationin Zope2.NoteInitial development of this library was sponsored by ZeOmega Inc.InstallationClone the repository. E.g.:$ cd /path/to/
$ git clone [email protected]:zopefoundation/zope2.sessioncookieGetzope2.sessioncookieinstalled on the Python path. E.g.:$ cd /path/to/zope2.sessioncookie
$ /path/to/virtualenv_with_zope2/bin/pip install -e .
...Copy / link thezope2.sessioncookie-meta.zcmlfile into the$INSTANCE_HOME/etc/package-includesof your Zope instance. (You might
need to create the directory first.) E.g.:$ cd /path/to/zopes_instance
$ mkdir -p etc/package-includes
$ cd etc/package-includes
$ ln -s \
/path/to/zope2.sessioncookie/zope2.sessioncookie-meta.zcml .Generate a 32-byte, hexlified secret:$ /path/to/virtualenv_with_zope2/bin/print_secret
DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFEdit thesite.zcmlfor your instance. E.g.:$ cd /path/to/zopes_instance
$ vim etc/site.zcmlAdd an XML namespace declaration at the top, e.g.:xmlns:sc="https://github.com/zopefoundation/zope2.sessioncookie"Add a stanza near the end, configuring the cookie session. E.g.:<sc:sessioncookie
secret="DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF"
secure="False"
encrypt="True"/>Run the installation script, which disables the standard session
manager and adds the new hook. E.g.:$ bin/zopectl run \
/path/to/zope2.sessioncookie/zope2/sessioncookie/scripts/install.py(Re)start your Zope instance. Test methods which set session variables,
and inspect request / response cookies to see that_ZopeIdis no longer
being set, whilesessionisset (with encrypted, base64-encoded data).Changelog0.8 (2016-04-28)Add aZopeCookieSession.setmethod (PR #4).0.7.1 (2015-12-16)Packaging bug: fix rendering ofREADME.txtin--long-descriptionoutput.0.7 (2015-12-16)Fix example ZCML snippet inREADME.rst(PR #3).Fix ZCML namespace inzope2/sessioncookie/meta.zcml(PR #3).Add script for uninstalling the root traversal hook (PR #2).0.6.1 (2015-12-08)Packaging bug: add missingMANIFEST.in.0.6 (2015-11-23)Transferred copyright to Zope Foundation, relicensed to ZPL 2.1.Rename fromzope2.signedsessioncookie->zope2.sessioncookie.Replace locally-definedEncryptingPickleSerialzerwithpyramid_nacl_session.EncryptedSerializer. Closes #8 and #9.0.5 (2015-10-08)Add support for (optionally) encrypting session cookies, rather than
signing them.0.4 (2015-10-05)Add an attribute,signedsessioncookie_installed, to the root object
during installation.0.3 (2015-09-30)Fix renderinghttp_onlycookie attribute.0.2 (2015-09-29)Add support for extra Pyramid session configuration via ZCML:hash_algorithm,timeout,reissue_time.Suppress empty / None values in cookie attributes passed toZPublisher.HTTPResponse.setCookie.Refactor install script to allow reuse from other modules.Fix compatibility w/zope.configuration 3.7.4.0.1 (2015-09-18)Initial release. |
zope2.zodbbrowser | IntroductionZope2.ZodbBrowser is a web application to browse, inspect and introspect Zope’s zodb objects. It is inspired on smalltalk’s class browser and zodbbrowsers for zope3.There is a demo video available atYouTube’s menttes channel.Using ZodbBrowser with your buildoutIf you already have a buildout for Zope2.13 or Plone4 running, edit buildout.cfg to add zope2.zodbbrowser to eggs and zcml sections at buildout and instance parts respectively.[buildout]
...
eggs = zope2.zodbbrowser
...
[instance]
...
zcml = zope2.zodbbrowserThen run bin/buildout to make the changes effective.Buildout Install$ svn co http://zodbbrowser.googlecode.com/svn/buildout/ zodbbrowser
$ python2.6 bootstrap.py
$ bin/buildout -v
$ bin/instance fgUse of zodbbrowserTo access zodbbrowser add /zodbbrowser in your zope instance url, for example:http://localhost:8080/zodbbrowserChangelog0.2 experimental versionAdded ui.layout for better layout and resizable panels. Thanks to Quimera.Updated jquery from 1.4.2 to 1.4.4.Added Pretty printing format to show propertie’s values. Thanks to Laurence Rowe and Emanuel Sartor.Added support for older pythons 2.4 , 2.5. Thanks to Laurence Rowe.Included module and file path for source code. Thanks to davidjb.Added z3c.autoinclude.plugin support to remove the zcml entry on buildout. Thanks to aclark.0.1 experimental versionInitial release includes: Class and Ancestors, Properties, Callables and
Interfaces provided.Support for Zope 2.13.x and Plone 4.0. Not tested with older or newer versions of Zope although it should work.Support for Firefox 3.6 and Chrome 5.0. No support Internet Explorer yet. |
zope3app | No description available on PyPI. |
zope.annotation | zope.annotationREADMEThis package provides a mechanism to store additional information about
objects without need to modify object class.Changes5.0 (2023-03-27)Add support for Python 3.11.Drop support for Python 2.7, 3.5, 3.6.4.8 (2022-09-06)Add support for Python 3.8, 3.9, 3.10.Drop support for Python 3.4.4.7.0 (2018-10-16)Add support for Python 3.7 and drop support for Python 3.3.Fix a DeprecationWarning fromzope.annotation.attribute. Seeissue 16.4.6.0 (2017-09-22)MakeAttributeAnnotationshave a__parent__. The__parent__is the object that it stores__annotations__on.
This is a convenience for upwards traversal as used by things likezope.keyreference. Seehttps://github.com/zopefoundation/zope.annotation/issues/114.5 (2017-06-03)Drop support for Python 2.6.Claim support for Python 3.5 and 3.6.Reach 100% test coverage.AttributeAnnotationsis now always acollections.MutableMapping. Previously on Python 2 it was aUserDict.DictMixin.4.4.1 (2015-01-09)Convert doctests to Sphinx documentation. Doctest snippets are still
tested viatox-edocs.4.4.0 (2015-01-09)LP #98462: add additional “iterable mapping” methods toIAnnotations.LP #878265:Makepersistent(used only for doctests) a soft dependency,
installable via thezope.annotation[btree]extra.MakeBTrees(used for attribute storage) a soft dependency,
installable via thezope.annotation[btree]extra. Fall back to
usingdictfor attribute storage ifBTreesis not importable.4.3.0 (2014-12-26)Add support for Python 3.4.4.2.0 (2013-03-18)Don’t make AttributeAnnotations available as a view.4.1.0 (2013-02-24)Add__bool__method toIAnnotationsAPI for Python 3 compatibility.4.0.1 (2013-02-11)Addtox.ini.4.0.0 (2013-02-11)Add support for Python 3.3 and PyPy.Replace deprecatedzope.component.adaptsusage with equivalentzope.component.adapterdecorator.Replace deprecatedzope.interface.implementsusage with equivalentzope.interface.implementerdecorator.Drop support for Python 2.4 and 2.5.Include zcml dependencies in configure.zcml, require the necessary packages
via a zcml extra, added tests for zcml.3.5.0 (2009-09-07)Add ZODB3 to install_requires, because it’s a true requirement of this
package, not just a testing requirement, as BTrees are in use.Fix one test that was inactive because it’s function was overriden by
a mistake.3.4.2 (2009-03-09)Clean up package description and documentation a bit.Change mailing list address to zope-dev at zope.org, as
zope3-dev at zope.org is now retired.Remove old zpkg-related files.3.4.1 (2008-08-26)Annotation factories take care not to store proxies in the database,
so adapting an object wrapped in aLocationProxyworks correctly.
Fixeshttps://bugs.launchpad.net/zope3/+bug/2616203.4.0 (2007-08-29)Annotation factories are no longer containing the factored object.
Instead the objects are located usingzope.location. This removes
a dependency tozope.app.container. |
zope.apidoc | This Zope 3 package provides helper utilities to discover your Application API
and the Zopen Component Registry.ContentsZope 3 API DocumentationComponent Inspection UtilitiesgetRequiredAdapters(iface, withViews=False)getProvidedAdapters(iface, withViews=False)getClasses(iface)getFactories(ifaces)getUtilities(iface)getRealFactory(factory)getInterfaceInfoDictionary(iface)getTypeInfoDictionary(type)getSpecificationInfoDictionary(spec)getAdapterInfoDictionary(reg)getFactoryInfoDictionary(reg)getUtilityInfoDictionary(name, factory)Interface Inspection UtilitiesgetElements(iface, type=IElement)getFieldsInOrder(iface, _itemsorter=…)getAttributes(iface)getMethods(iface)getFields(iface)getInterfaceTypes(iface)getFieldInterface(field)getAttributeInfoDictionary(attr, format=’restructuredtext’)getMethodInfoDictionary(method, format=’restructuredtext’)getFieldInfoDictionary(field, format=’restructuredtext’)Presentation Inspection UtilitiesgetViewFactoryData(factory)getPresentationType(iface)getViews(iface, type=IRequest)filterViewRegistrations(regs, iface, level=SPECIFC_INTERFACE_LEVEL)getViewInfoDictionary(reg)Miscellaneous UtilitiesrelativizePath(path)truncateSysPath(path)getPythonPath(obj)isReferencable(path)getPermissionIds(name, checker=_marker, klass=_marker)getFunctionSignature(func)getPublicAttributes(obj)getInterfaceForAttribute(name, interfaces=_marker, klass=_marker, asPath=True)columnize(entries, columns=3)getDocFormat(module)dedentString(text)renderText(text, module=None, format=None)The Class RegistrygetClassesThatImplement(iface)getSubclassesOf(klass)Safe ImportsCHANGESZope 3 API DocumentationThis Zope 3 package provides fully dynamic API documentation of Zope 3 and
registered add-on components. The package is very extensible and can be easily
extended by implementing new modules.Besides being an application, the API doctool also provides several public
APIs to extract information from various objects used by Zope 3.utilities – Miscellaneous classes and functions that aid all documentation
modules. They are broadly usable.interface – This module contains functions to inspect interfaces and
schemas.component – This modules provides utility functions to lookup components
given an interface.presentation – Presentation components are generally more complex than
others, so a separate utilities module is provided to inspect views.classregistry – Here a simple dictionary-based registry for all known
classes is provided. It allows us to search in classes.Component Inspection UtilitiesOnce 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.apidoc import componentprovide 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):
... passgetRequiredAdapters(iface, withViews=False)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.component import provideAdapter, provideHandler
>>> provideAdapter(None, (IFoo,), IResult)
>>> provideAdapter(None, (IFoo, IBar), ISpecialResult)
>>> provideAdapter(None, (IFoo, IRequest), ISpecialResult)
>>> provideHandler('stubFactory', (IFoo,))>>> regs = list(component.getRequiredAdapters(IFoo))
>>> regs.sort()
>>> regs
[AdapterRegistration(<BaseGlobalComponents base>,
[IFoo, IBar], ISpecialResult, u'', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IFoo], IResult, u'', None, u''),
HandlerRegistration(<BaseGlobalComponents base>,
[IFoo], u'', 'stubFactory', u'')]Note how the adapter requiring anIRequestat 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, u'', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IFoo, IRequest], ISpecialResult, u'', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IFoo], IResult, u'', None, u''),
HandlerRegistration(<BaseGlobalComponents base>,
[IFoo], u'', 'stubFactory', u'')]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, u'', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IFoo], IResult, u'', None, u''),
HandlerRegistration(<BaseGlobalComponents base>,
[IFoo], u'', 'stubFactory', u'')]And all of the required interfaces are considered, of course:>>> regs = list(component.getRequiredAdapters(IBar))
>>> regs.sort()
>>> regs
[AdapterRegistration(<BaseGlobalComponents base>,
[IFoo, IBar], ISpecialResult, u'', None, u'')]getProvidedAdapters(iface, withViews=False)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, u'', None, u'')]And by specifying thewithViewflag, we get views as well:>>> regs = list(component.getProvidedAdapters(ISpecialResult, withViews=True))
>>> regs.sort()
>>> regs
[AdapterRegistration(<BaseGlobalComponents base>,
[IFoo, IBar], ISpecialResult, u'', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IFoo, IRequest], ISpecialResult, u'', None, u'')]We can of course also ask for adapters specifyingIResult:>>> regs = list(component.getProvidedAdapters(IResult, withViews=True))
>>> regs.sort()
>>> regs
[AdapterRegistration(<BaseGlobalComponents base>,
[IFoo, IBar], ISpecialResult, u'', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IFoo, IRequest], ISpecialResult, u'', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IFoo], IResult, u'', None, u'')]getClasses(iface)This package comes with a little tool called the class registry
(seeclassregistry.txt). 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 implements
>>> from zope.apidoc.classregistry import classRegistry>>> class MyFoo(object):
... implements(IFoo)
>>> classRegistry['MyFoo'] = MyFoo>>> class MyBar(object):
... implements(IBar)
>>> classRegistry['MyBar'] = MyBar>>> class MyFooBar(object):
... implements(IFooBar)
>>> classRegistry['MyFooBar'] = MyFooBarLet’s now see whether what results we get:>>> classes = component.getClasses(IFooBar)
>>> classes.sort()
>>> classes
[('MyFooBar', <class 'zope.apidoc.doctest.MyFooBar'>)]>>> classes = component.getClasses(IFoo)
>>> classes.sort()
>>> classes
[('MyFoo', <class 'zope.apidoc.doctest.MyFoo'>),
('MyFooBar', <class 'zope.apidoc.doctest.MyFooBar'>)]getFactories(ifaces)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
>>> from zope.component import provideUtility
>>> provideUtility(Factory(MyFoo), IFactory, 'MyFoo')
>>> provideUtility(Factory(MyBar), IFactory, 'MyBar')
>>> 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.apidoc.doctest.MyFooBar'>>, None, u'')]>>> regs = list(component.getFactories(IFoo))
>>> regs.sort()
>>> regs
[UtilityRegistration(<BaseGlobalComponents base>, IFactory, 'MyFoo',
<Factory for <class 'zope.apidoc.doctest.MyFoo'>>, None, u''),
UtilityRegistration(<BaseGlobalComponents base>, IFactory, 'MyFooBar',
<Factory for <class 'zope.apidoc.doctest.MyFooBar'>>, None, u'')]getUtilities(iface)Return all utility registrations for utilities that provide the specified
interface.As usual, we have to register some utilities first:>>> provideUtility(MyFoo(), IFoo)
>>> provideUtility(MyBar(), IBar)
>>> provideUtility(MyFooBar(), IFooBar)Now let’s have a look what we have:>>> regs = list(component.getUtilities(IFooBar))
>>> regs.sort()
>>> regs #doctest:+ELLIPSIS
[UtilityRegistration(<BaseGlobalComponents base>, IFooBar, u'',
<zope.apidoc.doctest.MyFooBar object at ...>, None, u'')]>>> regs = list(component.getUtilities(IFoo))
>>> regs.sort()
>>> regs #doctest:+ELLIPSIS
[UtilityRegistration(<BaseGlobalComponents base>, IFoo, u'',
<zope.apidoc.doctest.MyFoo object at ...>, None, u''),
UtilityRegistration(<BaseGlobalComponents base>, IFooBar, u'',
<zope.apidoc.doctest.MyFooBar object at ...>, None, u'')]getRealFactory(factory)During registration, factories are commonly masked by wrapper functions. Also,
factories are sometimes alsoIFactoryinstances, which are not referencable,
so that we would like to return the class. If the wrapper objects/functions
play nice, then they provide afactoryattribute 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 = wrapper1So whether we pass inFactory,>>> component.getRealFactory(Factory)
<class 'zope.apidoc.doctest.Factory'>wrapper1,>>> component.getRealFactory(wrapper1)
<class 'zope.apidoc.doctest.Factory'>orwrapper2,>>> component.getRealFactory(wrapper2)
<class 'zope.apidoc.doctest.Factory'>the answer should always be theFactoryclass. 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.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.apidoc.doctest.Factory'>getInterfaceInfoDictionary(iface)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.apidoc.doctest', 'name': 'IFoo'}The functions using this function use it with little care and can also
sometimes pass inNone. In these cases we want to returnNone:>>> component.getInterfaceInfoDictionary(None) is None
TrueIt’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.apidoc.doctest', 'name': 'MyFoo'}getTypeInfoDictionary(type)This function returns the info dictionary of a type.>>> pprint(component.getTypeInfoDictionary(tuple), width=1)
{'module': '__builtin__',
'name': 'tuple',
'url': '__builtin__/tuple'}getSpecificationInfoDictionary(spec)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.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': '__builtin__',
'name': 'tuple',
'url': '__builtin__/tuple'}For the type, we simply reuse the type info dictionary function.getAdapterInfoDictionary(reg)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:>>> class MyResult(object):
... implements(IResult)>>> from zope.component.registry import AdapterRegistration
>>> reg = AdapterRegistration(None, (IFoo, IBar), IResult, 'FooToResult',
... MyResult, 'doc info')And now get the info dictionary:>>> pprint(component.getAdapterInfoDictionary(reg), width=1)
{'doc': 'doc info',
'factory': 'zope.apidoc.doctest.MyResult',
'factory_url': 'zope/apidoc/doctest/MyResult',
'name': u'FooToResult',
'provided': {'module': 'zope.apidoc.doctest',
'name': 'IResult'},
'required': [{'isInterface': True,
'isType': False,
'module': 'zope.apidoc.doctest',
'name': 'IFoo'},
{'isInterface': True,
'isType': False,
'module': 'zope.apidoc.doctest',
'name': 'IBar'}],
'zcml': None}If the factory’s path cannot be referenced, for example if a type has been
created using thetype()builtin function, then the URL of the factory
will beNone:>>> 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=1)
{'doc': 'doc info',
'factory': 'zope.apidoc.doctest.MyResult2',
'factory_url': None,
'name': u'FooToResult',
'provided': {'module': 'zope.apidoc.doctest',
'name': 'IResult'},
'required': [{'isInterface': True,
'isType': False,
'module': 'zope.apidoc.doctest',
'name': 'IFoo'},
{'isInterface': True,
'isType': False,
'module': 'zope.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.component.registry import HandlerRegistration
>>> reg = HandlerRegistration(None, (IFoo, IBar), u'', MyResult, 'doc info')>>> pprint(component.getAdapterInfoDictionary(reg))
{'doc': 'doc info',
'factory': 'zope.apidoc.doctest.MyResult',
'factory_url': 'zope/apidoc/doctest/MyResult',
'name': u'',
'provided': None,
'required': [{'isInterface': True,
'isType': False,
'module': 'zope.apidoc.doctest',
'name': 'IFoo'},
{'isInterface': True,
'isType': False,
'module': 'zope.apidoc.doctest',
'name': 'IBar'}],
'zcml': None}getFactoryInfoDictionary(reg)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(
... component.getFactories(IFooBar).next()))
{'description': u'<p>My Foo Bar</p>\n',
'name': u'MyFooBar',
'title': 'MyFooBar',
'url': 'zope/apidoc/doctest/MyFooBar'}If the factory’s path cannot be referenced, for example if a type has been
created using thetype()builtin function, then the URL of the factory
will beNone:>>> class IMine(Interface):
... pass>>> class FactoryBase(object):
... def getInterfaces(self): return [IMine]>>> MyFactoryType = type('MyFactory', (FactoryBase,), {})
>>> from zope.interface import classImplements
>>> classImplements(MyFactoryType, IFactory)
>>> provideUtility(MyFactoryType(), IFactory, 'MyFactory')>>> pprint(component.getFactoryInfoDictionary(
... component.getFactories(IMine).next()), width=1)
{'description': u'',
'name': u'MyFactory',
'title': u'',
'url': None}getUtilityInfoDictionary(name, factory)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(
... component.getUtilities(IFooBar).next()))
{'iface_id': 'zope.apidoc.doctest.IFooBar',
'name': u'<i>no name</i>',
'path': 'zope.apidoc.doctest.MyFooBar',
'url': 'Code/zope/apidoc/doctest/MyFooBar',
'url_name': 'X19ub25hbWVfXw=='}Interface Inspection UtilitiesThis document is a presentation of the utility functions provided by>>> from zope.apidoc import interfaceFor the following demonstrations, we need a nice interface that we can inspect:>>> from zope.interface import Interface, Attribute
>>> from zope.schema import Field, TextLine>>> class IFoo(Interface):
... foo = Field(title=u"Foo")
...
... bar = TextLine(title=u"Bar",
... description=u"The Bar",
... required=True,
... default=u"My Bar")
...
... baz = Attribute('baz',
... 'This is the baz attribute')
...
... def blah(one, two, three=None, *args, **kwargs):
... """This is the `blah` method."""getElements(iface, type=IElement)Return a dictionary containing all elements in an interface. The type
specifies whether we are looking for attributes, fields or methods. So let’s
look at an example.First, let’s get the methods of an interface:>>> from zope.interface.interfaces import IMethod
>>> interface.getElements(IFoo, type=IMethod).keys()
['blah']and now the fields:>>> from zope.schema.interfaces import IField
>>> names = interface.getElements(IFoo, type=IField).keys()
>>> names.sort()
>>> names
['bar', 'foo']We can also get all attributes of course.>>> from zope.interface.interfaces import IAttribute
>>> names = interface.getElements(IFoo, type=IAttribute).keys()
>>> names.sort()
>>> names
['bar', 'baz', 'blah', 'foo']You might be surprised by the above result, since the fields and methods are
again included. However, fields and methods are just attributes and thus
extend the simple attribute implementation. If you want to get a list of
attributes that does not include fields and methods, see thegetAttributes(iface)function.The default type isIElementwhich will simply return all elements of the
interface:>>> names = interface.getElements(IFoo).keys()
>>> names.sort()
>>> names
['bar', 'baz', 'blah', 'foo']Note: The interface you pass to this functioncannotbe proxied!
Presentation code often like to wrap interfaces in security proxies and apidoc
even uses location proxies for interface.getFieldsInOrder(iface, _itemsorter=…)For presentation purposes we often want fields to have the a certain order,
most comonly the order they have in the interface. This function returns a
list of (name, field) tuples in a specified order.The_itemsorterargument provides the function that is used to order the
fields. The default function, which sorts by the fields’orderattribute,
should be the correct one for 99% of your needs.Reusing the interface created above, we check the output:>>> [n for n, a in interface.getFieldsInOrder(IFoo)]
['foo', 'bar']By changing the sort method to sort by names, we get:>>> [n for n, a in interface.getFieldsInOrder(
... IFoo, _itemsorter=lambda x, y: cmp(x[0], y[0]))]
['bar', 'foo']getAttributes(iface)This function returns a (name, attr) tuple for every attribute in the
interface. Note that this function will only return pure attributes; it
ignores methods and fields.>>> attrs = interface.getAttributes(IFoo)
>>> attrs.sort()
>>> attrs #doctest: +ELLIPSIS
[('baz', <zope.interface.interface.Attribute object at ...>)]getMethods(iface)This function returns a (name, method) tuple for every declared method in the
interface.>>> methods = interface.getMethods(IFoo)
>>> methods.sort()
>>> methods #doctest: +ELLIPSIS
[('blah', <zope.interface.interface.Method object at ...>)]getFields(iface)This function returns a (name, field) tuple for every declared field in the
interface.>>> interface.getFields(IFoo) #doctest: +ELLIPSIS
[('foo', <zope.schema._bootstrapfields.Field object at ...>),
('bar', <zope.schema._bootstrapfields.TextLine object at ...>)]Note that this returns the same result asgetFieldsInOrder()with the fields
sorted by theirorderattribute, except that you cannot specify the sort
function here. This function was mainly provided for symmetry with the other
functions.getInterfaceTypes(iface)Interfaces can be categorized/grouped by using interface types. Interface
types simply extendzope.interface.interfaces.IInterface, which are
basically meta-interfaces. The interface types are then provided by particular
interfaces.ThegetInterfaceTypes()function returns a list of interface types that are
provided for the specified interface. Note that you commonly expect only one
type per interface, though.Before we assign any type to ourIFoointerface, there are no types
declared.>>> interface.getInterfaceTypes(IFoo)
[]Now we define a new type calledIContentType>>> from zope.interface.interfaces import IInterface
>>> class IContentType(IInterface):
... passand have our interface provide it:>>> from zope.interface import directlyProvides
>>> directlyProvides(IFoo, IContentType)Note that ZCML has some more convenient methods of doing this. Now let’s get
the interface types again:>>> interface.getInterfaceTypes(IFoo)
[<InterfaceClass zope.apidoc.doctest.IContentType>]Again note that the interface passed to this functioncannotbe proxied,
otherwise this method will pick up the proxy’s interfaces as well.getFieldInterface(field)This function tries pretty hard to determine the best-matching interface that
represents the field. Commonly the field class has the same name as the field
interface (minus an “I”). So this is our first choice:>>> from zope.schema import Text, Int
>>> interface.getFieldInterface(Text())
<InterfaceClass zope.schema.interfaces.IText>>>> interface.getFieldInterface(Int())
<InterfaceClass zope.schema.interfaces.IInt>If the name matching method fails, it picks the first interface that extendsIField:>>> from zope.schema.interfaces import IField
>>> class ISpecialField(IField):
... pass
>>> class ISomething(Interface):
... pass>>> from zope.interface import implements
>>> class MyField:
... implements(ISomething, ISpecialField)>>> interface.getFieldInterface(MyField())
<InterfaceClass zope.apidoc.doctest.ISpecialField>getAttributeInfoDictionary(attr, format=’restructuredtext’)This function returns a page-template-friendly dictionary for a simple
attribute:>>> from pprint import pprint
>>> pprint(interface.getAttributeInfoDictionary(IFoo['baz']))
{'doc': u'<p>This is the baz attribute</p>\n',
'name': 'baz'}getMethodInfoDictionary(method, format=’restructuredtext’)This function returns a page-template-friendly dictionary for a method:>>> pprint(interface.getMethodInfoDictionary(IFoo['blah'])) #doc
{'doc':
u'<p>This is the <cite>blah</cite> method.</p>\n',
'name': 'blah',
'signature': '(one, two, three=None, *args, **kwargs)'}getFieldInfoDictionary(field, format=’restructuredtext’)This function returns a page-template-friendly dictionary for a field:>>> pprint(interface.getFieldInfoDictionary(IFoo['bar']), width=1)
{'class': {'name': 'TextLine',
'path': 'zope/schema/_bootstrapfields/TextLine'},
'default': "u'My Bar'",
'description': u'<p>The Bar</p>\n',
'iface': {'id': 'zope.schema.interfaces.ITextLine',
'name': 'ITextLine'},
'name': 'bar',
'required': True,
'required_string': u'required',
'title': u'Bar'}Presentation Inspection UtilitiesThepresentationmodule provides some nice utilities to inspect presentation
registrations.>>> from zope.apidoc import presentationgetViewFactoryData(factory)This function tries really hard to determine the correct information about a
view factory. For example, when you create a page, a new type is dynamically
generated upon registration. Let’s look at a couple examples.First, let’s inspect a case where a simple browser page was configured without
a special view class. In these cases the factory is aSimpleViewClass:>>> from zope.browserpage.simpleviewclass import SimpleViewClass
>>> view = SimpleViewClass('sample.pt')
>>> info = presentation.getViewFactoryData(view)Before we can check the result, we have to make sure that all Windows paths
are converted to Unix-like paths. We also clip off instance-specific parts of
the template path:>>> info['template'] = info['template'].replace('\\', '/')[-21:]
>>> from pprint import pprint
>>> pprint(info)
{'path': 'zope.browserpage.simpleviewclass.simple',
'referencable': True,
'resource': None,
'template': 'zope/apidoc/sample.pt',
'template_obj': <BoundPageTemplateFile of None>,
'url': 'zope/browserpage/simpleviewclass/simple'}So in the result above we see what the function returns. It is a dictionary
(converted to a list for test purposes) that contains the Python path of the
view class, a flag that specifies whether the factory can be referenced and
thus be viewed by the class browser, the (page) template used for the view and
the URL under which the factory will be found in the class browser. Some
views, like icons, also use resources to provide their data. In these cases
the name of the resource will be provided. Of course, not in all cases all
values will be available. Empty values are marked withNone.Believe it or not, in some cases the factory is just a simple type. In these
cases we cannot retrieve any useful information:>>> info = presentation.getViewFactoryData(3)
>>> pprint(info)
{'path': None,
'referencable': False,
'resource': None,
'template': None,
'url': None}In some cases factories are callable class instances, where we cannot directly
have a referencable name, so we lookup the class and use its name:>>> class Factory(object):
... pass>>> info = presentation.getViewFactoryData(Factory())
>>> pprint(info)
{'path': 'zope.apidoc.doctest.Factory',
'referencable': True,
'resource': None,
'template': None,
'url': 'zope/apidoc/doctest/Factory'}One of the more common cases, however, is that the factory is a class or
type. In this case we can just retrieve the reference directly:>>> info = presentation.getViewFactoryData(Factory)
>>> pprint(info)
{'path': 'zope.apidoc.doctest.Factory',
'referencable': True,
'resource': None,
'template': None,
'url': 'zope/apidoc/doctest/Factory'}When factories are created by a directive, they can also be functions. In
those cases we just simply return the function path:>>> def factory():
... pass# The testing framework does not set the __module__ correctly
>>> factory.__module__ = ‘__builtin__’>>> info = presentation.getViewFactoryData(factory)
>>> pprint(info)
{'path': '__builtin__.factory',
'referencable': True,
'resource': None,
'template': None,
'url': '__builtin__/factory'}However, the function is rather unhelpful, since it will be the same for all
views that use that code path. For this reason the function keeps track of the
original factory component in a function attribute calledfactory:>>> factory.factory = Factory>>> info = presentation.getViewFactoryData(factory)
>>> pprint(info)
{'path': 'zope.apidoc.doctest.Factory',
'referencable': True,
'resource': None,
'template': None,
'url': 'zope/apidoc/doctest/Factory'}Let’s now have a look at some extremly specific cases. If a view is registered
using thezope:viewdirective and a permission is specified, aProxyViewclass instance is created that references its original factory:>>> class ProxyView(object):
...
... def __init__(self, factory):
... self.factory = factory
>>> proxyView = ProxyView(Factory)>>> info = presentation.getViewFactoryData(proxyView)
>>> pprint(info)
{'path': 'zope.apidoc.doctest.Factory',
'referencable': True,
'resource': None,
'template': None,
'url': 'zope/apidoc/doctest/Factory'}Another use case is when a new type is created by thebrowser:pageorbrowser:viewdirective. In those cases the true/original factory is really
the first base class. Those cases are detected by inspecting the__module__string of the type:>>> new_class = type(Factory.__name__, (Factory,), {})
>>> new_class.__module__ = 'zope.browserpage.viewmeta'>>> info = presentation.getViewFactoryData(new_class)
>>> pprint(info)
{'path': 'zope.apidoc.doctest.Factory',
'referencable': True,
'resource': None,
'template': None,
'url': 'zope/apidoc/doctest/Factory'}The same sort of thing happens for XML-RPC views, except that those are
wrapped twice:>>> new_class = type(Factory.__name__, (Factory,), {})
>>> new_class.__module__ = 'zope.app.publisher.xmlrpc.metaconfigure'>>> new_class2 = type(Factory.__name__, (new_class,), {})
>>> new_class2.__module__ = 'zope.app.publisher.xmlrpc.metaconfigure'>>> info = presentation.getViewFactoryData(new_class2)
>>> pprint(info)
{'path': 'zope.apidoc.doctest.Factory',
'referencable': True,
'resource': None,
'template': None,
'url': 'zope/apidoc/doctest/Factory'}Finally, it sometimes happens that a factory is wrapped and the wrapper is
wrapped in return:>>> def wrapper1(*args):
... return Factory(*args)
>>> wrapper1.__module__ = None>>> def wrapper2(*args):
... return wrapper1(*args)
>>> wrapper2.__module__ = NoneInitially, the documentation is not very helpful:>>> info = presentation.getViewFactoryData(wrapper2)
>>> pprint(info)
{'path': 'None.wrapper2',
'referencable': True,
'resource': None,
'template': None,
'url': 'None/wrapper2'}However, if those wrappers play nicely, they provide a factory attribute each
step of the way …>>> wrapper1.factory = Factory
>>> wrapper2.factory = wrapper1and the result is finally our original factory:>>> info = presentation.getViewFactoryData(wrapper2)
>>> pprint(info)
{'path': 'zope.apidoc.doctest.Factory',
'referencable': True,
'resource': None,
'template': None,
'url': 'zope/apidoc/doctest/Factory'}getPresentationType(iface)In Zope 3, presentation types (i.e. browser, ftp, …) are defined through
their special request interface, such asIBrowserRequestorIFTPRequest. To complicate matters further, layer interfaces are used in
browser presentations to allow skinning. Layers extend any request type, but
most commonlyIBrowserRequest. This function inspects the request interface
of any presentation multi-adapter and determines its type, which is returned
in form of an interface.>>> from zope.apidoc.presentation import getPresentationType
>>> from zope.publisher.interfaces.http import IHTTPRequest
>>> from zope.publisher.interfaces.browser import IBrowserRequest>>> class ILayer1(IBrowserRequest):
... pass>>> presentation.getPresentationType(ILayer1)
<InterfaceClass zope.publisher.interfaces.browser.IBrowserRequest>>>> class ILayer2(IHTTPRequest):
... pass>>> presentation.getPresentationType(ILayer2)
<InterfaceClass zope.publisher.interfaces.http.IHTTPRequest>If the function cannot determine the presentation type, the interface itself
is returned:>>> from zope.interface import Interface
>>> class ILayer3(Interface):
... pass>>> presentation.getPresentationType(ILayer3)
<InterfaceClass zope.apidoc.doctest.ILayer3>Note that more specific presentation types are considered first. For example,IBrowserRequestextendsIHTTPRequest, but it will always determine the
presentation type to be anIBrowserRequest.getViews(iface, type=IRequest)This function retrieves all available view registrations for a given interface
and presentation type. The default argument for the presentation type isIRequest, which will effectively return all views for the specified
interface.To see how this works, we first have to register some views:>>> class IFoo(Interface):
... pass>>> from zope.component import provideAdapter
>>> provideAdapter(None, (IFoo, IHTTPRequest), Interface, name='foo')
>>> provideAdapter(None, (Interface, IHTTPRequest), Interface,
... name='bar')
>>> provideAdapter(None, (IFoo, IBrowserRequest), Interface,
... name='blah')Now let’s see what we’ve got. If we do not specify a type, all registrations
should be returned:>>> regs = list(presentation.getViews(IFoo))
>>> regs.sort()
>>> regs #doctest:+ELLIPSIS
[AdapterRegistration(<BaseGlobalComponents base>,
[IFoo, IBrowserRequest], Interface, 'blah', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IFoo, IHTTPRequest], Interface, 'foo', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[Interface, IHTTPRequest], Interface, 'bar', None, u'')]>>> regs = list(presentation.getViews(Interface, IHTTPRequest))
>>> regs.sort()
>>> regs #doctest:+ELLIPSIS
[AdapterRegistration(<BaseGlobalComponents base>,
[Interface, IHTTPRequest], Interface, 'bar', None, u'')]filterViewRegistrations(regs, iface, level=SPECIFC_INTERFACE_LEVEL)Oftentimes the amount of views that are being returned for a particular
interface are too much to show at once. It is then good to split the view into
categories. ThefilterViewRegistrations()function allows you to filter the
views on how specific they are to the interface. Here are the three levels you
can select from:SPECIFC_INTERFACE_LEVEL – Only return registrations that require thespecified interface directly.EXTENDED_INTERFACE_LEVEL – Only return registrations that require aninterface that the specified interface extends.GENERIC_INTERFACE_LEVEL – Only return registrations that explicitelyrequire theInterfaceinterface.So, let’s see how this is done. We first need to create a couple of interfaces
and register some views:>>> class IContent(Interface):
... pass
>>> class IFile(IContent):
... passClear out the registries first, so we know what we have.
>>> from zope.testing.cleanup import cleanUp
>>> cleanUp()>>> provideAdapter(None, (IContent, IHTTPRequest), Interface,
... name='view.html')
>>> provideAdapter(None, (IContent, IHTTPRequest), Interface,
... name='edit.html')
>>> provideAdapter(None, (IFile, IHTTPRequest), Interface,
... name='view.html')
>>> provideAdapter(None, (Interface, IHTTPRequest), Interface,
... name='view.html')Now we get all the registrations:>>> regs = list(presentation.getViews(IFile, IHTTPRequest))Let’s now filter those registrations:>>> result = list(presentation.filterViewRegistrations(
... regs, IFile, level=presentation.SPECIFIC_INTERFACE_LEVEL))
>>> result.sort()
>>> result
[AdapterRegistration(<BaseGlobalComponents base>,
[IFile, IHTTPRequest], Interface, 'view.html', None, u'')]>>> result = list(presentation.filterViewRegistrations(
... regs, IFile, level=presentation.EXTENDED_INTERFACE_LEVEL))
>>> result.sort()
>>> result
[AdapterRegistration(<BaseGlobalComponents base>,
[IContent, IHTTPRequest], Interface, 'edit.html', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IContent, IHTTPRequest], Interface, 'view.html', None, u'')]>>> result = list(presentation.filterViewRegistrations(
... regs, IFile, level=presentation.GENERIC_INTERFACE_LEVEL))
>>> result.sort()
>>> result
[AdapterRegistration(<BaseGlobalComponents base>,
[Interface, IHTTPRequest], Interface, 'view.html', None, u'')]You can also specify multiple levels at once using the Boolean OR operator,
since all three levels are mutually exclusive.>>> result = list(presentation.filterViewRegistrations(
... regs, IFile, level=presentation.SPECIFIC_INTERFACE_LEVEL |
... presentation.EXTENDED_INTERFACE_LEVEL))
>>> result.sort()
>>> result
[AdapterRegistration(<BaseGlobalComponents base>,
[IContent, IHTTPRequest], Interface, 'edit.html', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IContent, IHTTPRequest], Interface, 'view.html', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[IFile, IHTTPRequest], Interface, 'view.html', None, u'')]>>> result = list(presentation.filterViewRegistrations(
... regs, IFile, level=presentation.SPECIFIC_INTERFACE_LEVEL |
... presentation.GENERIC_INTERFACE_LEVEL))
>>> result.sort()
>>> result
[AdapterRegistration(<BaseGlobalComponents base>,
[IFile, IHTTPRequest], Interface, 'view.html', None, u''),
AdapterRegistration(<BaseGlobalComponents base>,
[Interface, IHTTPRequest], Interface, 'view.html', None, u'')]getViewInfoDictionary(reg)Now that we have all these utilities to select the registrations, we need to
prepare the them for output. For page templates the best data structures are
dictionaries and tuples/lists. This utility will generate an informational
dictionary for the specified registration.Let’s first create a registration:>>> from zope.component.registry import AdapterRegistration
>>> reg = AdapterRegistration(None, (IFile, Interface, IHTTPRequest),
... Interface, 'view.html', Factory, 'reg info')>>> pprint(presentation.getViewInfoDictionary(reg), width=1)
{'doc': 'reg info',
'factory': {'path': 'zope.apidoc.doctest.Factory',
'referencable': True,
'resource': None,
'template': None,
'url': 'zope/apidoc/doctest/Factory'},
'name': u'view.html',
'provided': {'module': 'zope.interface',
'name': 'Interface'},
'read_perm': None,
'required': [{'module': 'zope.apidoc.doctest',
'name': 'IFile'},
{'module': 'zope.interface',
'name': 'Interface'},
{'module': 'zope.publisher.interfaces.http',
'name': 'IHTTPRequest'}],
'type': 'zope.publisher.interfaces.http.IHTTPRequest',
'write_perm': None,
'zcml': None}Miscellaneous UtilitiesThe utilities module provides some useful helper functions and classes that
make the work of the API doctool and inspection code easier.>>> from zope.apidoc import utilitiesrelativizePath(path)When dealing with files, such as page templates and text files, and not with
Python paths, it is necessary to keep track of the the absolute path of the
file. However, for presentation purposes, the absolute path is inappropriate
and we are commonly interested in the path starting at the Zope 3 root
directory. This function attempts to remove the absolute path to the root
directory and replaces it with “Zope3”.>>> import os
>>> path = os.path.join(utilities.BASEDIR, 'src', 'zope', 'README.txt')>>> utilities.BASEDIR in path
True>>> path = utilities.relativizePath(path)>>> utilities.BASEDIR in path
False# Be kind to Windows users
>>> path.replace(’', ‘/’)
‘Zope3/src/zope/README.txt’If the base path is not found in a particular path, the original path is
returned:>>> otherpath = 'foo/bar/blah.txt'
>>> utilities.relativizePath(otherpath)
'foo/bar/blah.txt'truncateSysPath(path)In some cases it is useful to just know the path after the sys path of a
module. For example, you have a path of a file in a module. To look up the
module, the simplest to do is to retrieve the module path and look into the
system’s modules list.>>> import sys
>>> sysBase = sys.path[0]>>> utilities.truncateSysPath(sysBase + '/some/module/path')
'some/module/path'If there is no matching system path, then the whole path is returned:>>> utilities.truncateSysPath('some/other/path')
'some/other/path'getPythonPath(obj)Return the path of the object in standard Python dot-notation.This function makes only sense for objects that provide a name, since we
cannot determine the path otherwise. Instances, for example, do not have a__name__attribute, so we would expect them to fail.For interfaces we simply get>>> from zope.interface import Interface
>>> class ISample(Interface):
... pass>>> utilities.getPythonPath(ISample)
'zope.apidoc.doctest.ISample'and for classes>>> class Sample(object):
... def sample(self):
... pass>>> utilities.getPythonPath(Sample.sample)
'zope.apidoc.doctest.Sample'One can also pass functions>>> def sample():
... pass>>> utilities.getPythonPath(sample)
'zope.apidoc.doctest.sample'and even methods. If a method is passed in, its class path is returned.>>> utilities.getPythonPath(Sample.sample)
'zope.apidoc.doctest.Sample'Modules are another kind of objects that can return a python path:>>> utilities.getPythonPath(utilities)
'zope.apidoc.utilities'Passing inNonereturnsNone:>>> utilities.getPythonPath(None)Clearly, instance lookups should fail:>>> utilities.getPythonPath(Sample())
Traceback (most recent call last):
...
AttributeError: 'Sample' object has no attribute '__name__'isReferencable(path)Determine whether a path can be referenced in the API doc, usually by the code
browser module. Initially you might think that all objects that have paths can
be referenced somehow. But that’s not true, partially by design of apidoc, but
also due to limitations of the Python language itself.First, here are some cases that work:>>> utilities.isReferencable('zope')
True
>>> utilities.isReferencable('zope.app')
True
>>> utilities.isReferencable('zope.apidoc.classregistry.ClassRegistry')
True
>>> utilities.isReferencable('zope.apidoc.utilities.isReferencable')
TrueThe first case isNone. When you ask for the python path ofNone, you
getNone, so that result should not be referencable:>>> utilities.isReferencable(None)
FalseBy design we also do not document any private classes and functions:>>> utilities.isReferencable('some.path.to._Private')
False
>>> utilities.isReferencable('some.path.to.__Protected')
False
>>> utilities.isReferencable('zope.apidoc.__doc__')
TrueSome objects might fake their module name, so that it does not exist:>>> utilities.isReferencable('foo.bar')
FalseOn the other hand, you might have a valid module, but non-existent attribute:>>> utilities.isReferencable('zope.apidoc.MyClass')
FalseNote that this case is also used for types that are generated using thetype()function:>>> mytype = type('MyType', (object,), {})
>>> path = utilities.getPythonPath(mytype)
>>> path
'zope.apidoc.doctest.MyType'>>> utilities.isReferencable(path)
FalseNext, since API doc does not allow the documentation of instances yet, it
is not possible to document singletons, so they are not referencable:>>> class Singelton(object):
... pass>>> utilities.isReferencable('zope.apidoc.doctest.Singelton')
True>>> Singelton = Singelton()>>> utilities.isReferencable('zope.apidoc.doctest.Singelton')
FalseFinally, the globalIGNORE_MODULESlist from the class registry is also
used to give a negative answer. If a module is listed inIGNORE_MODULES,
thenFalseis returned.>>> import classregistry
>>> classregistry.IGNORE_MODULES.append('zope.apidoc')>>> utilities.isReferencable('zope.app')
True
>>> utilities.isReferencable('zope.apidoc')
False
>>> utilities.isReferencable('zope.apidoc.apidoc.APIDocumentation')
False>>> classregistry.IGNORE_MODULES.pop()
'zope.apidoc'
>>> utilities.isReferencable('zope.apidoc')
TruegetPermissionIds(name, checker=_marker, klass=_marker)Get the permissions of a class attribute. The attribute is specified by name.Either theklassor thecheckerargument must be specified. If the class
is specified, then the checker for it is looked up. Furthermore, this function
only works withINameBasedCheckercheckers. If another checker is found,Noneis returned for the permissions.We start out by defining the class and then the checker for it:>>> from zope.security.checker import Checker, defineChecker
>>> from zope.security.checker import CheckerPublic>>> class Sample(object):
... attr = 'value'
... attr3 = 'value3'>>> class Sample2(object):
... pass>>> checker = Checker({'attr': 'zope.Read', 'attr3': CheckerPublic},
... {'attr': 'zope.Write', 'attr3': CheckerPublic})
>>> defineChecker(Sample, checker)Now let’s see how this function works:>>> entries = utilities.getPermissionIds('attr', klass=Sample)
>>> entries['read_perm']
'zope.Read'
>>> entries['write_perm']
'zope.Write'>>> from zope.security.checker import getCheckerForInstancesOf
>>> entries = utilities.getPermissionIds('attr',
... getCheckerForInstancesOf(Sample))
>>> entries['read_perm']
'zope.Read'
>>> entries['write_perm']
'zope.Write'TheSampleclass does not know about theattr2attribute:>>> entries = utilities.getPermissionIds('attr2', klass=Sample)
>>> print entries['read_perm']
n/a
>>> print entries['write_perm']
n/aTheSample2class does not have a checker:>>> entries = utilities.getPermissionIds('attr', klass=Sample2)
>>> entries['read_perm'] is None
True
>>> print entries['write_perm'] is None
TrueFinally, theSampleclass’attr3attribute is public:>>> entries = utilities.getPermissionIds('attr3', klass=Sample)
>>> print entries['read_perm']
zope.Public
>>> print entries['write_perm']
zope.PublicgetFunctionSignature(func)Return the signature of a function or method. Thefuncargumentmustbe a
generic function or a method of a class.First, we get the signature of a function that has a specific positional and
keyword argument:>>> def func(attr, attr2=None):
... pass
>>> utilities.getFunctionSignature(func)
'(attr, attr2=None)'Here is a function that has an unspecified amount of keyword arguments:>>> def func(attr, **kw):
... pass
>>> utilities.getFunctionSignature(func)
'(attr, **kw)'And here we mix specified and unspecified keyword arguments:>>> def func(attr, attr2=None, **kw):
... pass
>>> utilities.getFunctionSignature(func)
'(attr, attr2=None, **kw)'In the next example we have unspecified positional and keyword arguments:>>> def func(*args, **kw):
... pass
>>> utilities.getFunctionSignature(func)
'(*args, **kw)'And finally an example, where we have on unspecified keyword arguments without
any positional arguments:>>> def func(**kw):
... pass
>>> utilities.getFunctionSignature(func)
'(**kw)'Next we test whether the signature is correctly determined for class
methods. Note that theselfargument is removed from the signature, since it
is not essential for documentation.We start out with a simple positional argument:>>> class Klass(object):
... def func(self, attr):
... pass
>>> utilities.getFunctionSignature(Klass.func)
'(attr)'Next we have specific and unspecified positional arguments as well as
unspecified keyword arguments:>>> class Klass(object):
... def func(self, attr, *args, **kw):
... pass
>>> utilities.getFunctionSignature(Klass.func)
'(attr, *args, **kw)'If you do not pass a function or method to the function, it will fail:>>> utilities.getFunctionSignature('func')
Traceback (most recent call last):
...
TypeError: func must be a function or methodA very uncommon, but perfectly valid, case is that tuple arguments are
unpacked inside the argument list of the function. Here is an example:>>> def func((arg1, arg2)):
... pass
>>> utilities.getFunctionSignature(func)
'((arg1, arg2))'Even default assignment is allowed:>>> def func((arg1, arg2)=(1, 2)):
... pass
>>> utilities.getFunctionSignature(func)
'((arg1, arg2)=(1, 2))'However, lists of this type are not allowed inside the argument list:>>> def func([arg1, arg2]):
... pass
Traceback (most recent call last):
...
SyntaxError: invalid syntaxInternal assignment is also not legal:>>> def func((arg1, arg2=1)):
... pass
Traceback (most recent call last):
...
SyntaxError: invalid syntaxgetPublicAttributes(obj)Return a list of public attribute names for a given object.This excludes any attribute starting with ‘_’, which includes attributes of
the form__attr__, which are commonly considered public, but they are so
special that they are excluded. Theobjargument can be either a classic
class, type or instance of the previous two. Note that the term “attributes”
here includes methods and properties.First we need to create a class with some attributes, properties and methods:>>> class Nonattr(object):
... def __get__(*a):
... raise AttributeError('nonattr')>>> class Sample(object):
... attr = None
... def __str__(self):
... return ''
... def func(self):
... pass
... def _getAttr(self):
... return self.attr
... attr2 = property(_getAttr)
...
... nonattr = Nonattr() # Should not show up in public attrsWe can simply pass in the class and get the public attributes:>>> attrs = utilities.getPublicAttributes(Sample)
>>> attrs.sort()
>>> attrs
['attr', 'attr2', 'func']Note that we exclude attributes that would raise attribute errors,
like our silly Nonattr.But an instance of that class will work as well.>>> attrs = utilities.getPublicAttributes(Sample())
>>> attrs.sort()
>>> attrs
['attr', 'attr2', 'func']The function will also take inheritance into account and return all inherited
attributes as well:>>> class Sample2(Sample):
... attr3 = None>>> attrs = utilities.getPublicAttributes(Sample2)
>>> attrs.sort()
>>> attrs
['attr', 'attr2', 'attr3', 'func']getInterfaceForAttribute(name, interfaces=_marker, klass=_marker, asPath=True)Determine the interface in which an attribute is defined. This function is
nice, if you have an attribute name which you retrieved from a class and want
to know which interface requires it to be there.Either theinterfacesorklassargument must be specified. Ifinterfacesis not specified, theklassis used to retrieve a list of
interfaces.interfacesmust be iterable.asPathspecifies whether the dotted name of the interface or the interface
object is returned.First, we need to create some interfaces and a class that implements them:>>> from zope.interface import Interface, Attribute, implements
>>> class I1(Interface):
... attr = Attribute('attr')>>> class I2(I1):
... def getAttr():
... '''get attr'''>>> class Sample(object):
... implements(I2)First we check whether an aatribute can be found in a list of interfaces:>>> utilities.getInterfaceForAttribute('attr', (I1, I2), asPath=False)
<InterfaceClass zope.apidoc.doctest.I1>
>>> utilities.getInterfaceForAttribute('getAttr', (I1, I2), asPath=False)
<InterfaceClass zope.apidoc.doctest.I2>Now we are repeating the same lookup, but using the class, instead of a list
of interfaces:>>> utilities.getInterfaceForAttribute('attr', klass=Sample, asPath=False)
<InterfaceClass zope.apidoc.doctest.I1>
>>> utilities.getInterfaceForAttribute('getAttr', klass=Sample, asPath=False)
<InterfaceClass zope.apidoc.doctest.I2>By default,asPathisTrue, which means the path of the interface is
returned:>>> utilities.getInterfaceForAttribute('attr', (I1, I2))
'zope.apidoc.doctest.I1'If no match is found,Noneis returned.>>> utilities.getInterfaceForAttribute('attr2', (I1, I2)) is None
True
>>> utilities.getInterfaceForAttribute('attr2', klass=Sample) is None
TrueIf both, theinterfacesandklassargument are missing, raise an error:>>> utilities.getInterfaceForAttribute('getAttr')
Traceback (most recent call last):
...
ValueError: need to specify interfaces or klassSimilarly, it does not make sense if both are specified:>>> utilities.getInterfaceForAttribute('getAttr', interfaces=(I1,I2),
... klass=Sample)
Traceback (most recent call last):
...
ValueError: must specify only one of interfaces and klasscolumnize(entries, columns=3)This function places a list of entries into columns.Here are some examples:>>> utilities.columnize([1], 3)
[[1]]>>> utilities.columnize([1, 2], 3)
[[1], [2]]>>> utilities.columnize([1, 2, 3], 3)
[[1], [2], [3]]>>> utilities.columnize([1, 2, 3, 4], 3)
[[1, 2], [3], [4]]>>> utilities.columnize([1], 2)
[[1]]>>> utilities.columnize([1, 2], 2)
[[1], [2]]>>> utilities.columnize([1, 2, 3], 2)
[[1, 2], [3]]>>> utilities.columnize([1, 2, 3, 4], 2)
[[1, 2], [3, 4]]getDocFormat(module)This function inspects a module to determine the supported documentation
format. The function returns a valid renderer source factory id.If the__docformat__module attribute is specified, its value will be used
to look up the factory id:>>> from zope.apidoc import utilities
>>> utilities.getDocFormat(utilities)
'zope.source.rest'By default structured text is returned:>>> from zope.apidoc import tests
>>> utilities.getDocFormat(tests)
'zope.source.stx'This is a sensible default, since we only decided later in development to
endorse restructured text, so that many files are still in the structured text
format. All converted and new modules will have the__docformat__attribute.The__docformat__attribute can also optionally specify a language field. We
simply ignore it:>>> class Module(object):
... pass
>>> module = Module()
>>> module.__docformat__ = 'restructuredtext en'
>>> utilities.getDocFormat(module)
'zope.source.rest'dedentString(text)Before doc strings can be processed using STX or ReST they must be dendented,
since otherwise the output will be incorrect. Let’s have a look at some
docstrings and see how they are correctly dedented.Let’s start with a simple one liner. Nothing should happen:>>> def func():
... '''One line documentation string'''>>> utilities.dedentString(func.__doc__)
'One line documentation string'Now what about one line docstrings that start on the second line? While this
format is discouraged, it is frequently used:>>> def func():
... '''
... One line documentation string
... '''>>> utilities.dedentString(func.__doc__)
'\nOne line documentation string\n'We can see that the leading whitespace on the string is removed, but not the
newline character. Let’s now try a simple multi-line docstring:>>> def func():
... '''Short description
...
... Lengthy description, giving some more background information and
... discuss some edge cases.
... '''>>> print utilities.dedentString(func.__doc__)
Short description
<BLANKLINE>
Lengthy description, giving some more background information and
discuss some edge cases.
<BLANKLINE>Again, the whitespace was removed only after the first line. Also note that
the function determines the indentation level correctly. So what happens if
there are multiple indentation levels? The smallest amount of indentation is
chosen:>>> def func():
... '''Short description
...
... Root Level
...
... Second Level
... '''>>> print utilities.dedentString(func.__doc__)
Short description
<BLANKLINE>
Root Level
<BLANKLINE>
Second Level
<BLANKLINE>>>> def func():
... '''Short description
...
... $$$ print 'example'
... example
...
... And now the description.
... '''>>> print utilities.dedentString(func.__doc__)
Short description
<BLANKLINE>
$$$ print 'example'
example
<BLANKLINE>
And now the description.
<BLANKLINE>renderText(text, module=None, format=None)A function that quickly renders the given text using the specified format.If themoduleargument is specified, the function will try to determine the
format using the module. If theformatargument is given, it is simply
used. Clearly, you cannot specify both, themoduleandformatargument.You specify the format as follows:>>> utilities.renderText('Hello!\n', format='zope.source.rest')
u'<p>Hello!</p>\n'Note that the format string must be a valid source factory id; if the factory
id is not given, ‘zope.source.stx’ is used. Thus, specifying the module is
often safer (if available):>>> utilities.renderText('Hello!\n', module=utilities)
u'<p>Hello!</p>\n'The Class RegistryThis little registry 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 thegetClassesThatImplement(iface)method that returns all classes that
implement the passed interface. Another method,getSubclassesOf(klass)returns all registered subclassess of the given class.The class registry, subclassing the dictionary type, can be instantiated like
any other dictionary:>>> from zope.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, implements>>> class IA(Interface):
... pass
>>> class IB(IA):
... pass
>>> class IC(Interface):
... pass
>>> class ID(Interface):
... pass>>> class A(object):
... implements(IA)
>>> reg['A'] = A>>> class B:
... implements(IB)
>>> reg['B'] = B>>> class B2(object):
... implements(IB)
>>> reg['B2'] = B2>>> class C(object):
... implements(IC)
>>> reg['C'] = C
>>> class A2(A):
... pass
>>> reg['A2'] = A2Since the registry is just a dictionary, we can ask for all its keys, which
are the names of the classes:>>> names = reg.keys()
>>> names.sort()
>>> names
['A', 'A2', 'B', 'B2', 'C']>>> reg['A'] is A
TrueThere are two API methods specific to the class registry:getClassesThatImplement(iface)This method returns all classes that implement the specified interface:>>> from pprint import pprint
>>> pprint(reg.getClassesThatImplement(IA)) #doctest:+ELLIPSIS
[('A', <class 'A'>),
('B', <class __builtin__.B at ...>),
('A2', <class 'A2'>),
('B2', <class 'B2'>)]>>> pprint(reg.getClassesThatImplement(IB)) #doctest:+ELLIPSIS
[('B', <class __builtin__.B at ...>),
('B2', <class 'B2'>)]>>> pprint(reg.getClassesThatImplement(IC))
[('C', <class 'C'>)]>>> pprint(reg.getClassesThatImplement(ID))
[]getSubclassesOf(klass)This method will find all classes that inherit the specified class:>>> pprint(reg.getSubclassesOf(A))
[('A2', <class 'A2'>)]>>> pprint(reg.getSubclassesOf(B))
[]Safe ImportsUsing thesafe_import()we can quickly look up modules by minimizing
import calls.>>> from zope.apidoc import classregistry
>>> from zope.apidoc.classregistry import safe_importFirst we try to find the path insys.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 thedefaultvalue.Here are some examples:>>> import sys
>>> 'zope' in sys.modules
True
>>> safe_import('zope') is sys.modules['zope']
True
>>> safe_import('weirdname') is None
TrueFor 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)
>>> f = open(filename, 'w')
>>> f.write('# dummy module\n')
>>> f.close()The temporary module is not already imported:>>> module_name = 'testmodule'
>>> module_name in sys.modules
FalseWhen we trysafe_import()now, we will still get thedefaultvalue,
because importing new modules is disabled by default:>>> safe_import(module_name) is None
TrueBut 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
TrueNow 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:>>> open(os.path.join(dir, 'alwaysfail.py'), 'w').write('raise ValueError\n')
>>> sys.path.insert(0, dir)>>> safe_import('alwaysfail') is None
TrueLet’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 ignorezope,>>> classregistry.IGNORE_MODULES.append('zope')then we cannot import it anymore, even though we know it is available:>>> safe_import('zope') is None
TrueNote that all sub-packages are also unavailable:>>> safe_import('zope.apidoc') is None
TrueWe also need to play nice concerning variables and have to reset the module
globals:>>> classregistry.IGNORE_MODULES.pop()
'zope'
>>> classregistry.__import_unknown_modules__ = FalseCHANGES1.0.0 (2013-02-25)Initial release independent ofzope.app.api. |
zope.app.annotation | This module has moved to zope.annotationCHANGES3.4.0 (2007-10-10)Initial release independent of the main Zope tree. |
zope.app.apidoc | This Zope 3 package provides fully dynamic API documentation of Zope 3 and
registered add-on components. The package is very extensible and can be easily
extended by implementing new modules.Documentation is available athttps://zopeappapidoc.readthedocs.io/CHANGES5.0 (2023-07-06)Drop support for Python 2.7, 3.5, 3.6.Add support for Python 3.11.4.3.0 (2021-12-15)Add support for Python 3.8, 3.9 and 3.10.Drop support for Python 3.4.4.2.0 (2018-08-21)Add support for Python 3.7.The rootCodedocumentation node no longer allows incidental
traversal and documentation of unregistered root modules such asreandlogging(builtinsis special cased). These were
not listed in the tables of contents or menus, and mostly served to
slow down static exports. To document a root module, explicitly
include it in ZCML with<apidoc:rootModulemodule="MODULE"/>.
Seeissue #20.Fixcodemodule.Modulefor modules that have a__file__ofNone. This can be the case with namespace packages, especially
under Python 3.7. Seeissue #17.Rendering documentation for a class that has a__doc__property
no longer fails but produces a descriptive message. Seeissue 16.Host documentation athttps://zopeappapidoc.readthedocs.io/Add argument tostatic-apidocfor loading a specific ZCML file. To use this feature, the ZCML file you specify needs to
establish a working Zope 3 publication environment. The easiest way to do so is to include this line in the ZCML:<includepackage='zope.app.apidoc'file='static.zcml'condition='havestatic-apidoc'/>.
SeePR #13.Class Finder entries in live apidoc are now displayed on separate lines, like in static exports.
SeePR #14.Class Finder search in static exports will search on Enter, not just when clicking “Find”.
SeePR #15.__main__.pyfiles are no longer imported by the code documentation module.
Seeissue #22.Cython functions registered as adapters on Python 2 no longer break
page generation with anAttributeError. Seeissue 25.Static exports no longer highlight lines in ZCML files. Seeissue #24.4.0.0 (2017-05-25)Add support for Python 3.4, 3.5, 3.6 and PyPy.The long-deprecated layer configuration was removed. It was only
ever available if thedeprecatedlayersZCML feature was installed.Modernize some of the templates.zope.app.apidoccan now be used
with Chameleon 3.2 via z3c.pt and z3c.ptcompat.Declared install dependency onzope.app.exception.Docstrings are treated as UTF-8 on Python 2.Handle keyword only arguments and annotations in function signatures
on Python 3.Change the default documentation format torestructuredtextfor
modules that do not specify a__docformat__. Previously it wasstructuredtext(STX).3.7.5 (2010-09-12)Define__file__in doctests to make them pass under Python 2.4.3.7.4 (2010-09-01)Prefer the standard library’s doctest module to the one from zope.testing.Remove unneeded dependencies zope.app.component and zope.app.container3.7.3 (2010-07-14)Apply refactoring from #153309.Fix LP bug 605057: ZCML links were no longer working (Guilherme Salgado)3.7.2 (2010-03-07)Adapted tests for Python2.43.7.1 (2010-01-05)Updated tests to work with zope.publisher 3.12 (usingzope.login).3.7.0 (2009-12-22)Updated tests to work with latestzope.testingand usezope.browserpagein
favor ofzope.app.pagetemplate.3.6.8 (2009-11-18)Updated the tests after movingIPossibleSiteandISitetozope.component.3.6.7 (2009-09-29)Updated the tests after movingITraverserback tozope.traversing.3.6.6 (2009-09-15)Made the tests work again with the most recent Zope Toolkit KGS.3.6.5 (2009-07-24)Update documentation file inzope.sitefromREADME.txttosite.txt.3.6.4 (2009-07-23)TheIContainedinterface moved tozope.location.interfaces. Make a
test pass.3.6.3 (2009-05-16)Explicitly defined default views.Replace relative url links with absolute ones.Addedz3cpackages to the code browser.Madebin/static-apidocprincipally working (publisher and
webserver mode). There are still some files which are not correctly
fetched.3.6.2 (2009-03-17)Adapt principal registry book chapter to a new place, as it was moved
from zope.app.security to zope.principalregistry.Remove zcml slugs and old zpkg-related files.3.6.1 (2009-02-04)When a module provides an interface or has an __all__ attribute,
use one of those for the module documentation. Fixes LP #323375.Undid broken link tosavepoint.txtcaused in 3.6.0. The latest
version of the transaction package puts savepoint.txt in thetestssubpackage.Expanded the presentation of module documentation.Class documentation now includes constructor information.3.6.0 (2009-01-31)Use zope.container instead of zope.app.container.Use zope.site instead of zope.app.component and zope.app.folder (in
at least a few places).savepoint.txtmoved from ZODB’s test directory a level up – we
follow.Make compatible with new zope.traversing and zope.location.3.5.0 (2009-01-17)Adapted transaction book chapters for new transaction egg. The
README.txt was removed and savepoint.txt was moved. Also add chapter
about dooming transactions (doom.txt).Changed mailing list address to zope-dev at zope.org, because zope3-dev
is retired now.Cleaned up dependencies.3.4.3 (2007-11-10)Fixhttps://bugs.launchpad.net/zope3/+bug/161737: Misleading text in
the interface viewer.Fixhttps://bugs.launchpad.net/zope3/+bug/161190: The zope3-dev
mailinglist has been retired, point to zope-dev.3.4.2 (2007-10-30)Avoid deprecation warnings forZopeMessageFactory.3.4.1 (2007-10-23)Avoid deprecation warnings.3.4.0 (2007-10-10)Improved package meta-data.Fixed the code to at least gracefully ignore unzipped eggs. Eventually we
want to handle eggs well.3.4.0a1 (2007-04-22)Initial release independent of the main Zope tree. |
zope.app.applicationcontrol | zope.app.applicationcontrolThe application control instance is usually generated upon startup.
This package provides runtime information adapter for application
control and Zope version. Also provide a utility with methods for
shutting down and restarting the server.CHANGES4.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 withzope.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 onzope.app.testingandzope.app.zcmlfiles, among others.Change dependency onZODB3toZODB.Remove the ability ofZopeVersionto 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 setLC_*in the environment: those variables shadowLANG.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 usedpip installinstead ofeasy_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: Launchingsvnreplaced the whole environment instead of just
appendingLANG.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 packageBreak dependency onzope.app.appsetupby using a conditional import3.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.
Seehttp://launchpad.net/bugs/219302Bugfix: ZopeVersion used to report an unknown version when running on a
machine with a locale different than English.
Seehttp://launchpad.net/bugs/177733Fixed deprecation warning in ftesting.zcml: import ZopeSecurityPolicy from
the new location.3.4.1 (2007-09-27)rebumped to replace faulty egg3.4.0 (2007-09-25)Initial documented releaseReflect changes form zope.app.error refactoring |
zope.app.appsetup | zope.app.appsetup READMEThis package provides application setup helpers for the Zope3 appserver.Contentszope.app.appsetup READMEBootstrap helpersCheck the Security PolicyDebug consoleProduct-specific configurationFaux configuration objectApplication APITest support functionsChangelog5.0 (2023-02-09)4.2.0 (2020-05-20)4.1.0 (2018-12-15)4.0.0 (2016-08-08)4.0.0a1 (2013-03-03)3.16.0 (2011-01-27)3.15.0 (2010-09-25)3.14.0 (2010-04-13)3.13.0 (2009-12-24)3.12.0 (2009-06-20)3.11 (2009-05-13)3.10.1 (2009-03-31)3.10.0 (2009-03-19)3.9.0 (2009-01-31)3.8.0 (2008-08-25)3.7.0 (2008-08-19)3.6.0 (2008-07-23)3.5.0 (2008-06-17)3.4.1 (2007-09-27)3.4.0 (2007-09-25)Bootstrap helpersThe 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
TrueGenerally, 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
TrueCheck the Security PolicyWhen 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 alsohttp://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.zcmlHowever, 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()Debug consoleThe 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> 'Product-specific configurationTheproductmodule 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 productLet’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 objectTheFauxConfigurationclass 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 APIThere 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 theFauxConfigurationclass 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 thegetProductConfiguration()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
TrueNote 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
TrueThe new sections are available, as expected:>>> product.getProductConfiguration("two")
{'abc': 'def'}Test support functionsAdditional 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 orNoneas
arguments. IfNoneis provided as the second argument, any configuration
settings for the name are removed, if present. If the second argument is notNone, it will be used as the return value forgetProductConfigurationfor 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"))
NoneThe 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 tosetProductConfiguration. Using this withsetProductConfigurationswould require constructingFauxConfigurationobjects.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 theloadConfigurationfunction:>>> 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'}}Changelog5.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 forpython 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 onzdaemon(split off fromZODB).Claim support for Python 3.4, 3.5 and PyPy which requireszope.app.publication>= 4.0.Drop Python 2.6 support.4.0.0a1 (2013-03-03)Added support for Python 3.3.Replaced deprecatedzope.interface.implementsusage with equivalentzope.interface.implementerdecorator.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 withzope.testing >= 3.10, requiring at least this
version andzope.testrunner.SwitchIErrorReportingUtility copy_to_zlogfield toTrue.Using Python’sdoctestmodule instead of depreactedzope.testing.doctest.3.14.0 (2010-04-13)Madezope.testingan optional (test) dependency.Removed test dependency onzope.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 onzope.testing.3.12.0 (2009-06-20)Usingzope.processlifetimeinterfaces and implementations
directly instead of BBB imports fromzope.app.appsetup.Got rid of depencency onzope.app.component.Got rid of test dependency onzope.app.security.3.11 (2009-05-13)Event interfaces / implementations moved tozope.processlifetime,
version 1.0. Depend on this package, and add BBB imports.3.10.1 (2009-03-31)Fixed aDeprecationWarningintroduced 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 thezope.app.appsetup.bootstrapmodule. 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 fromzope.sessioninto this
package. This removes a dependency from zope.session to this package.Remove one more deprecated function.3.9.0 (2009-01-31)Usezope.siteinstead ofzope.app.folderandzope.app.component.Usezope.containerinstead ofzope.app.container.Move error log bootstrapping logic fromzope.errorinto 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 inzope.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.loadConfigurationtest-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.authentication | This package provides a flexible and pluggable authentication utility for Zope
3, usingzope.pluggableauth. Several common plugins are provided.ContentsPluggable-Authentication UtilityAuthenticationSimple Credentials PluginSimple Authenticator PluginPrincipal FactoriesConfiguring a PAUUsing the PAU to AuthenticateAuthenticated Principal Creates EventsMultiple Authenticator PluginsMultiple Credentials PluginsPrincipal SearchingFound Principal Creates EventsMultiple Authenticator PluginsIssuing a ChallengeChallenge ProtocolsPluggable-Authentication PrefixesSearchingPrincipal FolderAuthenticationSearchChanging credentialsRemoving principalsVocabulariescredentialsPluginsChanges5.0 (2023-02-09)4.0.0 (2017-05-02)3.9 (2010-10-18)3.8.0 (2010-09-25)3.7.1 (2010-02-11)3.7.0 (2010-02-08)3.6.2 (2010-01-05)3.6.1 (2009-10-07)3.6.0 (2009-03-14)3.5.0 (2009-03-06)3.5.0a2 (2009-02-01)3.5.0a1 (2009-01-31)3.4.4 (2008-12-12)3.4.3 (2008-08-07)3.4.2 (2008-07-09)3.4.1 (2007-10-24)3.4.0 (2007-10-11)3.4.0b1 (2007-09-27)Pluggable-Authentication UtilityThe 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 thezope.authentication.interfaces.IAuthenticationinterface.AuthenticationThe primary job of PAU is to authenticate principals. It uses two types of
plug-ins in its work:Credentials PluginsAuthenticator PluginsCredentials 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 PluginTo 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 pluginAs a plugin, MyCredentialsPlugin needs to be registered as a named utility:>>> myCredentialsPlugin = MyCredentialsPlugin()
>>> provideUtility(myCredentialsPlugin, name='My Credentials Plugin')Simple Authenticator PluginNext 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.idOur 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 searchAs with the credentials plugin, the authenticator plugin must be registered
as a named utility:>>> myAuthenticatorPlugin = MyAuthenticatorPlugin()
>>> provideUtility(myAuthenticatorPlugin, name='My Authenticator Plugin')Principal FactoriesWhile 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 PAUFinally, 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 AuthenticateWe can now use the PAU to authenticate a sample request:>>> from zope.publisher.browser import TestRequest
>>> print(pau.authenticate(TestRequest()))
NoneIn 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!')))
NoneHowever, 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 EventsWe 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
TrueThe 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
TrueNormally, 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 PluginsThe 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!!')))
NoneWhen 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 PluginsAs 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 credentialsGet 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 SearchingAs 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: blackFor 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] = idThis 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: blackFound Principal Creates EventsAs 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
TrueAs 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 PluginsAs 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 ChallengePart 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 TrueThis 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 ProtocolsSometimes, 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 achallengeProtocolattribute that effectively
groups related plugins together for challenging. If a plugin returnsTruefrom 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 Trueand 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 PrefixesPrincipal 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}")SearchingPAU implements ISourceQueriables:>>> from zope.schema.interfaces import ISourceQueriables
>>> ISourceQueriables.providedBy(pau)
TrueThis 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
TrueIf 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
TruePrincipal FolderPrincipal folders contain principal-information objects that contain principal
information. We create an internal principal using theInternalPrincipalclass:>>> 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'] = p2AuthenticationPrincipal folders provide theIAuthenticatorPlugininterface. 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)SearchPrincipal 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 credentialsCredentials 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 principalsOf course, if a principal is removed, we can no-longer authenticate it:>>> del principals['p1']
>>> principals.authenticateCredentials({'login': 'bob',
... 'password': 'eek'})VocabulariesThe 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 useinto 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
TrueThe length reports the expected value.>>> len(vocab)
6One can get a term for a given value usinggetTerm(); its token, in
turn, should also return the same effective term fromgetTermByToken.>>> 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)']credentialsPluginsFor 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 useinto 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)
6One can get a term for a given value usinggetTerm(); its token, in
turn, should also return the same effective term fromgetTermByToken.>>> 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)']Changes5.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’sdoctestmodule instead of deprecatedzope.testing.doctest[unit].Moved the following views fromzope.app.securitypolicyhere, to inverse
dependency between these two packages, aszope.app.securitypolicydeprecated in ZTK 1.0:@@grant.html@@AllRolePermissions.html@@RolePermissions.html@@RolesWithPermission.html3.7.1 (2010-02-11)Using the newprincipalfactories.zcmlfile, fromzope.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 tozope.securitypolicyupdate.Don’t usezope.app.testing.ztapiin 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 theloginForm.htmlview. Now the logic is contained in thezope.app.authentication.browser.loginform.LoginFormclass.Fix login form redirection failure in some cases with Python 2.6.Use the newzope.authenticationpackage instead ofzope.app.security.The “Password Manager Names” vocabulary and simple password manager registry
were moved to thezope.passwordpackage.Remove deprecated code.3.5.0 (2009-03-06)Split password manager functionality off to the newzope.passwordpackage. Backward-compatibility imports are left in place.Usezope.siteinstead ofzope.app.component. (Browser code still
needszope.app.componentas 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)Usezope.containerinstead ofzope.app.container. (Browser code
still needszope.app.containeras 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 formd5andshaon 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,
Changedsuper(BTreeContainer,self).__init__()tosuper(GroupFolder,self).__init__()inGroupFolderclass.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.basicskin | A very simple skin for the original Zope 3 ZMI.CHANGES5.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-04-22)Add support for Python 3.4, 3.5, and 3.6.Add support for PyPy.3.5.1 (2010-09-25)Added test extra to declare test dependency onzope.component [test].3.5.0 (2009-12-16)Avoid extraneous testing dependencies and remove test extra.Avoid zope.app.component testing dependency.Removed BBB import for IBasicSkin.3.4.1 (2009-08-15)Added missing test dependency: zope.app.component.3.4.0 (2007-10-11)Initial release independent of the main Zope tree. |
zope.app.boston | The Boston skin is a new UI for the Zope Management Interface called ZMI.Detailed DcoumentationThe Boston SkinThe 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 = FalseCheck 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=')CHANGES3.5.1 (2010-01-08)Fix test bug (in combination with a newer zope.app.securitypolicy).3.5.0 (2010-01-05)Use zope.container instead of zope.app.container.Use zope.browsermenu instead of zope.app.publisher.Use zope.publisher 3.12 and new zope.login to make tests work.3.4.0 (2007-11-03)Initial release independent of the main Zope tree.3.4.0b1Fixed invalid HTML in wiget_macros. |
zope.app.broken | When an object cannot be correctly loaded from the ZODB, this package allows
this object still to be instantiated, but as a “Broken” object. This allows
for gracefully updating the database without interruption.CHANGES5.0 (2023-02-08)Add support for Python 3.10, 3.11.Drop support for Python 2.7, 3.5, 3.6.Removezope.app.broken.interfaces.IBroken. It had been moved toZODB.interfaceslong ago.4.2 (2020-11-18)Deprecatezope.app.broken.interfaces.IBroken. Please import it directly
fromZODB.interfaces.Add support for Python 3.9.4.1 (2020-03-31)Drop dependency onzope.broken, because the correct imports have
moved into ZODB.Add support for Python 3.7 and 3.8.4.0.0 (2017-05-16)Add support for Python 3.4, 3.5, 3.6 and PyPy.Change dependency onZODB3toZODB.Thebrowser.zcmlwill only be loaded ifzope.browserpageis
installed.Accessing the__parent__and__name__attributes of broken
objects will no longer raiseAttributeErrorif the state is an
unexpected type, instead returningNone.3.6.0 (2010-09-25)Depend on newzope.processlifetimeinterfaces and implementations
instead of using BBB imports fromzope.app.appsetup.Added test extra to declare test dependency onzope.testing.Using Python’sdoctestmodule instead of depreactedzope.testing.doctest.3.5.0 (2009-02-05)Depend on newzope.brokenpackage for theIBrokeninterface.3.4.0 (2007-10-11)Initial release independent of the main Zope tree. |
zope.app.cache | This package provides a caching mechanism for Zope applications.CHANGES3.7.0 (2009-07-25)Use the RAM cache implementation from zope.ramcache.3.6.0 (2009-05-27)Use zope.componentvocabulary instead of zope.app.component.3.5.0 (2009-01-31)Use zope.container instead of zope.app.container.3.4.1 (2008-07-30)Remove find-links from buildout.cfg.Get rid of zope.app.zapi as a dependency. Seehttp://launchpad.net/bugs/219302Fixed deprecation warning in zope.app.cache.browser.cacheable: zope.app.i18n
became zope.i18nmessageid.3.4.0 (2007-10-11)Initial release independent of the main Zope tree. |
zope.app.catalog | This package provides ZMI-based browser management pages and menu items
for zope.catalog - the cataloging and indexing framework for Zope 3.CHANGES4.0.0 (2017-05-05)Add support for Python 3.4, 3.5, 3.6 and PyPy.Remove test dependency onzope.app.testingandzope.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 newzope.catalogpackage,
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 onzope.app.containerwith a lighter-weight
dependency upon the newly refactoredzope.containerpackage.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 thesearchResultsmethod, 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)ResolveZopeSecurityPolicydeprecation warning.3.5.0 (2007-10-11)Updated some meta-data.Moveftests.pytotests.py.3.5.0a3 (2007-09-27)removed some deprecations3.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.component | NOTE: this package is deprecated. Its functionality has been moved to
more reusable packages, namely: zope.component, zope.security, zope.site
and zope.componentvocabulary. Please import from there instead.This package provides various ZCML directives (view, resource) and a
user interface related to local component management.ContentsCHANGES5.0 (2023-02-21)4.1.0 (2018-10-22)4.0.0 (2017-05-02)3.9.3 (2011-07-27)3.9.2 (2010-09-17)3.9.1 (2010-09-01)3.9.0 (2010-07-19)3.8.4 (2010-01-08)3.8.3 (2009-07-11)3.8.2 (2009-05-22)3.8.1 (2009-05-21)3.8.0 (2009-05-21)3.7.0 (2009-04-01)3.6.1 (2009-03-12)3.6.0 (2009-01-31)3.5.0 (2008-10-13)3.4.1 (2007-10-31)3.4.0 (2007-10-11)CHANGES5.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 fromzope.site)zope.app.component.queryNextUtility(import fromzope.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.Simplifyzope.app.component.testingto remove the deprecated or
broken functionality intestingNextUtilityandSiteManagerStub.PlacefulSetupis retained (and incorporates
much of what was previously inherited fromzope.app.testing),
although use ofzope.component.testing.PlacelessSetupis
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 onzope.app.authenticationwithzope.password.Removed unneeded dependencies.3.9.2 (2010-09-17)Replaced a testing dependency onzope.app.securitypolicywith one onzope.securitypolicy.3.9.1 (2010-09-01)No longer using deprecatedzope.testing.doctest. Use python’s build-indoctestinstead.Replaced the dependency onzope.deferredimportwith BBB imports.3.9.0 (2010-07-19)Added missing BBB import inzope.app.component.metaconfigure.Requiring at leastzope.component3.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 onzope.app.interface.3.8.2 (2009-05-22)Fix missing import inzope.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 tozope.site,zope.componentvocabularyandzope.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 deprecatedzope:defaultViewdirective and its
implementation. New directive to set default view isbrowser:defaultView.3.6.1 (2009-03-12)Makeclassdirective 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 tozope.security. In particular, the modulezope.app.component.contentdirectivehas moved tozope.security.metaconfigure, and a compatibility import has been
left in its place.Extractedzope.sitefrom zope.app.component with backwards
compatibility imports in place. Local site related functionality
is now inzope.siteand 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.metaconfigurebrowser: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)ResolveZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-11)Initial release independent of the main Zope tree. |
zope.app.container | This package define interfaces of container components, and provides
sample container implementations such as a BTreeContainer and
OrderedContainer.CHANGES5.0 (2023-02-08)Drop support for Python 2.7, 3.4, 3.5, 3.6.Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11.Fix deprecation warnings.4.0.0 (2017-04-24)Added support for PyPy and Python 3.4, 3.5 and 3.6.3.9.2 (2012-01-23)Replaced an undeclared test dependency onzope.app.authenticationwithzope.password.Removed undeclared test dependency onzope.app.folder.Replaced the use ofzope.app.pagetemplateand deprecatedzope.app.publisherwithzope.browserpageandzope.browsermenu.3.9.1 (2010-09-14)Removed a testing dependency onzope.app.file.Replaced a testing dependency onzope.app.securitypolicywith the basezope.securitypolicydistribution.3.9.0 (2010-08-19)Updatedftesting.zcmlto use the new permission names exported byzope.dublincore3.7.3.8.2 (2010-01-08)Fixed tests using a newer zope.publisher that requires zope.login.3.8.1 (2009-12-26)Fixed test_directive. Some parts of zope.app.publisher were moved
to zope.browsermenu and zope.browserpage.Moved tests/test_view_permissions.py to browser/tests.Added undeclared install dependency onzope.app.publisher.Test no longer use deprecatedzope.testing.doctestunitbut
python’sdoctestinstead.3.8.0 (2009-05-13)MovedIAddinginterface tozope.browser.interfaces, leaving
BBB imports.3.7.2 (2009-03-12)Show a “nothing to add” message instead of empty list in the
adding view, if there’s nothing to add.Don’t show the “Add” menu item if there’s nothing to add.Adapt to the removal of deprecated interfaces fromzope.component.interfaces. NowIAddinginherits fromzope.publisher.interfaces.browser.IBrowserView.3.7.1 (2009-02-05)Updated test to accomodate “Pythonic” exception now raised from__setitem__provided byzope.container(KeyErrorinstead
ofzope.exceptions.UserError).3.7.0 (2009-01-31)Remove long-time deprecatedIContentContainerclass.We now rely on a new package calledzope.container, which
contains the basic implementation ofzope.containerand is
intended to have less dependencies. We have gone through a wide
range of packages and updated their dependencies to point tozope.containerso that they will also have less indirect
dependencies.For backwards compatibility we have left the original modules inzope.app.containerin place and have placed imports to make sure
the symbols exist in their original locations.3.6.2 (2008-10-21)Fixed bug in_zope_app_container_contained.c.3.6.1 (2008-10-15)Reimplemented theBTreeContainerso that it directly accesses the btree
methods (removed an old #TODO)Removed usage of deprecatedLayerField.Made C code compatible with Python 2.5 on 64bit architectures.Fixed bug: Error thrown during__setitem__for an ordered container
leaves bad key in orderFixedhttps://bugs.launchpad.net/zope3/+bug/238579,https://bugs.launchpad.net/zope3/+bug/163149: Error with unicode
traversingFixedhttps://bugs.launchpad.net/zope3/+bug/221025: The Adding menu
is sorted with translated item by using a collator (better localized
sorting)Fixedhttps://bugs.launchpad.net/zope3/+bug/227617:prevent the namechooser from failing on ‘+’, ‘@’ and ‘/’added tests in the namechooserbe sure the name chooser returns unicodeFixedhttps://bugs.launchpad.net/zope3/+bug/175388: The setitem’s
size modification is now done insetitemf: setting an existing
item does not change the size, and the event subscribers should see
the new size instead of the old size.3.6.0 (2008-05-06)Added anIBTreeContainerinterface that allows an argument to theitems,keys, andvaluesmethods with the same semantics as for
a BTree object. The extended interface is implemented by theBTreeContainerclass.3.5 (2007-10-11)Updated bootstrap script to current version.Store length ofBTreeContainerin its ownLengthobject for faster__len__implementation of huge containers.SendIObjectModifiedEventwhen changing the title through the@@contents.htmlview.
This fixeshttps://bugs.edge.launchpad.net/zope3/+bug/98483.ResolveZopeSecurityPolicyandIRolePermissionManagerdeprecation
warning.3.4 (2007-04-22)Initial release as a separate project, corresponds tozope.app.containerfrom Zope 3.4.0a1. |
zope.app.content | This package defines anIInterfacethat allows the developer to mark
interfaces as content types.CHANGES5.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-04-23)Add support for PyPy.Add support for Python 3.4, 3.5 and 3.6.3.5.1 (2010-12-21)Replacezope.app.componentdependency withzope.componentvocabulary.3.5.0 (2010-09-20)Movedzope.app.interface.queryTypetozope.app.content.queryTypeto inverse dependency.3.4.0 (2007-10-11)Initial release independent of the main Zope tree. |
zope.app.dav | This package provides basic WebDAV support for a Zope application. A more
advanced implementation is available inz3c.dav.CHANGES3.5.3 (2010-03-11)Avoid creating a DAV namespace adapter per property in PROPPATCH
(create only one per namespace in a given request). See LP #98454.3.5.2 (2010-01-08)Fix tests using a newer zope.publisher that requires zope.login.3.5.1 (2009-09-15)Corrected invalid use of datetime.strftime. The timezone is denoted by %Z.3.5.0 (2009-02-01)Usezope.containerinstead ofzope.app.container.Usezope.siteinstead ofzope.app.folder.3.4.2 (2009-01-27)Substitute zope.app.zapi by direct calls to its wrapped apis. See
bug 219302.3.4.1 (2007-10-30)Removed deprecation warnings forZopeMessageFactoryandZopeSecurityPolicy.3.4.0 (2007-10-11)Initial release independent of the main Zope tree. |
zope.app.debug | This package provides a debugger for the Zope publisher. After Zope is
isntantiated, it drops the user into an interactive Python shell where the
full Zope environment and the database root are available.CHANGES4.0.0 (2017-05-08)Add support for Python 3.4, 3.5, 3.6 and PyPy.3.4.1 (2008-02-02)Fix of 599 error on conflict error in request
see:http://mail.zope.org/pipermail/zope-dev/2008-January/030844.html3.4.0 (2007-10-23)Initial release independent of the main Zope tree. |
zope.app.debugskin | The debug skin publishes failure tracebacks in the HTTP result.CHANGES3.4.1 (2010-09-16)Made tests compatible with current package versions.3.4.0 (2007-11-01)Initial release independent of the main Zope tree. |
zope.app.dependable | A simple object-dependency framework for Zope.CHANGES5.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 deprecatedpython 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.Addedtox.iniand 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.dtmlpage | This package provides a Zope 3 content component that contains DTML code,
which is executed when the component is accessed via its URL.CHANGES3.5.0 (2009-02-01)Reduced the dependency uponzope.app.containerto be simply a
dependency uponzope.container.3.4.1 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-23)Initial release independent of the main Zope tree. |
zope.app.dublincore | UNKNOWN |
zope.app.error | This package provides management views for the error reporting
utility defined in zope.error package.READMEThis package provides an error reporting utility which is able to
store errors. (Notice that the implementation classes have been moved
to thezope.errorpackage.)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 thebrowsersub-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>
... """)CHANGES4.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 [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.txt3.5.1 (2007-09-27)rebumped to replace faulty egg3.5.0Move core components tozope.error3.4.0 (2007-09-24)Initial documented release |
zope.app.exception | This packages provides Zope 3 browser views for some generic exceptions.ContentsSystem ErrorsCHANGES5.0 (2023-02-07)4.1.0 (2021-03-22)4.0.1 (2017-05-15)4.0.0 (2017-05-01)3.6.3 (2011-05-23)3.6.2 (2010-09-14)3.6.1 (2010-01-08)3.6.0 (2009-05-18)3.5.0 (2009-04-06)3.4.2 (2009-01-27)3.4.1 (2007-10-31)3.4.0 (2007-10-24)System ErrorsSystem 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 inftesting.zcmlwhich raisesException():>>> 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 asComponentLookupError. I have registered a simple
view inftesting.zcml, too, that will raise a component lookup
error. So if we callcomponentlookuperror.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.
...CHANGES5.0 (2023-02-07)Add support for Python 3.10, 3.11.Drop support for Python 2.7, 3.5, 3.6.4.1.0 (2021-03-22)Add support for Python 3.7, 3.8 and 3.9.Drop support for Python 3.4.Fix tests to run withzope.component >= 5.4.0.1 (2017-05-15)Fix rendering of user errors on Python 3.
Seeissue 2.4.0.0 (2017-05-01)Add support for PyPy, and Python 3.4, 3.5 and 3.6.Remove test dependency onzope.app.testing,zope.app.zcmlfilesand many others.3.6.3 (2011-05-23)Replaced an undeclared test dependency onzope.app.authenticationwithzope.password.3.6.2 (2010-09-14)No longer depend onzope.app.zptpagefor tests.Replaced dependency onzope.app.securitypolicybyzope.securitypolicy.3.6.1 (2010-01-08)Require zope.browserpage which now containsnamedtemplate.Fix ftesting.zcml due tozope.securitypolicyupdate.Fix tests using a newer zope.publisher that requires zope.login.3.6.0 (2009-05-18)ISystemErrorViewinterface has been moved tozope.browser.interfaces, leaving BBB import here.Cut dependency onzope.formlibby requiring newer version ofzope.app.pagetemplatewhich now containsnamedtemplate.3.5.0 (2009-04-06)Use newzope.authenticationinstead ofzope.app.security.Removed deprecated code and thus removed dependency on zope.deferredimport.Removed old zpkg-related SETUP.cfg file.3.4.2 (2009-01-27)Substitute zope.app.zapi by direct calls to its wrapped apis. See
bug 219302.Fixed author email and home page.3.4.1 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.externaleditor | This package allows Zope 3 content components to be edited via an editor of
your choice.CHANGES3.5.0 (2009-02-01)Change dependency fromzope.app.containertozope.containerand make it
a test dependency as it’s only used in the tests.Remove dependency on deprecatedzope.app.zapi.3.4.0 (2007-11-03)Initial release independent of the main Zope tree. |
zope.app.file | This package provides two basic Zope 3 content components, File and Image, and
their ZMI-compliant browser views.ContentsFile objectsAdding FilesBinary FilesText FilesNon-ASCII Text FilesNon-ASCII FilenamesSpecial URL handling for DTML pagesChanges4.0.0 (2017-05-16)3.6.1 (2010-09-17)3.6.0 (2010-08-19)3.5.1 (2010-01-08)3.5.0 (2009-01-31)3.4.6 (2009-01-27)3.4.5 (2009-01-27)3.4.4 (2008-09-05)3.4.3 (2008-06-18)3.4.2 (2007-11-09)3.4.1 (2007-10-31)3.4.0 (2007-10-24)File objectsAdding FilesYou 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)
TrueLet’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" />
<b>Object Name</b>
<input type="text" name="add_input_name" value="" />
</div>
...
</form>
...Binary FilesLet 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'
TrueAlso, 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'
TrueText FilesLet 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 FilesWe 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')
TrueAnd 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 FilenamesFilenames 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>
...Special URL handling for DTML pagesWhen 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>Changes4.0.0 (2017-05-16)Add support for Python 3.4, 3.5, 3.6 and PyPy.Remove test dependency onzope.app.testingandzope.app.zcmlfiles,
among others.Change dependency from ZODB3 to persistent and add missing
dependencies onzope.app.content.3.6.1 (2010-09-17)Removed ZPKG slugs and ZCML ones.Moved a functional test here fromzope.app.http.Using Python’sdoctestinstead of deprecatedzope.testing.doctest.3.6.0 (2010-08-19)Updatedftesting.zcmlto use the new permission names exported byzope.dublincore3.7.Using python’sdoctestinstead of deprecatedzope.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)Replacezope.app.folderuse byzope.site. Add missing
dependency insetup.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.zapi3.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 theIObjectModifiedEventafter upload.This fixeshttps://bugs.launchpad.net/zope3/+bug/98483.3.4.1 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.folder | This packages provides the standard Folder content type for Zope 3. It also
implements the root folder of a Zope application. Folders can also be
converted to sites, which allow one to register components locally.CHANGES5.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.form | This package provides the old form framework for Zope 3. It also
implements a few high-level ZCML directives for declaring forms. More
advanced alternatives are implemented inzope.formlibandz3c.form. The widgets that were defined in here were moved tozope.formlib. Version 4.0 and newer are maintained for backwards
compatibility reasons only.Detailed documentation:CHANGES6.0 (2023-02-24)Drop support for Python 2.7, 3.4, 3.5, 3.6.Add support for Python 3.8, 3.9, 3.10, 3.11.Adapt to changes inzope.configuration >= 4.4.5.1.0 (2018-10-22)Add support for Python 3.7.5.0.0 (2017-04-27)Add support for PyPy, Python 3.4, 3.5 and 3.6.4.0.2 (2010-01-22)Seems like 4.0.1 was released already. Brown bag.4.0.1 (2010-01-08)Import ‘escape’ for backwards compatibility as packages turn out to be
importing this too, even though it’s actually from the Python standard
library.Widget documentation is now on PyPI too.4.0 (2010-01-08)The widget implementations have been moved to zope.formlib. This
makes this package depend on zope.formlib. The dependency of zope.formlib
on this package has been broken.3.12.1 (2009-12-22)Added missing zope.datetime dependency.3.12.0 (2009-12-22)Use zope.browserpage in favor of zope.app.pagetemplate.3.11.1 (2009-12-22)Prefer zope.testing.doctest over doctestunit and adjust test output to newer
zope.schema release.3.11.0 (2009-12-18)Use zope.component.testing in favor of zope.app.testing where possible.Define dummy standard_macros for test purposes. This reduces the test
dependencies by zope.app.basicskin and zope.browserresource.Removed the zope.app.container and zope.app.publisher testing dependencies.Refactored code to remove zope.app.component dependency.Made the tests independent of zope.app.locales.Reduce zope.app test dependencies by avoiding zope.app.securitypolicy and
zope.app.zcmlfiles.3.10.0 (2009-12-17)Avoid thezope.app.basicskindependency, by defining our own FormMacros.3.9.0 (2009-10-08)Internationalized ‘Invalid value’ used with ConversionErrorAdded dependency on transaction and test dependency on zope.app.component.Moved dependencies on ZODB3 and zope.location to the test extra.Reduced the dependency on zope.app.publisher to a dependency on
zope.browsermenu plus a test dependency on zope.browserpage.3.8.1 (2009-07-23)Fix unittest failure due to translation update.3.8.0 (2009-05-24)Use standard properties instead ofzope.cachedescriptors.Requirezope.browser1.1 instead ofzope.app.containerfor IAdding.3.7.3 (2009-05-11)Fixed invalid markup.3.7.2 (2009-03-12)Fixed bug where OrderedMultiSelectWidget did not respect the widgets
size attribute.Fixed bug in SequenceWidget where it crashed while trying to iterate
a missing_value (None in most of cases) on _getRenderedValue.Adapt to removal of deprecated interfaces from zope.component.interfaces.
The IView was moved to zope.publisher and we use our custom IWidgetFactory
interface instead of removed zope.component.interfaces.IViewFactory.Fix tests to work on Python 2.6.3.7.1 (2009-01-31)Adapt to the upcoming zope.schema release 3.5.1 which will also silence the
spurioussetfailures.3.7.0 (2008-12-11)use zope.browser.interfaces.ITerms instead of zope.app.form.browser.interfacesDepending on zope.schema>=3.5a1 which uses the builtinsetinstead of thesetsmodule.3.6.4 (2008-11-26)The URIDisplayWidget doesn’t render an anchor for empty/None values.3.6.3 (2008-10-15)Get rid of deprecated usage of LayerField from
zope.app.component.back35, replaced by
zope.configuration.fields.GlobalInterface.3.6.2 (2008-09-08)Fixed restructured text in doc tests to unbreak the PyPI page.(3.6.1 skipped due to a typo)3.6.0 (2008-08-22)Dropdown widgets display an item for the missing value even if the field is
required when no value is selected. See zope/app/form/browser/README.txt on
how to switch this off for BBB.Source select widgets for required fields are now required as well. They
used not to be required on the assumption that some value would be selected
by the browser, which had always been wrong except for dropdown widgets.3.5.0 (2008-06-05)Translate the title on SequenceWidget’s “Add <title>” button.No longer uses zapi.3.4.2 (2008-02-07)Made display widgets for sources translate message IDs correctly.3.4.1 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-24)zope.app.formnow supports Python2.5Initial release independent of the main Zope tree.Before 3.4This package was part of the Zope 3 distribution and did not have its own
CHANGES.txt. For earlier changes please refer to either our subversion log or
the CHANGES.txt of earlier Zope 3 releases. |
zope.app.fssync | File Synchronization for Zope3The FSSync project (zope.app.fssync) provides support for filesystem
synchronization of Zope3 content that resides in a ZODB. This package defines
a Web-based API with basic support for some standard zope.app content
types and the standard security policy.This project is build on top of the more general zope.fssync package
which provides object serialization and deserialization tools. If you
need a pure Python API which is independent of the ZODB and the Zope3
security machinery you should look at zope.fssync.FSSync includes a command line client that resembles svn or cvs. Type:bin/zsync helpfor available commands and further information. If you want to see the zsync
client in action you can run the demo application:bin/demo startOpenhttp://localhost:8080/managein your browser and login withzsyncas your username and password. Add ademofolder with
some files via the ZMI. After that run the command line client for an
initial checkout:bin/zsync checkout http://zsync:zsync@localhost:8080/demo ./parts/checkoutEdit one of the files in the checkout directory and commit the changes:bin/zsync commit ./parts/checkoutThe modified file should now be available on the server.SSHZsync now supports communication over ssh in addition to http. ssh
urls look like:zsync+ssh://user:passwd@host:port/pathThe zsync protocol is the same as over HTTP, it simply is sent via
ssh.On the server side, the ssh server can check public keys to enforce
security (though the demo server doesn’t bother), and is responsible
for passing the zsync request to zope and returning the response over
ssh.There is an example ssh server in src/zope/app/fssync/demo_server.py
To use it, first make sure that zope is running. Then start the
server:sudo bin/demo-ssh-serverThis starts a demo ssh server on port 2200. The server must be run as
root in order to read the ssh host keys.In another terminal use the zsync client to connect to it:bin/zsync co zsync+ssh://zsync:zsync@localhost:2200/demo parts/co2This checks out the demo folder into the parts/co2 folder.You should be able to work in the check out normally. Zsync will use
ssh to communicate, but will otherwise act normally.Extending zsyncThe zsync script is generated by the following part of the buildout.cfg:[zsync]
recipe = zc.recipe.egg
eggs = zope.app.fssync
entry-points = zsync=zope.app.fssync.main:mainIf you want to use zope.app.fssync in your own application you
propably have to define application specific serializers and
deserializers. See zope/app/fssync/fssync.txtfor further documentation. You probably also need your own zsync script with
additional dependencies. Simply add the necessary eggs to the corresponding
buildout snippet of your project.Changes3.6The ssh transport now looks for known_hosts in an application specific file,
as well as the normal known_hosts file and in the user’s Agent. This file is
~/.ssh/fssync_known_hosts if POSIX and ~/ssh/fssync_known_hosts if win32.BUGFIX: The ssh transport now will prompt the user if he wishes to use an
unrecognized hostkey. If he says ‘yes’, it will be added to the fssync
known_hosts file. if he says ‘no’, an exception is raised.BUGFIX: If the user’s public key is encrypted, fssync will prompt for a
password.3.5Added -v –verbose switches to zsync status command. Verbose is off
by default.Added support for avoiding conflicts after commiting metadata files.Added ‘resolved’ as an alias for the ‘resolve’ command.Added a ‘merge’ command. It allows merging changes from one checkout
to another.Added ssh network transport. The client can now use zsync+ssh://
urls to communicate with the server. |
zope.app.ftp | This package provides an API for clients connecting via FTP.Detailed DcoumentationHow FTP Works in ZopeThe FTP server implementation is inzope.server.ftp.server. See
the README.txt file there.The publisher-based ftp server is inzope.server.ftp.publisher.The FTP server gets wired up with a request factory that creates
ftp requests with ftp publication objects.The ftp request object is defined inzope.publisher.ftp.The ftp publication object is defined inzope.app.publication.ftp.The publication object gets views to handle ftp requests. It
looks up a separate view for each method defined inzope.publisher.interfaces.ftp.IFTPPublisher.We provide a single class here that implements all of these methods.The view, in turn, uses adapters for theIReadFile,IWriteFile,IReadDirectory,IWriteDirectory,IFileFactory, andIDirectoryFactory, defined inzope.filerepresentation.interfaces.CHANGES3.5.0 (2009-02-01)Use zope.container instead of zope.app.container.3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.generations | Generations are a way of updating objects in the database when the application
schema changes. An application schema is essentially the structure of data,
the structure of classes in the case of ZODB or the table descriptions in the
case of a relational database.This package only contains the ZMI user interface forzope.generationsContentsCHANGES5.0 (2023-02-07)4.0.0 (2017-05-09)3.7.1 (2012-01-23)3.7.0 (2010-09-18)3.6.0 (2010-09-17)3.5.1 (2010-01-08)3.5.0 (2009-04-05)3.4.2 (2009-01-27)3.4.1 (2007-10-31)3.4.0 (2007-10-24)CHANGES5.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.Fix theevolveview to use independent transactions instead of
committing or aborting the thread-local current transaction.Drop dependency onzope.app.renderer.Drop test dependency onzope.app.testing,zope.app.zcmlfilesand others.3.7.1 (2012-01-23)Replaced an undeclared test dependency onzope.app.authenticationwithzope.password.3.7.0 (2010-09-18)Depends now on the extractedzope.generations.3.6.0 (2010-09-17)zope.app.generationsdepended onzope.app.applicationcontrolbut
did not declare it. Modernized dependecy tozope.applicationcontrolas
the needed interface has been moved there.Using python’sdoctestmodule instead of deprecatedzope.testing.doctest[unit].Replaced a testing dependency onzope.app.securitypolicywith one onzope.securitypolicy.3.5.1 (2010-01-08)Depend on newzope.processlifetimeinterfaces instead of using
BBB imports fromzope.app.appsetup.Fix ftesting.zcml due tozope.securitypolicyupdate.Fix tests using a newer zope.publisher that requires zope.login.3.5.0 (2009-04-05)MovedgetRootFolderutility method fromzope.app.zopeappgenerationstozope.app.generations.utility.Removed not necessary install dependency onzope.app.testing.3.4.2 (2009-01-27)Provide more logging output for the various stages and actions of evolving a
database.Fixed bug: A failing last generation would allow starting an app server
without having evolved to the minimum generation.Substitute zope.app.zapi by direct calls to its wrapped apis. See
bug 219302.Corrected author email and home page address.3.4.1 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.homefolder | The principal home folder subscriber lets you assign home folders to
principals as you would do in any OS. This particular implementation of such a
feature is intended as a demo of the power of the way to handle principals
and not as the holy grail. If you have concerns about the assumptions made in
this implementation (which are probably legitimate), just ignore this package
altogether.Detailed DcoumentationPrincipal Home FolderThe principal home folder subscriber lets you assign home folders to
principals as you would do in any OS. This particular implementation of such a
feature is intended as a demo of the power of the way to handle principals
and not as the holy grail. If you have concerns about the assumptions made in
this implementation (which are probably legitimate), just ignore this package
altogether.Managing the Home FoldersLet’s say we have a principal and we want to have a home folder for it. The
first task is to create the home folder manager, which keeps track of the
principal’s home folders:>>> from zope.app.homefolder.homefolder import HomeFolderManager
>>> manager = HomeFolderManager()Now the manager will not be able to do much, because it does not know where to
look for the principal home folders. Therefore we have to specify a folder
container:>>> from zope.container.btree import BTreeContainer
>>> baseFolder = BTreeContainer()
>>> manager.homeFolderBase = baseFolderNow we can assign a home folder to a principal:>>> manager.assignHomeFolder('stephan')Since we did not specify the name of the home folder, it is just the same
as the principal id:>>> manager.assignments['stephan']
'stephan'Since the home folder did not exist and thecreateHomeFolderoption was
turned on, the directory was created for you:>>> 'stephan' in baseFolder
TrueWhen creating the home folder, the principal also automatically receives thezope.Managerrole:>>> from zope.securitypolicy.interfaces import IPrincipalRoleManager
>>> roles = IPrincipalRoleManager(baseFolder['stephan'])
>>> [(role, str(setting))
... for role, setting in roles.getRolesForPrincipal('stephan')]
[(u'zope.Manager', 'PermissionSetting: Allow')]If a folder already exists for the provided name, then the creation is simply
skipped silently:>>> from zope.app.folder import Folder
>>> baseFolder['sc3'] = Folder()
>>> manager.assignHomeFolder('sc3')
>>> manager.assignments['sc3']
'sc3'This has the advantage that you can choose your ownIContainerimplementation instead of relying on the vanilla folder.Now let’s look at some derivations of the same task.Sometimes you want to specify an alternative folder name:>>> manager.assignHomeFolder('jim', folderName='J1m')
>>> manager.assignments['jim']
'J1m'
>>> 'J1m' in baseFolder
TrueEven though folders are created by default, you can specifically turn
that behavior off for a particular assignment:>>> manager.assignHomeFolder('dreamcatcher', create=False)
>>> manager.assignments['dreamcatcher']
'dreamcatcher'
>>> 'dreamcatcher' in baseFolder
FalseYou wish not to create a folder by default:>>> manager.createHomeFolder = False
>>> manager.assignHomeFolder('philiKON')
>>> manager.assignments['philiKON']
'philiKON'
>>> 'philiKON' in baseFolder
FalseYou do not want to create a folder by default, you want to create the
folder for a specific user:>>> manager.assignHomeFolder('stevea', create=True)
>>> manager.assignments['stevea']
'stevea'
>>> 'stevea' in baseFolder
TrueLet’s now look at removing home folder assignments. By default, removing an
assignment willnotdelete the actual folder:>>> manager.unassignHomeFolder('stevea')
>>> 'stevea' not in manager.assignments
True
>>> 'stevea' in baseFolder
TrueBut if you specify thedeleteargument, then the folder will be deleted:>>> 'J1m' in baseFolder
True
>>> manager.unassignHomeFolder('jim', delete=True)
>>> 'jim' not in manager.assignments
True
>>> 'J1m' in baseFolder
FalseNext, let’s have a look at retrieving the home folder for a principal. This
can be done as follows:>>> homeFolder = manager.getHomeFolder('stephan')
>>> homeFolder is baseFolder['stephan']
TrueIf you try to get a folder and it does not yet exist,Nonewill be
returned if autoCreateAssignment is False. Remember ‘dreamcatcher’, which
has an assignment, but not a folder:>>> 'dreamcatcher' in baseFolder
False
>>> homeFolder = manager.getHomeFolder('dreamcatcher')
>>> homeFolder is None
TrueHowever, if autoCreateAssignment is True and you try to get a home folder
of a principal which has no assignment, the assignment and the folder
will be automatically created. The folder will always be created, regardless
of the value of createHomeFolder. The name of the folder will be identically
to the principalId:>>> manager.autoCreateAssignment = True
>>> homeFolder = manager.getHomeFolder('florian')
>>> 'florian' in manager.assignments
True
>>> 'florian' in baseFolder
TrueSometimes you want to create a homefolder which is not a zope.app.Folder.
You can change the object type that is being created by changing the
containerObject property. It defaults to ‘zope.app.folder.Folder’.
Let’s create a homefile.>>> manager.containerObject = 'zope.app.file.File'
>>> manager.assignHomeFolder('fileuser', create=True)
>>> homeFolder = manager.getHomeFolder('fileuser')
>>> print homeFolder #doctest: +ELLIPSIS
<zope.app.file.file.File object at ...>You see that now a File object has been created. We reset containerObject
to zope,folder.Folder to not confuse the follow tests.>>> manager.containerObject = 'zope.folder.Folder'Accessing the Home FolderBut how does the home folder get assigned to a principal? There are two ways
of accessing the homefolder. The first is via a simple adapter that provides ahomeFolderattribute. The second method provides the folder via a path
adapter calledhomefolder.Let’s start by creating a principal:>>> from zope.security.interfaces import IPrincipal
>>> from zope.interface import implements
>>> class Principal:
... implements(IPrincipal)
... def __init__(self, id):
... self.id = id
>>> principal = Principal('stephan')We also need to register our manager as a utility:>>> from zope.app.testing import ztapi
>>> from zope.app.homefolder.interfaces import IHomeFolderManager
>>> ztapi.provideUtility(IHomeFolderManager, manager, 'manager')Now we can access the home folder via the adapter:>>> from zope.app.homefolder.interfaces import IHomeFolder
>>> adapter = IHomeFolder(principal)
>>> adapter.homeFolder is baseFolder['stephan']
TrueOr alternatively via the path adapter:>>> import zope.component
>>> from zope.traversing.interfaces import IPathAdapter
>>> zope.component.getAdapter(principal, IPathAdapter,
... "homefolder") is baseFolder['stephan']
TrueAs you can see, the path adapter just returns the homefolder. This way we can
guarantee that the folder’s full API is always available. Of course the real
way it will be used is via a TALES expression:Setup of the Engine>>> from zope.app.pagetemplate.engine import Engine
>>> from zope.tales.tales import Context
>>> context = Context(Engine, {'principal': principal})Executing the TALES expression>>> bytecode = Engine.compile('principal/homefolder:keys')
>>> list(bytecode(context))
[]
>>> baseFolder['stephan'][u'documents'] = Folder()
>>> list(bytecode(context))
[u'documents']CHANGES3.5.0 (2009-02-01)Usezope.containerinstead ofzope.app.container.Remove dependency onzope.app.zapi.3.4.0 (2007-11-03)Initial release independent of the main Zope tree. |
zope.app.http | This package implements the simplest HTTP behavior within the Zope
Publisher. It implements all HTTP verbs as views and defines the necessary
HTTP exceptions.CHANGES5.0 (2023-02-07)Drop support for Python 2.7, 3.3, 3.4, 3.5, 3.6.Add support for Python 3.7, 3.8 and 3.9.4.0.1 (2017-05-16)The PUT views return an empty byte string instead of an empty native
string. On Python 3, the unicode native string leads to a TypeError
in zope.publisher.http.4.0.0 (2016-08-08)Added support for Python 3.3 up to 3.6.Added support for PyPy2.3.10.2 (2011-08-09)Fixing brown bag release 3.10.1, failing tests.3.10.1 (2011-08-04)Replaced an undeclared test dependency onzope.app.authenticationwithzope.password.Replaced the testing dependency onzope.app.zcmlfileswith explicit
dependencies of a minimal set of packages.3.10.0 (2011-01-25)PUT raises405 MethodNotAllowedwhen the context cannot be adapted tozope.filerepresentation.interfaces.IWriteFilefor existing objects
resp.zope.filerepresentation.interfaces.IFileFactoryfor not existing
ones.3.9.0 (2010-09-17)Replaced a testing dependency onzope.app.securitypolicywith one onzope.securitypolicy.Removed test dependency onzope.app.fileby moving the test which needs
this package tozope.app.file.3.8 (2010-04-19)Remove dependency onzope.app.testingby using thezope.app.wsgi.testlayersupport instead.At the time of this writing the test dependency onzope.app.zcmlfilescannot be removed however, because there is a
dependency onzope.app.filefor testing, which pulls in the world.3.7 (2010-04-13)Remove unnecessary dependency onzope.app.publisher.Fix for an edge case:
If someone does adefaultViewfor the context object and someone comes with
a not allowed method, the exception view fails ongetAdapters.3.6.1 (2010-01-08)Replaced the dependency onzope.deprecationwith BBB importsMade the dependency onzope.app.publisherexplicitFix tests using a newerzope.publisherthat requireszope.login.3.6.0 (2009-05-23)MovedIHTTPException,IMethodNotAllowed, andMethodNotAllowedfromzope.app.httptozope.publisher.interfaces.http, fixing dependency
cycles involvingzope.app.http.3.5.2 (2009-04-01)Replaced deprecatedzope:defaultViewdirective withbrowser:defaultView.3.5.1 (2009-03-12)If the ‘CONTENT_LENGTH’ header is provided, provide this length as
argument to thereadmethod of the input stream object.3.5.0 (2009-02-01)Change dependency onzope.app.containertozope.container.3.4.5 (2010-01-28)Backport r108613 from trunk:
Fix for an edge case:
If someone does adefaultViewfor the context object and someone comes with
a not allowed method, the exception view fails ongetAdapters.3.4.4 (2009-01-29)Make tests compatible with newzope.traversingrelease.3.4.3 (2009-01-27)Added missing depencendy:zope.app.zcmlfiles.3.4.2 (2009-01-26)Add a couple of tests to the OPTIONS verb.Substitutezope.app.zapiby direct calls to its wrapped APIs and get
rid ofzope.app.zapias a dependency. See bug #LP219302.3.4.1 (2007-10-31)ResolvedZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.i18n | zope.app.i18nSummaryThis package provides placeful persistent translation domains and
message catalogs along with ZMI views for managing them.CaveatsCurrently this integration does not support the feature of plural messages
which is supported by the underlyingzope.i18nlibrary. In case you need
this feature, please discuss this in the issue tracker in the repository.CHANGES4.1.0 (2020-10-07)Add compatibility withzope.i18n >= 4.7. We fulfill the interface for
plural messages now, although we do not provide any implementation. This is
documented and raises NotImplementedError.4.0.1 (2019-07-10)Add support for Python 3.7.Fix deprecation warning about importing IRegistered/IUnregistered from
their old locations in zope.component.interfaces instead of their current
locations in zope.interface.interfaces.4.0.0 (2017-05-25)Add support for Python 3.5, 3.6 and PyPy.Replace dependency onZODB3withBTreesandpersistent.Drop test dependency onzope.app.testing.The synchronization view now uses Python’s built-in transport for
handling Basic Authentication. As a reminder, Basic Authentication
does not permit a colon (:) in the username, but does allow colons
in the password (if the server properly conforms to the specification).3.6.4 (2012-12-14)Fix translate() when used with ZODB 4.Remove test dependency on zope.app.component3.6.3 (2010-09-01)Remove undeclared dependency on zope.deferredimport.Use zope.publisher >= 3.9 instead of zope.app.publisher.3.6.2 (2009-10-07)Fix test_translate and follow recent change of HTTPResponse.redirect.3.6.1 (2009-08-15)Added a missing testing dependency on zope.app.component.3.6.0 (2009-03-18)Some of ZCML configuration was moved into another packages:The global INegotiator utility registration was moved intozope.i18n.The include ofzope.i18n.localeswas also moved intozope.i18n.The registration of IModifiableUserPreferredLanguages adapter was moved
intozope.app.publisher.The IAttributeAnnotation implementation statement for HTTPRequest was moved
intozope.publisherand will only apply ifzope.annotationis
available.The IUserPreferredCharsets adapter registration was also moved intozope.publisher.Depend on zope.component >= 3.6 instead of zope.app.component as thequeryNextUtilityfunction was moved there.Remove the oldzope.app.i18n.metadirectivesmodule as the directive was
moved tozope.i18nages ago.3.5.0 (2009-02-01)Use zope.container instead of zope.app.container.3.4.6 (2009-01-27)Fix a simple inconsistent MRO problem in testsSubstitute zope.app.zapi by direct calls to its wrapped apis. See bug
219302.3.4.5 (unreleased)This was skipped over by accident.3.4.4 (2007-10-23)Fix deprecation warning.3.4.3 (2007-10-23)Fix imports in tests.Clean up long lines.3.4.2 (2007-9-26)Release to fix packaging issues with 3.4.1.3.4.1 (2007-9-25)Added missing Changes.txt and README.txt files to egg3.4.0 (2007-9-25)Initial documented releaseMove ZopeMessageFactory to zope.i18nmessageid |
zope.app.i18nfile | This package provides an extension to the File and Image content components
for Zope 3, allowing the content to be localized.Detailed DcoumentationI18nFile testsFirst, let’s create an I18nFile instance:>>> print http(r"""
... POST /@@contents.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, form={"type_name": "BrowserAdd__zope.app.i18nfile.i18nfile.I18nFile",
... "new_value": "i18nfile"})
HTTP/1.1 303 See Other
...Then add some sample data for default (en) language:>>> print http(r"""
... POST /i18nfile/edit.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, form={"contentType": "text/plain",
... "defaultLanguage": "en",
... "language": "en",
... "newLanguage": "",
... "data": "English",
... "edit": "Save"})
HTTP/1.1 303 See Other
...Ok, now we can view the data in the edit form:>>> print http(r"""
... GET /i18nfile/editForm.html?language=en HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
HTTP/1.1 200 OK
...
<textarea ...>English</textarea>
...and as file content:>>> print http(r"""
... GET /i18nfile/index.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
HTTP/1.1 200 OK
...
EnglishLet’s add new (russian) language:>>> print http(r"""
... POST /i18nfile/edit.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, form={"contentType": "text/plain",
... "defaultLanguage": "en",
... "language": "en",
... "addLanguage": "Add new language",
... "newLanguage": "ru",
... "data": "English"})
HTTP/1.1 303 See Other
...and add some sample data for russian (ru) language:>>> print http(r"""
... POST /i18nfile/edit.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, form={"contentType": "text/plain",
... "defaultLanguage": "en",
... "language": "ru",
... "newLanguage": "",
... "data": "Russian",
... "edit": "Save"})
HTTP/1.1 303 See Other
...Then we can view sample data for russain language in the edit form:>>> print http(r"""
... GET /i18nfile/editForm.html?language=ru HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
HTTP/1.1 200 OK
...
<textarea ...>Russian</textarea>
...and if our preferred language is russian as file content:>>> print http(r"""
... GET /i18nfile/index.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Accept-Language: ru,en
... """)
HTTP/1.1 200 OK
...
RussianI18nImage testsFirst, let’s create an I18nImage instance:>>> print http(r"""
... POST /@@contents.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, form={
... "type_name": "BrowserAdd__zope.app.i18nfile.i18nimage.I18nImage",
... "new_value": "i18nimage"})
HTTP/1.1 303 See Other
...Then add some sample image data for default (en) language:>>> print http(r"""
... POST /i18nimage/uploadAction.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, form={"contentType": "image/gif",
... "defaultLanguage": "en",
... "language": "en",
... "newLanguage": "",
... "data": 'GIF89aENEN',
... "edit": "Save"})
HTTP/1.1 303 See Other
...Ok, now we can view the image size in the edit form:>>> print http(r"""
... GET /i18nimage/upload.html?language=en HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
HTTP/1.1 200 OK
...
...>1 KB 20037x20037</...
...and the image data as file content:>>> print http(r"""
... GET /i18nimage/ HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
HTTP/1.1 200 OK
Content-Length: 10
Content-Type: image/gif
<BLANKLINE>
GIF89aENENLet’s add new (russian) language:>>> print http(r"""
... POST /i18nimage/uploadAction.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, form={"contentType": "image/gif",
... "defaultLanguage": "en",
... "language": "en",
... "addLanguage": "Add new language",
... "newLanguage": "ru",
... "data": ""})
HTTP/1.1 303 See Other
...and add some sample image data for russian (ru) language:>>> print http(r"""
... POST /i18nimage/uploadAction.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """, form={"contentType": "image/gif",
... "defaultLanguage": "en",
... "language": "ru",
... "newLanguage": "",
... "data": "GIF89aRURU",
... "edit": "Save"})
HTTP/1.1 303 See Other
...Then we can view the size of sample image for russain language in
the edit form:>>> print http(r"""
... GET /i18nimage/upload.html?language=ru HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """)
HTTP/1.1 200 OK
...
...>1 KB 21842x21842</...
...and if our preferred language is russian we can view the image as file content:>>> print http(r"""
... GET /i18nimage/ HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Accept-Language: ru,en
... """)
HTTP/1.1 200 OK
Content-Length: 10
Content-Type: image/gif
<BLANKLINE>
GIF89aRURUCHANGES3.4.1 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.interface | This package provides several extensions to Zope interfaces, such as a
persistent implementation, interface type queries, and a vocabulary of all
registered interfaces of the system (or of a particular type).CHANGES3.6.0 (2010-09-20)Added test extra to declare test dependency onzope.testing.Movedzope.app.interfaces.queryTypetozope.app.contentto inverse
dependency, leaving BBB import here.3.5.2 (2010-07-08)3.5.1 was a bad release3.5.1 (2010-07-07)Fixed tests and test tearDown to actually close the DB.3.5.0 (2009-05-21)Factor out ObjectInterfacesVocabulary intozope.componentvocabulary.Remove various test dependencies.3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.interpreter | Integration of the safe Python interpreter in Zope 3.CHANGES3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.intid | This package provides browser views for adding and managing integer id
utility, provided by thezope.intidpackage.CHANGES3.7.1 (2010-01-10)Fix ftesting.zcml due to the zope.securitypolicy update.Removed unneeded dependency on zope.app.publisher, added the missing one on
zope.security.Added test dependency on zope.login.3.7.0 (2009-02-01)Move core functionality to newzope.intidpackage, leaving only
ZMI-related browser views here.Note, that if you used theexcludedirective fromzc.configurationpackage to exclude thesubscribers.zcmlfile fromzope.app.intid,
you need to change the directive to exclude it fromzope.intidnow.3.6.0 (2009-01-31)Changed dependency fromzope.app.containertozope.container.Move test dependencieszope.app.folderandzope.app.componentaszope.site.3.5.1 (2008-12-11)Make it possible to subscribe object-specific handlers
for IntIdAddedEvent/IntIdRemovedEvent. Use them like
the zope.app.container.interfaces.IObjectAddedEvent.Include utility->id mapping of added ids to the
IntIdAddedEvent.Removed testing dependencies from install_requires.3.5.0 (2008-06-19)Separate subscriber configuration into a separate ZCML file.3.4.1 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.keyreference | This package used to provide object references with support for support
stable comparison and hashes. But all functionality was moved to thezope.keyreferencepackage. This package now only provides
backward-compatibility imports for objects defined inzope.keyreference.CHANGES3.6.1 (2010-03-07)Adapted tests for Python 2.4Added license file3.6.0 (2009-01-39)Move all functionality to newzope.keyreferencepackage. This
package only provides backward-compatibility imports now.3.5.0b2 (unknown)Performance related change to the conflict resolution code inzope.app.keyreference.persistent.KeyReferenceToPersistent.__cmp__.Added support for newZODB.ConflictResolution.PersistentReferencebehavior
to persistent key references so that they can now, in many cases, allow
conflict resolution when they are used as keys or set members in ZODBBTreesdata structures.Move zope.testing to the “test” extra require, because it’s only needed for testing.3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.layers | A meta-package in which generated layer interfaces are placed.CHANGES3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.applicationcontrol | zope.applicationcontrolThe application control instance can be generated upon startup of an
application built with the Zope Toolkit.This package provides an API to retrieve runtime information. It also
provides a utility with methods for shutting down and restarting the
server.Changes5.0 (2023-07-06)Add support for Python 3.11.Drop support for Python 2.7, 3.5, 3.6.4.3 (2022-06-24)Drop support for Python 3.4.Add support for Python 3.8, 3.9, 3.10.4.2.0 (2018-10-19)Drop support forsetup.py test.Drop support for Python 3.3.Add support for Python 3.7.4.1.0 (2017-05-03)Add support for Python 3.5 and 3.6.Drop support for Python 3.2 and 2.6.4.0.1 (2015-06-05)Add support for Python 3.2 and PyPy3.4.0.0 (2014-12-24)Add support for PyPy. (PyPy3 is pending release of a fix for:https://bitbucket.org/pypy/pypy/issue/1946)Add support for Python 3.4.Add support for testing on Travis.4.0.0a1 (2013-02-22)Add support for Python 3.3.Replace deprecatedzope.interface.implementsusage with equivalentzope.interface.implementerdecorator.Drop support for Python 2.4 and 2.5.3.5.5 (2010-01-09)Initial release, extracted fromzope.app.applicationcontrol. |
zope.app.locales | zope.app.localesThis package provides some facilities for extracting and managing i18n
messages that occur in Zope software. More specifically, i18n
messages can occur in Python code, in Page Templates and in ZCML
declarations.zope.app.localesprovides a utility that can
extract messages from all three and write them to a standard gettext
template (potfile).UsageVersion 4.2 does not contain any*.mofiles. They are the compiled
translation files (*.po). (Future versions will contain them again.)To generate or update*.mofiles on the fly set the following environment
variable:zope_i18n_compile_mo_files=TrueTo restrict the allowed languages setzope_i18n_allowed_languagesto a list
of languages. Example:zope_i18n_allowed_languages=de,en,es,frDetailed DocumentationInternationalization (I18n) and Localization (L10n)This document assumes that you have a Zope 3 checkout and the gettext
utilities installed.Creating/Updating Message Catalog Template (POT) FilesWhenever you’ve made a change to Zope that affects the i18n messages,
you need to re-extract i18n messages from the code. To do that,
executei18nextract.pyfrom theutilitiesdirectory of your
Zope 3 checkout:$ python utilities/i18nextract.py -d zope -p src/zope -o app/localesThis will update thezope.potfile. Make sure that the checkout’ssrcdirectory is part of yourPYTHONPATHenvironment variable.After that, you need to merge those changes to all existing
translations. You can do that by executing thei18nmergeall.pyscript from theutilitiesdirectory of your Zope 3 checkout:$ python utilities/i18nmergeall.py -l src/zope/app/localesTranslatingTo translate messages you need to do the following steps:If a translation for your language is already present and you just
want to update, skip ahead to step 2. If you want to start
translation on a new language, you need tocreate a directorysrc/zope/app/locales/<lang_code>/LC_MESSAGESwith the appropriate code for your language as <lang_code>.
Note that the two letters specifying the language should always
be lower case (e.g. ‘pt’); if you additionally specify a region,
those letters should be upper case (e.g. ‘pt_BR’).copy thezope.pottemplate file to<lang_code>/LC_MESSAGES/zope.po.edit the PO header of the newly createdzope.pofile and
fill in all the necessary information.Translate messages within the PO file. Make sure the gettext
syntax stays intact. Tools like poEdit and KBabel can help you.Finally, when you’re done translating, compile the PO file to its
binary equivalent using themsgfmttool:$ cd <lang_code>/LC_MESSAGES
$ msgfmt -o zope.mo zope.poCHANGES5.0 (2023-08-28)Add support for Python 3.11.Drop support for Python 2.7, 3.5, 3.6.4.3 (2022-09-12)Remove*.mofiles from the repository and document in the README how to
generate them on the fly.
(#7)Automatically create*.mofiles during the release process so this
release will again contain*.mofiles.4.2 (2022-06-10)Add support for Python 3.9, 3.10.Make path in ZCML extraction relative.This release does not contain any*.mofiles.4.1 (2019-06-24)Flake8 the code.Add support for Python 3.7, 3.8b1 and PyPy3.Port usage of custom POT file header template here fromz3c.recipe.i18n.
(#11)Prevent POT files from collecting duplicate location specifiers over time.
(#12)4.0.1 (2018-06-29)Recompile the*.motranslation files.4.0.0 (2017-05-02)Add support for Python 3.5 and 3.6 and PyPy.3.7.5 (2016-03-28)Add a test for the zcml_extraction.Remove zope.app.applicationcontrol and zope.app.appsetup dependencies.Add list of supported Python versions to Trove classifiers.3.7.4 (2012-05-14)In version 3.7.2 msgids and default values were forced to beunicode. This was too strict because at least the TAL extractor returns
UTF-8 encoded default values. Fixed this by allowing the default value to
be a string again.3.7.3 (2012-01-06)i18nextract bugfix: _(“msgid”, mapping={…}) does not have a default, just
like _(“msgid”). Previously it would get a#. Default: ""annotation in
the .pot file.3.7.2 (2011-12-12)Handle Unicode msgids and default values.Consistent sorting of source filenames for each msgid. Also sort line
numbers numerically, not lexicographically.3.7.1 (2011-12-07)Fix nl translations.Updated Brazilian Portuguese translation [erico_andrei]3.7.0 (2011-03-02)Include zcml dependencies inconfigure.zcml, require the necessary
packages via azcmlextra, added tests for zcml.Using Python’sdoctestmodule instead of depreactedzope.testing.doctest.3.6.2 (2010-07-31)Updated copyright toZope Foundation, even in pot template.Updated e-mail address in pot template to current address of zope
mailing list.Added missing test dependency onzope.i18n.3.6.1 (2010-05-17)Updated Dutch and German translations.3.6.0 (2009-12-28)Addedconfigure.zcmlwhich registers the translations in the
package. So the package contains its configuration. (Till now it was
done inzope.app.zcmlfiles.)3.5.2 (2009-12-22)Updated tests to handle Unicode correctly.Update Japanese Translation (thanks Takeshi Yamamoto).3.5.1 (2009-01-27)Added missing dependency (zope.tal) for tests.3.5.0 (2009-01-26)Moved the dependencies of the extract console script into anextractextras_require to avoid runtime dependencies.Fixed bug #227582 (bad size in zh_CN locale)3.4.5 (2008-07-16)added filePattern parameter for tal_strings to be able to not only parse.ptfiles.Updated Dutch translation3.4.4 (2008-03-05)Updated Spanish translation3.4.3 (2008-02-20)Updated Spanish translationUpdated Japanese translation3.4.2 (2008-02-06)Fixed and updated Russian translation. Fixed issue #186628 (Typos and errors
in russian translation)3.4.1 (2007-12-12)Fixed and updated the french translation3.4.0 (2007-10-25)Folded the i18nextract script intozope.app.locales.extractand
exposed it as a console script entry point.3.4.0a1 (2007-04-22)Initial release as a separate project, corresponds tozope.app.localesfrom Zope 3.4.0a1 |
zope.app.localpermission | This package implements local persistent permissions for zope.security that
can be added and registered per site.This is a part of “Through The Web” development pattern that is not used
much by zope community and not really supported in zope framework anymore
nowadays, so it can be considered as deprecated.CHANGES5.0 (2023-02-08)Drop support for Python 2.7, 3.4, 3.5, 3.6.Add support for Python 3.8, 3.9, 3.10, 3.11.4.1.0 (2018-10-19)Add support for Python 3.7.4.0.0 (2017-04-23)Add support for PyPy.Add support for Python 3.4, 3.5, and 3.6.Remove dependency on ZODB3. Instead, depend on the separatepersistentpackage.3.7.2 (2010-03-21)Added missing i18n domain tobrowser.zcml.3.7.1 (2010-02-22)The zope.app namespace wasn’t declared correctly.3.7.0 (2009-03-14)Initial release. This package was extracted from zope.app.security to separate
the functionality without additional dependencies. |
zope.app.locking | This package provides a framework for object locking. The implementation
is intended to provide a simple general-purpose locking architecture upon
which other locking applications can be built (WebDAV locking, for example).Detailed DcoumentationObject LockingThis package provides a framework for object locking. The implementation
is intended to provide a simple general-purpose locking architecture upon
which other locking applications can be built (WebDAV locking, for example).The locking system is purelyadvisory- it provides a way to associate a
lock with an object, but it does not enforce locking in any way. It is up
to application-level code to ensure that locked objects are restricted in
a way appropriate to the application.The Zope 3 locking model defines interfaces and a default implementation
that:allows for a single lock on an object, owned by a specific principaldoes not necessarily impose inherent semantic meaning (exclusive
vs. non-exclusive, write vs. read) on locks, though it will
provide fields that higher-level application components can use
to implement and enforce such semanticscan potentially be used to build more ambitious locking
mechanisms (such as WebDAV locking equivalent to Zope 2)supports common use cases that have been uncovered in several years
of development of real-world applications (such as reporting all of
the objects locked by a given user)The Zope3 locking architecture defines anILockableinterface and
provides a default adapter implementation that requires only that an
object be adaptable toIKeyReference. All persistent objects can be
adapted to this interface by default in Zope 3, so in practice all
persistent objects are lockable.The defaultILockableadapter implementation provides support for:locking and unlocking an objectbreaking an existing lock on an objectobtaining the lock information for an objectLocking operations (lock, unlock, break lock) fire events that may be
handled by applications or other components to interact with the locking
system in a loosely-coupled way.Lock information is accessible through an object that supports theILockInfointerface. TheILockInfointerface impliesIAnnotatable,
so that other locking implementations (superseding or complementing the
default implementation) can store more information if needed to support
extended locking semantics.The locking architecture also supports an efficient method of lock tracking
that allows you to determine what locks are held on objects. The default
implementation provides anILockTrackerutility that can be used by
applications to quickly find all objects locked by a particular principal.Locking essentialsNormally, locking is provided by the default locking implementation. In
this example, we’ll create a simple content class. The content class
is persistent, which allows us to use the default locking adapters and
utilities.>>> import persistent>>> class Content(persistent.Persistent):
... """A sample content object"""
...
... def __init__(self, value):
... self.value = value
...
... def __call__(self):
... return self
...
... def __hash__(self):
... return self.value
...
... def __cmp__(self, other):
... return cmp(self.value, other.value)Now we will create a few sample objects to work with:>>> item1 = Content("item1")
>>> item1.__name__ = "item1">>> item2 = Content("item2")
>>> item2.__name__ = "item2">>> item3 = Content("item3")
>>> item3.__name__ = "item3"It is possible to test whether an object supports locking by attempting
to adapt it to the ILockable interface:>>> from zope.app.locking.interfaces import ILockable
>>> from zope.app.locking.interfaces import ILockInfo>>> ILockable(item1, None)
<Locking adapter for...>>> ILockable(42, None)There must be an active interaction to use locking, to allow the framework
to determine the principal performing locking operations. This example sets
up some sample principals and a helper to switch principals for further
examples:>>> class FauxPrincipal:
... def __init__(self, id):
... self.id = id>>> britney = FauxPrincipal('britney')
>>> tim = FauxPrincipal('tim')>>> class FauxParticipation:
... interaction = None
... def __init__(self, principal):
... self.principal = principal>>> import zope.security.management
>>> def set_principal(principal):
... if zope.security.management.queryInteraction():
... zope.security.management.endInteraction()
... participation = FauxParticipation(principal)
... zope.security.management.newInteraction(participation)>>> set_principal(britney)Now, let’s look at basic locking. To perform locking operations, we first
have to adapt an object toILockable:>>> obj = ILockable(item1)
>>> from zope.interface.verify import verifyObject
>>> verifyObject(ILockable, obj)
TrueWe can ask if the object is locked:>>> obj.locked()
FalseIf it were locked, we could get the id of the principal that owns the
lock. Since it is not locked, this will returnNone:>>> obj.locker()Now let’s lock the object. Note that the lock method return an instance
of an object that implementsILockInfoon success:>>> info = obj.lock()
>>> verifyObject(ILockInfo, info)
True>>> obj.locked()
True>>> obj.locker()
'britney'Methods are provided to check whether the current principal already has
the lock on an object and whether the lock is already owned by a different
principal:>>> obj.ownLock()
True>>> obj.isLockedOut()
FalseIf we switch principals, we see that the answers reflect the current
principal:>>> set_principal(tim)
>>> obj.ownLock()
False>>> obj.isLockedOut()
TrueA principal can only release his or her own locks:>>> obj.unlock()
Traceback (most recent call last):
...
LockingError: Principal is not lock ownerIf we switch back to the original principal, we see that the original
principal can unlock the object:>>> set_principal(britney)
>>> obj.unlock()There is a mechanism for breaking locks that does not take the current
principal into account. This will break any existing lock on an object:>>> obj.lock()
<...LockInfo...>>>> set_principal(tim)
>>> obj.locked()
True>>> obj.breaklock()
>>> obj.locked()
FalseLocks can be created with an optional timeout. If a timeout is provided,
it should be an integer number of seconds from the time the lock is
created.>>> # fake time function to avoid a time.sleep in tests!
>>> import time
>>> def faketime():
... return time.time() + 3600.0>>> obj.lock(timeout=10)
<...LockInfo...>>>> obj.locked()
True>>> import zope.app.locking.storage
>>> zope.app.locking.storage.timefunc = faketime
>>> obj.locked()
False(Note that we undo our time hack in the tearDown of this module.)Finally, it is possible to explicitly get anILockInfoobject that
contains the lock information for the object. Note that locks that do
not have a timeout set have a timeout value ofNone.>>> obj = ILockable(item2)
>>> obj.lock()
<...LockInfo...>>>> info = obj.getLockInfo()
>>> info.principal_id
'tim'
>>> info.timeoutIt is possible to get the object associated with a lock directly from
anILockInfoinstance:>>> target = info.target
>>> target.__name__ == 'item2'
TrueTheILockInfointerface extends the IMapping interface, so application
code can store extra information on locks if necessary. It is recommended
that keys for extra data use qualified names following the convention that
is commonly used for annotations:>>> info['my.namespace.extra'] = 'spam'
>>> info['my.namespace.extra']
'spam'
>>> obj.unlock()
>>> obj.locked()
FalseLock trackingIt is often desirable to be able to report on the currently held locks in
a system (particularly on a per-user basis), without requiring an expensive
brute-force search. AnILockTrackerutility allows an application to get
the current locks for a principal, or all current locks:>>> set_principal(tim)
>>> obj = ILockable(item2)
>>> obj.lock()
<...LockInfo...>>>> set_principal(britney)
>>> obj = ILockable(item3)
>>> obj.lock()
<...LockInfo...>>>> from zope.app.locking.interfaces import ILockTracker
>>> from zope.component import getUtility
>>> util = getUtility(ILockTracker)
>>> verifyObject(ILockTracker, util)
True>>> items = util.getLocksForPrincipal('britney')
>>> len(items) == 1
True>>> items = util.getAllLocks()
>>> len(items) >= 2
TrueThese methods allow an application to create forms and other code that
performs unlocking or breaking of locks on sets of objects:>>> items = util.getAllLocks()
>>> for item in items:
... obj = ILockable(item.target)
... obj.breaklock()>>> items = util.getAllLocks()
>>> len(items)
0The lock storage utility provides further capabilities, and is a part of the
standard lock adapter implementation, but the ILockable interface does not
depend on ILockStorage. Other implementations of ILockable may not use
ILockStorage. However, if used by the adapter, it provides useful
capabilties.>>> from zope.app.locking.interfaces import ILockStorage
>>> util = getUtility(ILockStorage)
>>> verifyObject(ILockStorage, util)
TrueLocking eventsLocking operations (lock, unlock, break lock) fire events that can be used
by applications. Note that expiration of a lockdoes notfire an event
(because the current implementation uses a lazy expiration approach).>>> import zope.event>>> def log_event(event):
... print event>>> zope.event.subscribers.append(log_event)>>> obj = ILockable(item2)
>>> obj.lock()
LockedEvent ...>>> obj.unlock()
UnlockedEvent ...>>> obj.lock()
LockedEvent ...>>> obj.breaklock()
BreakLockEvent ...TALES conditions based on lockingTALES expressions can use a named path adapter to get information
about the lock status for an object, including whether or not the
object can be locked. The default registration for this adapter uses
the name “locking”, so a condition might be expressed like
“context/locking:ownLock”, for example.For objects that aren’t lockable, the adapter provides information
that makes sense:>>> from zope.component import getAdapter
>>> from zope.traversing.interfaces import IPathAdapter
>>> ns = getAdapter(42, IPathAdapter, "locking")
>>> ns.lockable
False
>>> ns.locked
False
>>> ns.lockedOut
False
>>> ns.ownLock
FalseUsing an object that’s lockable, but unlocked, also gives the expected
results:>>> ns = getAdapter(item1, IPathAdapter, "locking")
>>> ns.lockable
True
>>> ns.locked
False
>>> ns.lockedOut
False
>>> ns.ownLock
FalseIf we lock the object, the adapter indicates that the object is locked
and that we own it:>>> ob = ILockable(item1)
>>> ob.lock()
LockedEvent for ...
>>> ns.lockable
True
>>> ns.locked
True
>>> ns.lockedOut
False
>>> ns.ownLock
TrueCHANGES3.5.0 (2009-02-01)Usezope.siteinstead ofzope.app.folderin test.Remove usage of deprecatedzope.app.zapi.3.4.0 (2007-10-25)Initial release independent of the main Zope tree. |
zope.app.module | Persistent Python modules allow us to develop and store Python modules in the
ZODB in contrast to storing them on the filesystem. You might want to look at
thezodbcodepackage for the details of the implementation. In Zope 3 we
implemented persistent modules as utilities. These utilities are known as
module managers that manage the source code, compiled module and name of the
module. We then provide a special module registry that looks up the utilities
to find modules.Detailed DocumentationPersistent Python ModulesPersistent Python modules allow us to develop and store Python modules in the
ZODB in contrast to storing them on the filesystem. You might want to look at
thezodbcodepackage for the details of the implementation. In Zope 3 we
implemented persistent modules as utilities. These utilities are known as
module managers that manage the source code, compiled module and name of the
module. We then provide a special module registry that looks up the utilities
to find modules.The Module ManagerOne can simply create a new module manager by instantiating it:>>> from zope.app.module.manager import ModuleManager
>>> manager = ModuleManager()If I create the manager without an argument, there is no source code:>>> manager.source
''When we add some code>>> manager.source = """\n
... foo = 1
... def bar(): return foo
... class Blah(object):
... def __init__(self, id): self.id = id
... def __repr__(self): return 'Blah(id=%s)' % self.id
... """we can get the compiled module and use the created objects:>>> module = manager.getModule()
>>> module.foo
1
>>> module.bar()
1
>>> module.Blah('blah')
Blah(id=blah)We can also ask for the name of the module:>>> manager.name
>>> module.__name__But why is itNone? Because we have no registered it yet. Once we register
and activate the registration a name will be set:>>> from zope.app.testing import setup
>>> root = setup.buildSampleFolderTree()
>>> root_sm = setup.createSiteManager(root)>>> from zope.app.module import interfaces
>>> manager = setup.addUtility(root_sm, 'mymodule',
... interfaces.IModuleManager, manager)>>> manager.name
'mymodule'>>> manager.getModule().__name__
'mymodule'Next, let’s ensure that the module’s persistence works correctly. To do that
let’s create a database and add the root folder to it:>>> from ZODB.tests.util import DB
>>> db = DB()
>>> conn = db.open()
>>> conn.root()['Application'] = root>>> import transaction
>>> transaction.commit()Let’s now reopen the database to test that the module can be seen from a
different connection.>>> conn2 = db.open()
>>> root2 = conn2.root()['Application']
>>> module2 = root2.getSiteManager().queryUtility(
... interfaces.IModuleManager, 'mymodule').getModule()
>>> module2.foo
1
>>> module2.bar()
1
>>> module2.Blah('blah')
Blah(id=blah)Module Lookup APIThe way the persistent module framework hooks into Python is via module
registires that behave pretty much likesys.modules. Zope 3 provides its own
module registry that uses the registered utilities to look up modules:>>> from zope.app.module import ZopeModuleRegistry
>>> ZopeModuleRegistry.findModule('mymodule')But why did we not get the module back? Because we have not set the site yet:>>> from zope.app.component import hooks
>>> hooks.setSite(root)Now it will find the module and we can retrieve a list of all persistent
module names:>>> ZopeModuleRegistry.findModule('mymodule') is module
True
>>> ZopeModuleRegistry.modules()
[u'mymodule']Additionally, the package provides two API functions that look up a module in
the registry and then insys.modules:>>> import zope.app.module
>>> zope.app.module.findModule('mymodule') is module
True
>>> zope.app.module.findModule('zope.app.module') is zope.app.module
TrueThe second function can be used to lookup objects inside any module:>>> zope.app.module.resolve('mymodule.foo')
1
>>> zope.app.module.resolve('zope.app.module.foo.resolve')In order to use this framework in real Python code import statements, we need
to install the importer hook, which is commonly done with an event subscriber:>>> import __builtin__
>>> event = object()
>>> zope.app.module.installPersistentModuleImporter(event)
>>> __builtin__.__import__ # doctest: +ELLIPSIS
<bound method ZopePersistentModuleImporter.__import__ of ...>Now we can simply import the persistent module:>>> import mymodule
>>> mymodule.Blah('my id')
Blah(id=my id)Finally, we unregister the hook again:>>> zope.app.module.uninstallPersistentModuleImporter(event)
>>> __builtin__.__import__
<built-in function __import__>Persistent Interfaceszope.app.module’s ModuleManagers behave a little differently when
interfaces are involved:>>> from zope.app.module.manager import ModuleManager
>>> manager = ModuleManager()
>>> source = """\n
... from zope.interface import Interface
... class IFoo(Interface): pass
... class IBar(IFoo): pass
... """
>>> manager.source = sourceA ModuleManager doesn’t get a name until it’s registered and the
zodbcode wrappers break without a name, so we can’t retrieve our
module until our manager is registered:>>> from zope.app.testing import setup
>>> from zope.app.module import interfaces
>>> root = setup.buildSampleFolderTree()
>>> root_sm = setup.createSiteManager(root)
>>> manager = setup.addUtility(root_sm, u'foo',
... interfaces.IModuleManager, manager)Now we can compile a module with interfaces and access everything
appropriately:>>> module = manager.getModule()
>>> module
<PersistentModule foo>
>>> module.IFoo
<PersistentInterfaceClass foo.IFoo>
>>> module.IBar
<PersistentInterfaceClass foo.IBar>CHANGES3.5.0 (2009-02-01)Use zope.container instead of zope.app.container.3.4.0 (2007-10-25)Initial release independent of the main Zope tree. |
zope.app.onlinehelp | This package provides a framework for creating help pages for Zope 3
applications. ZCML directives are used to minimize the overhead of creating
new help pages.Documentation is hosted athttps://zopeapponlinehelp.readthedocs.ioCHANGES5.0 (2023-07-06)Add support for Python 3.11.Drop support for Python 2.7, 3.5, 3.6.4.2.0 (2022-04-05)Add support for Python 3.7, 3.8, 3.9, and 3.10.Drop support for Python 3.4.4.1.0 (2017-07-12)The help namespace no longer modifies the global help object on
traversal. Instead it returns a new proxy object. This makes it
thread-safe. Seeissue 4.getTopicFornow really returns the first found topic in the
event that the object implements multiple interfaces that have
registered topics for the given view. Previously it would return the
topic for the least-specific interface.4.0.1 (2017-05-21)Drop test dependency onzope.app.securitypolicy. It wasn’t used,
and it isn’t yet fully ported to Python 3.4.0.0 (2017-05-17)Add support for Python 3.4, 3.5, 3.6 and PyPy.Change ZODB dependency to persistent.Drop test dependency onzope.app.testing,zope.app.zcmlifilesandzope.app.apidoc, among others.3.5.2 (2010-01-08)Fix tests using a newer zope.publisher that requires zope.login.3.5.1 (2009-03-21)Usezope.siteinstead ofzope.app.folder.3.5.0 (2009-02-01)RemovedOnlineHelpTopicFactory,simpleandSimpleViewClass. All of them where using old deprecated and
removed Zope3 imports. None of them where used and tested.Usezope.containerinstead ofzope.app.container.Removed use ofzope.app.zapi.3.4.1 (2007-10-25)Package meta-data update.3.4.0 (2007-10-23)Initial release independent of the main Zope tree.OlderMake the onlinehelp utility more component oriented.Use registred page/view instead of ViewPageTemplate for rendering topic tree
This way we can use/register own templates for tree layout.Add page template based topic for rendering topics which has to
call other zope3 resources like javascripts and css styles sheets etc.
This resources can be rendered in the header area of the onlinehelp_macros.Enhance the API of topics and simplyfie the view part.Implemented getSubTopics() method on topics. This way we can sublist topics.Remove unused onlinehelp code in rotterdam template.ptAdd type to directive, this supports registration of README.txt as ‘rest’ topics |
zope.app.pagetemplate | Thezope.app.pagetemplatepackage integrates the Page Template
templating system (zope.pagetemplate) into the Zope 3 application
server. In particular, it provides:a TALES engine implementation that uses Zope’s security system for
checking access,TALES namespace adapters for easy access to DublinCore metadata
(e.g.obj/zope:title) and URL quoting
(e.g.obj/@@absolute_url/url:quote).ContentsChanges5.0 (2023-02-07)4.0.0 (2017-04-22)3.11.2 (2010-09-25)3.11.1 (2010-09-01)3.11.0 (2010-04-26)3.10.1 (2010-01-04)3.10.0 (2009-12-22)3.9.0 (2009-12-22)3.8.0 (2009-12-16)3.7.1 (2009-05-27)3.7.0 (2009-05-25)3.6.0 (2009-05-18)3.5.0 (2009-02-01)3.4.1 (2008-07-30)3.4.0 (2007-09-28)Changes5.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-04-22)Add support for Python 3 and PyPy.Do not explicitly requirezope.security [untrustedpython]. Olderzope.pagetemplateversions require it, newer ones do not.3.11.2 (2010-09-25)Declared test dependency onzope.component [test]as it is needed to
run the tests.3.11.1 (2010-09-01)Added metaconfigure.registerType BBB import because some packages use it.Using doctest from standard library instead ofzope.testing.doctest.3.11.0 (2010-04-26)Moved tales:expressiontype directive down into zope.browserpage.3.10.1 (2010-01-04)Fixed thezope.browserpageimports in thenamedtemplatemodule.3.10.0 (2009-12-22)Moved named template implementation to zope.browserpage.3.9.0 (2009-12-22)Moved viewpagetemplatefile, simpleviewclass and metaconfigure.registerType
into the zope.browserpage package, reversing the dependency.3.8.0 (2009-12-16)Refactored nested macro test from a functional test into a unit test. This
allowed to remove the last outside zope.app dependencies.Fixed undeclared testing dependency on zope.app.component.Copy trivial NoTraverser class from zope.app.publication to avoid a ZCML
dependency on that package.Correct testing dependency to point to zope.securitypolicy instead of its
zope.app variant. The app version is no longer required since 3.4.1.Removed theinline-evaluationextra referring to zope.app.interpreter.
There’s no code or ZCML left pointing to that package.3.7.1 (2009-05-27)Restoredzope.app.pagetemplate.enginemodule, using BBB imports fromzope.pagetemplate.engine.3.7.0 (2009-05-25)Moved theenginemodule and associated testing machinery tozope.pagetemplate(version 3.5.0).3.6.0 (2009-05-18)Movednamedtemplate.*fromzope.formlibhere as it is more
about a page template engine than a formular library. This also
breaks some dependencies onzope.formlib.Added doctests to long_description to show up on pypi.3.5.0 (2009-02-01)Usezope.containerinstead ofzope.app.container.3.4.1 (2008-07-30)Substitute zope.app.zapi by direct calls to its wrapped apis.
Seehttp://launchpad.net/bugs/219302Fix deprecation warning in ftesting.zcml: ZopeSecurityPolicy now lives in
zope.securitypolicy.3.4.0 (2007-09-28)Initial release as standalone package.Dependency on zope.app.interpreter moved to an extra
[inline-evaluation]. It is only needed by zope.app.pythonpage,
which is an oddity. |
zope.app.pluggableauth | This package provides the original implementation of the pluggable
authentication utility. It has been superceded byzope.app.authentication.Detailed DcoumentationNew Authentication Service DesignThe current implementation will be replaced. The following is a design
I came up with together with Jim Fulton.
– itamarNote that this design is implemented (in some form) by the pluggable
auth service. This document needs to be updated to reflect the final
implementation.Design notes for new AuthenticationServiceThe service contains a list of user sources. They implement interfaces,
starting with:class IUserPassUserSource:
"""Authenticate using username and password."""
def authenticate(username, password):
"Returns boolean saying if such username/password pair exists"
class IDigestSupportingUserSource(IUserPassUserSource):
"""Allow fetching password, which is required by digest auth methods"""
def getPassword(username):
"Return password for username"etc. Probably there will be others as well, for dealing with certificate
authentication and what not. Probably we need to expand above interfaces
to deal with principal titles and descriptions, and so on.A login method (cookie auth, HTTP basic auth, digest auth, FTP auth),
is registered as a view on one of the above interfaces.class ILoginMethodView:
def authenticate():
"""Return principal for request, or None."""
def unauthorized():
"""Tell request that a login is required."""The authentication service is then implemented something like this:class AuthenticationService:
def authenticate(self, request):
for us in self.userSources:
loginView = getView(self, us, "login", request)
principal = loginView.authenticate()
if principal is not None:
return principal
def unauthorized(self, request):
loginView = getView(self, self.userSources[0], request)
loginView.unauthorized()CHANGES3.4.0 (2007-10-25)Initial release independent of the main Zope tree. |
zope.app.preference | This package provides a UI to maintain hierarchical user preferences
in the ZMI.Contentszope.app.preferenceSet upEditing PreferencesPreference Group TreesCHANGES4.1.0 (2022-08-05)4.0.0 (2017-05-17)3.8.1 (2010-06-15)3.8.0 (2010-06-12)3.7.0 (2010-06-11)3.6.0 (2009-02-01)3.5.0 (2009-01-17)3.4.1 (2007-10-30)3.4.0 (2007-10-25)zope.app.preferenceThis package provides a user interface in the ZMI, so the user can edit
the preferences.Set upTo show the user interface functions we need some setup beforehand:>>> from zope.testbrowser.wsgi import Browser
>>> browser = Browser()
>>> browser.handleErrors = FalseAs the preferences cannot be defined through the web we have to define
them in python code:>>> import zope.interface
>>> import zope.schema
>>> class IZMIUserSettings(zope.interface.Interface):
... """Basic User Preferences"""
...
... email = zope.schema.TextLine(
... title=u"E-mail Address",
... description=u"E-mail Address used to send notifications")
...
... skin = zope.schema.Choice(
... title=u"Skin",
... description=u"The skin that should be used for the ZMI.",
... values=['Rotterdam', 'ZopeTop', 'Basic'],
... default='Rotterdam')
...
... showZopeLogo = zope.schema.Bool(
... title=u"Show Zope Logo",
... description=u"Specifies whether Zope logo should be displayed "
... u"at the top of the screen.",
... default=True)
>>> class INotCategorySettings(zope.interface.Interface):
... """An example that's not a categary"""
... comment = zope.schema.TextLine(
... title=u'A comment',
... description=u'A description')The preference schema is usually registered using a ZCML statement:>>> from zope.configuration import xmlconfig
>>> import zope.preference
>>> context = xmlconfig.file('meta.zcml', zope.preference)>>> context = xmlconfig.string('''
... <configure
... xmlns="http://namespaces.zope.org/zope"
... i18n_domain="test">
...
... <preferenceGroup
... id="ZMISettings"
... title="ZMI Settings"
... schema="zope.app.preference.README.IZMIUserSettings"
... category="true"
... />
...
... <preferenceGroup
... id="NotCategory"
... title="Not Category"
... schema="zope.app.preference.README.INotCategorySettings"
... category="false"
... />
...
... </configure>''', context)Editing PreferencesThe preferences are accessable in the++preferences++namespace:>>> browser.open('http://localhost/++preferences++')The page shows a form which allows editing the preference values:>>> browser.getControl("comment").value = "A comment"
>>> browser.getControl('E-mail').value = '[email protected]'
>>> browser.getControl('Skin').displayOptions
['Rotterdam', 'ZopeTop', 'Basic']
>>> browser.getControl('Skin').displayValue = ['ZopeTop']
>>> browser.getControl('Show Zope Logo').selected
True
>>> browser.getControl('Show Zope Logo').click()After selectingChangethe values get persisted:>>> browser.getControl('Change').click()
>>> browser.url
'http://localhost/++preferences++/@@index.html'
>>> browser.getControl('E-mail').value
'[email protected]'
>>> browser.getControl('Skin').displayValue
['ZopeTop']
>>> browser.getControl('Show Zope Logo').selected
FalseThe preference group is shown in a tree. It has a link to the form:>>> browser.getLink('ZMISettings').click()
>>> browser.url
'http://localhost/++preferences++/ZMISettings/@@index.html'
>>> browser.getControl('E-mail').value
'[email protected]'Preference Group TreesThe preferences would not be very powerful, if you could create a full
preferences. So let’s create a sub-group for our ZMI user settings, where we
can adjust the look and feel of the folder contents view:>>> class IFolderSettings(zope.interface.Interface):
... """Basic Folder Settings"""
...
... shownFields = zope.schema.Set(
... title=u"Shown Fields",
... description=u"Fields shown in the table.",
... value_type=zope.schema.Choice(['name', 'size', 'creator']),
... default=set(['name', 'size']))
...
... sortedBy = zope.schema.Choice(
... title=u"Sorted By",
... description=u"Data field to sort by.",
... values=['name', 'size', 'creator'],
... default='name')And register it:>>> context = xmlconfig.string('''
... <configure
... xmlns="http://namespaces.zope.org/zope"
... i18n_domain="test">
...
... <preferenceGroup
... id="ZMISettings.Folder"
... title="Folder Content View Settings"
... schema="zope.app.preference.README.IFolderSettings"
... />
...
... </configure>''', context)The sub-group is displayed inside the parent group as a form:>>> browser.reload()
>>> browser.getControl('Shown Fields').displayOptions
['name', 'size', 'creator']
>>> browser.getControl('Shown Fields').displayValue
['name', 'size']
>>> browser.getControl('Shown Fields').displayValue = ['size', 'creator']
>>> browser.getControl('Sorted By').displayOptions
['name', 'size', 'creator']
>>> browser.getControl('Sorted By').displayValue = ['creator']SelecingChangepersists these values, too:>>> browser.getControl('Change').click()
>>> browser.getControl('Shown Fields').displayValue
['size', 'creator']
>>> browser.getControl('Sorted By').displayValue
['creator']
>>> browser.open("http://localhost/++preferences++/ZMISettings.Folder/@@index.html")CHANGES4.1.0 (2022-08-05)Add support for Python 3.7, 3.8, 3.9, 3.10.Drop support for Python 3.4.4.0.0 (2017-05-17)Add support for Python 3.4, 3.5, 3.6 and PyPy.Removed test dependency onzope.app.zcmlfilesandzope.app.renderer, among others.zope.app.rendereris still
required at runtime.Broke test dependency onzope.app.testingby usingzope.app.wsgi.testlayer.3.8.1 (2010-06-15)Fixed BBB imports which pointed to a not existingzope.preferencespackage.3.8.0 (2010-06-12)Depend on split outzope.preference.3.7.0 (2010-06-11)Added HTML labels to ZMI forms.Removededit.ptas it seems to be unused.Added tests for the ZMI views.3.6.0 (2009-02-01)Usezope.containerinstead ofzope.app.container.3.5.0 (2009-01-17)Got rid ofzope.app.zapidependency, replacing its uses with direct
imports from original places.Change mailing address from zope3-dev to zope-dev, as the first one
is retired now.Fix tests for python 2.6.Remove zpkg stuff and zcml include files for
old mkzopeinstance-based instances.3.4.1 (2007-10-30)Avoid deprecation warnings forZopeMessageFactory.3.4.0 (2007-10-25)Initial release independent of the main Zope tree. |
zope.app.preview | This package provides a simple page template that is shared among several
other packages. It is used in the Zope 3 ZMI.CHANGES3.4.0 (2007-10-26)Initial release independent of the main Zope tree. |
zope.app.principalannotation | This package used to provide implementation of IAnnotations for zope.security
principal objects, but it’s now moved to thezope.principalannotationpackage. This package only contains a bootstrap subscriber that sets up
the principal annotation utility for the root site and the browser add
menu item for adding the annotation utility through ZMI.CHANGES5.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-01)Add support for Python 3.4, 3.5 and 3.6 and PyPy.3.7.0 (2009-12-26)Depend on newzope.processlifetimeinterfaces instead of using
BBB imports fromzope.app.appsetup.Removed unneeded dependency on zope.app.publisher, added the missing one on
transaction.3.6.1 (2009-03-31)Got rid ofDeprecationWarninginzope.app.appsetup>=
3.10. Ironically older versions now produce aDeprecationWarning.3.6.0 (2009-03-09)Most of functionality is now moved to thezope.principalannotationpackage. This package now only provides the bootstrap subscriber
for thezope3 application serveras well as browser menu item for
adding PrincipalAnnotationUtility using ZMI.3.5.1 (2009-03-06)Make boostrap subscriber called on IDatabaseOpenedWithRootEvent
instead of IDatabaseOpenedEvent, because this can cause bug if
subscriber will be called before root object is created.Use zope.site instead of zope.app.component.3.5.0 (2009-02-01)Move boostrap subscriber to bootstrap.zcml file and browser
menu item definition to browser.zcml file to ease overriding
and excluding configuration.Use zope.container instead of zope.app.container.3.4.0 (2007-10-26)Initial release independent of the main Zope tree. |
zope.app.publication | Publication and traversal components.CHANGES5.0 (2023-02-08)Add support for Python 3.10, 3.11.Drop support for Python 2.7, 3.5, 3.6.4.5 (2020-11-05)Add support for Python 3.8 and 3.9.Update the tests tozope.app.wsgi >= 4.3.4.4 (2020-05-14)Drop support forpython setup.py test.4.3.2 (2019-12-04)Fix deprecation warning in tests.4.3.1 (2019-07-01)Updated expected doc output to match latest library versions (yes, again).Fixed supported Python versions in .travis.yml.Avoid passing unicode text to logging.Logger.warning() on Python 2 (issue 8).4.3.0 (2018-10-09)Drop Python 3.4 support and added 3.7.Updated expected doc output to match latest library versions.Removed all deprecation warnings.4.2.1 (2017-04-17)IncludeMANIFEST.insince it is needed for pip install.4.2.0 (2016-11-23)Update the code to be compatible withtransaction >= 2.0.Update tests to be compatible withZODB >= 5.1, thus requiring at least
this version for the tests.Drop Python 3.3 support.4.1.0 (2016-08-08)Test against released final versions, thus requiringzope.app.http>= 4.0
(test dependency).4.0.0 (2016-08-08)Claim compatibility to Python 3.4 and 3.5 and drop support for Python 2.6.Improve the publication factory lookup by falling back to a more generic
registration if the specific factory chooses not to handle the request after
all.Relax ZODB dependency to allow 3.10dev builds from SVN.Introduce ZopePublication.callErrorView as a possible hook point.3.14.0 (2012-03-09)Replace ZODB.POSException.ConflictError with
transaction.interfaces.TransientError. The latter should be a more generic
signal to retry a transaction/request.
This requires ZODB3 >= 3.10.0 and transaction >= 1.1.0.Get rid of ZODB dependency.3.13.2 (2011-08-04)Add missing test dependency on zope.testing.Remove test dependency on zope.app.exception.3.13.1 (2011-03-14)Test fix: HTTP request should not have leading whitespace.3.13.0 (2011-01-25)Reenabled a test which makes sure405 MethodNotAllowedis returned
when PUT is not supported. This requires at least version 3.10 of
zope.app.http.3.12.0 (2010-09-14)Use the standard libraries doctest module.Include thenotfound.txttest again but reduce its scope to functionality
relevant to this distribution.Notify with IStartRequestEvent at the start of the request publication
cycle.3.11.1 (2010-04-19)Fix up tests to work with newer zope.app.wsgi release (3.9.0).3.11.0 (2010-04-13)Don’t depend on zope.app.testing and zope.app.zcmlfiles anymore in
the tests.3.10.2 (2010-01-08)Lift the test dependency on zope.app.zptpage.3.10.1 (2010-01-08)make zope.testing an optional (test) dependencyFix tests using a newer zope.publisher that requires zope.login.3.10.0 (2009-12-15)Moved EndRequestEvent and IEndRequestEvent to zope.publisher.Moved BeforeTraverseEvent and IBeforeTraverseEvent to zope.traversing.Removed dependency on zope.i18n.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.3.9.0 (2009-09-29)An abort within handleExceptions could have failed without logging what
caused the error. It now logs the original problem.Moved registration of and tests for two publication-specific event handlers
here from zope.site in order to invert the package dependency.Declared the missing dependency on zope.location.3.8.1 (2009-06-21)Bug fix: The publication traverseName method used ProxyFactory
rather than the publication proxy method.3.8.0 (2009-06-20)Added a proxy method that can be overridden in subclasses to control
how/if security proxies are created.Replaced zope.deprecation dependency with backward-compatible imports3.7.0 (2009-05-23)Moved the publicationtraverse module to zope.traversing, removing the
zope.app.publisher -> zope.app.publication dependency (which was a
cycle).Moved IHTTPException to zope.publisher, removing the dependency
on zope.app.http.Moved the DefaultViewName API from zope.app.publisher.browser to
zope.publisher.defaultview, making it accessible to other packages
that need it.Look up the application controller through a utility registration
rather than a direct reference.3.6.0 (2009-05-18)Usezope:adapterZCML directive instead ofzope:view.
This avoid dependency onzope.app.component.Update imports fromzope.app.securitytozope.authenticationandzope.principalregistry.Usezope.browser.interfaces.ISystemErrorto avoid dependency onzope.app.exception.Refactored tests so they can run successfully with ZODB 3.8 and 3.9.3.5.3 (2009-03-13)Adapt to the removal of IXMLPresentation from zope.app.publisher which
was removed to adapt to removal of deprecated interfaces from zope.component.3.5.2 (2009-03-10)Use ISkinnable.providedBy(request) instead of IBrowserRequest as condition
for calling setDefaultSkin. This at the same time removes dependency to
the browser part of zope.publisher.Remove deprecated code.Use built-in set class instead of the deprecated sets.Set and thus
don’t cause deprecation warning in Python 2.6.3.5.1 (2009-01-31)Import ISite from zope.location.interfaces instead of deprecated place
in zope.app.component.interfaces.3.5.0 (2008-10-09)Nowzope.app.publication.zopepublication.ZopePublicationannotates the
request with the connection to the main ZODB whengetApplicationis
called.Removed support for non-existent Zope versions.3.4.3 (2007-11-01)Removed unused imports.ResolveZopeSecurityPolicydeprecation warning.3.4.2 (2007-09-26)Added missing files to egg distribution.3.4.1 (2007-09-26)Added missing files to egg distribution.3.4.0 (2007-09-25)Initial documented release.Reflect changes formzope.app.errorrefactoring. |
zope.app.publisher | OverviewThis package is at present not reusable without depending on a large
chunk of the Zope Toolkit and its assumptions. It is maintained by theZope Toolkit project.This package used to provide browser page, resource and menu classes
for use with zope.publisher object publishing framework, as well as some
other useful utilities and adapters, but most of things was factored out
to separate packages, leaving here only backward-compatibility imports.However, some potentially useful things are still contained in this package:“date” field converter for zope.publisher’s BrowserRequest field converter
mechanism.“Browser Skins” vocabulary (a vocabulary for IBrowserSkinType utilities)ManagementViewSelector (a browser view that redirects to a first available
management view)XML-RPC view and method publishing mechanism along with xmlrpc:view ZCML
directive.CHANGES5.0 (2023-02-10)Add support for Python 3.9, 3.10, 3.11.Drop support for Python 2.7, 3.5, 3.6.Make.xmlrpc.testing.ServerProxyset an appropriateHostheader in
its request, allowing WSGI applications that serve multiple virtual hosts
to tell the difference between them.4.3.1 (2020-06-08)Fix handling of HTTP body in.xmlrpc.testingto enable characters
beyond ASCII.
(#11)4.3.0 (2020-05-12)Support optionsuse_datetime(Python >= 2.7) anduse_builtin_types(Python >= 3.5) in.xmlrpc.testing.ServerProxy.4.2.0 (2019-12-05)Move XMLRPC testing infrastructure from.xmlrpc.teststo.xmlrpc.testingand make it reusable by requiring the WSGI app to be
provided. Use thetestingextra fromsetup.pyto use this testing
infrastructure.
(#8)Add support for Python 3.8.Drop support for Python 3.4.4.1.0 (2018-10-22)Add support for Python 3.7.4.0.0 (2017-05-05)Add support for Python 3.4, 3.5, 3.6 and PyPy.Replaced an undeclared test dependency on zope.app.authentication with
zope.password.Removed test dependency onzope.app.testing,zope.app.zcmlfilesand others.3.10.2 (2010-09-14)Remove a testing dependency on zope.app.securitypolicy.3.10.1 (2010-01-08)Fix tests using a newer zope.publisher that requires zope.login.3.10.0 (2009-08-31)Fix test dependency on zope.container, now we depend on
zope.container >= 3.9.3.9.0 (2009-08-27)Refactor package, spliting it to several new packages:zope.browserresource- the resources mechanism was moved here, see its
CHANGES.txt for more information about changes during move.zope.ptresource- the page template resource was moved into another
package so zope.browserresource doesn’t depend on any templating system.
See zope.ptresource’s CHANGES.txt for more information.zope.browsermenu- the menu mechanism was moved here completely.zope.browserpage- the browser:page directive and friends were
moved here. Also, these directives don’t depend hardly on menu system
anymore, so they simply ignore the “menu” argument when zope.browsermenu
is not available.Backward-compatibility imports are provided, so there should not be much impact
for those who uses old imports.The CacheableBrowserLanguages and ModifiableBrowserLanguages adapters were
moved intozope.publisherpackage, as well as browser:defaultSkin and
browser:defaultView ZCML directives and ZCML class configuration for
zope.publisher classes.ZCML registrations of IXMLRPCPublisher adapters for zope.container were moved
into zope.container for now.3.8.4 (2009-07-23)Added dependency onzope.app.pagetemplate, it is used byzope.app.publisher.browser.viewmeta.3.8.3 (2009-06-18)Bugfix: FixIAbsoluteURLforIResourceconfiguration. The latest
release was moving the url generation for resources to an adapter which was
a good idea. But the adapter was configured forIDefaultBrowserLayer. This means every existing project which dosen’t
useIDefaultBrowserLayerwill get a wrongIAbsoluteURLadapter and
is loosing the@@part in the resource url.3.8.2 (2009-06-16)Remove test dependency onzope.app.pagetemplate.Calling a resource to get its URL now usesIAbsoluteURL.3.8.1 (2009-05-25)Updated to usezope.pagetemplate.enginemodule (requires versino
3.5.0 or later), instead ofzope.app.pagetemplateprecursor.Replacedzope.deprecationdependency with BBB imports3.8.0 (2009-05-23)There is no direct dependency on zope.app.component anymore (even in
the tests).Moved the publicationtraverse module to zope.traversing, removing the
zope.app.publisher -> zope.app.publication dependency (which was a
cycle).Moved the DefaultViewName API from zope.app.publisher.browser to
zope.publisher.defaultview, making it accessible to other packages
that need it.3.7.0 (2009-05-22)Use zope.componentvocabulary instead of zope.app.component
(except for tests and IBasicViewInformation).Use zope.browser for IAdding interface (instead of zope.app.container)Update references tozope.app.component.tests.viewsto point to the new
locations inzope.component.testfiles.views.3.6.2 (2009-03-18)RegisterIModifiableUserPreferredLanguagesadapter in the ZCML
configuration ofzope.app.publisher.browserpackage. This was previously
done byzope.app.i18n.3.6.1 (2009-03-12)Remove deprecated code.Adapt to removal of deprecated interfaces from zope.component.interfaces.
The IResource is now moved to zope.app.publisher.interfaces. The IView
and IDefaultViewName is now in zope.publisher.interfaces. The IPresentation
interface was removed completely.3.6.0 (2009-01-31)Use zope.container instead of zope.app.container.Use zope.site.folder instead of zope.app.folder.3.5.3 (2009-01-27)Finally removed <browser:skin> and <browser:layer> that were marked as
deprecated in 2006/02.3.5.2 (2008-12-06)Added possibility to specify custom item class in menuItem, subMenuItem
and addMenuItem directives using theitem_classargument (LP #291865).Menu items registered with <browser:page/> were not re-registered after the
first functional test layer ran. In any subsequent functional test layer the
items where not availabe (introduced in 3.5.0a3).Added a hook to specify a different BaseURL for resources. This makes sense
if you want to put resources on a Content Delivery Network. All you need to
do is to register an named Adapter ‘resource’ that implements IAbsoluteURL.3.5.1 (2008-10-13)Removed usage of deprecated LayerField from zope.app.component.back35.3.5.0 (2008-08-05)Refactored code to provide more hooks when deriving code from this pacakge.A resource’s URL creation is now in its own method.The resource class of factories can be overwritten.The cache timeout value can now be set as a class or instance attribute.3.5.0a4 (2007-12-28)Backed out the changes for the controversial XML-RPC skin support.3.5.0a3 (2007-11-27)make it possible to override menus: this was not possible because new
interfaces where created any time a menu with the same name was created.ResolveZopeSecurityPolicydeprecation warning.3.5.0a2 (2007-08-23)<browser:defaultView> now accepts classes as well as interfaces.3.5.0a1 (2007-08-21)Added alayerattribute toxmlrpc:view. This works just like layers forbrowser:viewetc. but uses theIXMLRPCSkinType. |
zope.app.pythonpage | Python Page provides the user with a content object that interprets
Python in content space.Detailed DcoumentationPython PagePython Page provides the user with a content object that interprets
Python in content space. To save typing and useless messing with
output, any free-standing string and print statement are considered
for output; see the example below.ExampleCreate a new content type called “Python Page” and enter the following
code example:'''
<html>
<body>
<ul>
'''
import time
print time.asctime()
'''
</ul>
</body>
</html>
'''CHANGES3.5.1 (2009-08-15)Fixed a spurious test failure when run with with Python 2.63.5.0 (2009-02-01)Replacezope.app.containerwithzope.container.3.4.1 (2007-07-30)Get rid of zope.app.zapi as a dependency.
Seehttps://bugs.launchpad.net/zope3/+bug/219302Fix deprecation warning in zope/app/pythonpage/browser.py: zope.app.i18n
was moved to zope.i18nmessageid.3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.renderer | This package provides a framework to convert a string from one format, such as
Structured or Restructured Text, to another, such as HTML. Converters are
looked up by adapter and uses other packages to implement the converters.CHANGES5.0 (2023-02-08)Drop support for Python 2.7, 3.4, 3.5, 3.6.Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11.4.1.0 (2017-05-25)Raise the docutils ReST error report level from its default oferrortosevere. An error-level report is issued for directives
that are unknown, such as:class:, which are increasingly common
due to the use of Sphinx. This change prevents such an error being
printed on stderr as well as rendered in the HTML.4.0.0 (2017-05-17)Add support for Python 3.4, 3.5, 3.6 and PyPy.Remove dependency onzope.app.testing.Use the standard librarydoctestmodule.3.5.1 (2009-07-21)Require the newromanpackage, since docutils does not install it
correctly.3.5.0 (2009-01-17)Adapted to docutils 0.5 for ReST rendering: get rid of the
ZopeTranslator class, because docutils changed the way it
uses translator so previous implementation doesn’t work anymore.
Instead, use publish_parts and join needed parts in therendermethod of the renderer itself.Removed deprecated meta.zcml stuff and zpkg stuff.Replaced __used_for__ with zope.component.adapts calls.3.4.0 (2007-10-27)Initial release independent of the main Zope tree. |
zope.app.rotterdam | This package provides an advanced skin for the Zope 3 ZMI.CHANGES5.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.Drop support forzope.app.skinswhich is deprecated since 2006.4.0.1 (2017-05-25)Remove long-deprecated <browser:layer> configuration which was hidden
behind ahave deprecatedlayerscondition. That directive simply
doesn’t exist any longer and defining that feature would cause an
“Unknown directive” ConfigurationError.4.0.0 (2017-04-27)Remove test dependency onzope.app.zcmlfiles,zope.app.testingand several others.Thezope.app.formdependency has been replaced withzope.formlib.Add support for PyPy, Python 3.4, 3.5 and 3.6.3.5.3 (2012-01-23)Replaced an undeclared test dependency onzope.app.authenticationwithzope.password.Replaced an undeclared test dependency onzope.app.folderwithzope.site.3.5.2 (2010-09-14)Removed not needed test dependency onzope.app.zptpage.Replaced test dependency onzope.app.securitypolicybyzope.securitypolicy.Using Python’sdoctestinstead of deprecatedzope.testing.doctest.3.5.1 (2010-01-08)Fix tests using a newer zope.publisher that requires zope.login.3.5.0 (2009-02-01)Use zope.container instead of zope.app.container.3.4.1 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-27)Initial release independent of the main Zope tree. |
zope.app.schema | This package provides a component architecture based vocabulary registry.Component-based Vocabulary RegistryThis package provides a vocabulary registry for zope.schema,
based on the component architecture.NOTE:This functionality has been replaced withzope.vocabularyregistry. These imports continue to work
for backwards compatibility.It replaces the zope.schema’s simple vocabulary registry
whenzope.app.schemapackage is imported, so it’s done
automatically. All we need is provide vocabulary factory
utilities:>>> import zope.app.schema
>>> from zope.component import provideUtility
>>> from zope.schema.interfaces import IVocabularyFactory
>>> from zope.schema.vocabulary import SimpleTerm
>>> from zope.schema.vocabulary import SimpleVocabulary>>> def SomeVocabulary(context=None):
... terms = [SimpleTerm(1), SimpleTerm(2)]
... return SimpleVocabulary(terms)>>> provideUtility(SomeVocabulary, IVocabularyFactory,
... name='SomeVocabulary')Now we can get the vocabulary using standard zope.schema
way:>>> from zope.schema.vocabulary import getVocabularyRegistry
>>> vr = getVocabularyRegistry()
>>> voc = vr.get(None, 'SomeVocabulary')
>>> [term.value for term in voc]
[1, 2]ConfigurationThis package provides configuration that sets security permissions and
factories for the objects provided inzope.schema. Thezope.securitypackage must be installed to use it.>>> from zope.configuration import xmlconfig
>>> _ = xmlconfig.string(r"""
... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope">
... <include package="zope.app.schema" />
... </configure>
... """)CHANGES5.0 (2023-02-07)Drop support for Python 2.7, 3.5, 3.6.Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11.4.1.0 (2017-05-10)Replaced the local implementation ofZopeVocabularyRegistrywith
one imported fromzope.vocabularyregistry. Backwards
compatibility imports remain.4.0.1 (2017-05-10)Packaging: Add the Python version and implementation classifiers.4.0.0 (2017-04-17)Support for Python 3.5, 3.6 and PyPy has been added.Added support for tox.Drop dependency onzope.app.testing, since it was not needed.3.6.0 (2017-04-17)Package modernization including manifest.3.5.0 (2008-12-16)Remove deprecatedvocabularydirective.Add test for component-based vocabulary registry.3.4.0 (2007-10-27)Initial release independent of the main Zope tree. |
zope.app.security | This package provides ZMI browser views for Zope security components.It used to provide a large part of security functionality for Zope 3, but it was
factored out from this package to several little packages to reduce dependencies
and improve reusability.The functionality was splitted into these new packages:zope.authentication - the IAuthentication interface and related utilities.zope.principalregistry - the global principal registry and its zcml directives.zope.app.localpermission - the LocalPermission class that implements
persistent permissions.The rest of functionality that were provided by this package is merged intozope.securityandzope.publisher.Backward-compatibility imports are provided to ensure that older applications
work. See CHANGES.txt for more info.Detailed DocumentationThe Query View for Authentication UtilitiesA regular authentication service will not provide theISourceQueriablesinterface, but it is a queriable itself, since it provides the simplegetPrincipals(name)method:>>> class Principal:
... def __init__(self, id):
... self.id = id>>> class MyAuthUtility:
... data = {'jim': Principal(42), 'don': Principal(0),
... 'stephan': Principal(1)}
...
... def getPrincipals(self, name):
... return [principal
... for id, principal in self.data.items()
... if name in id]Now that we have our queriable, we create the view for it:>>> from zope.app.security.browser.auth import AuthUtilitySearchView
>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> view = AuthUtilitySearchView(MyAuthUtility(), request)This allows us to render a search form.>>> print(view.render('test')) # doctest: +NORMALIZE_WHITESPACE
<h4>principals.zcml</h4>
<div class="row">
<div class="label">
Search String
</div>
<div class="field">
<input type="text" name="test.searchstring" />
</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.searchstring'] = 'n'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 (!):>>> ids = list(view.results('test'))
>>> ids.sort()
>>> ids
[0, 1]Login/Logout SnippetThe class LoginLogout:>>> from zope.app.security.browser.auth import LoginLogoutis used as a view to generate an HTML snippet suitable for logging in or
logging out based on whether or not the current principal is authenticated.When the current principal is unauthenticated, it provides
IUnauthenticatedPrincipal:>>> from zope.authentication.interfaces import IUnauthenticatedPrincipal
>>> from zope.principalregistry.principalregistry import UnauthenticatedPrincipal
>>> anonymous = UnauthenticatedPrincipal('anon', '', '')
>>> IUnauthenticatedPrincipal.providedBy(anonymous)
TrueWhen LoginLogout is used for a request that has an unauthenticated principal,
it provides the user with a link to ‘Login’:>>> from zope.publisher.browser import TestRequest
>>> request = TestRequest()
>>> request.setPrincipal(anonymous)
>>> print(LoginLogout(None, request)())
<a href="@@login.html?nextURL=http%3A//127.0.0.1">[Login]</a>Attempting to login at this point will fail because nothing has
authorized the principal yet:>>> from zope.app.security.browser.auth import HTTPAuthenticationLogin
>>> login = HTTPAuthenticationLogin()
>>> login.request = request
>>> login.context = None
>>> login.failed = lambda: 'Login Failed'
>>> login.login()
'Login Failed'There is a failsafe that will attempt to ask for HTTP Basic authentication:>>> from zope.app.security.browser.auth import HTTPBasicAuthenticationLogin
>>> basic_login = HTTPBasicAuthenticationLogin()
>>> basic_login.request = request
>>> basic_login.failed = lambda: 'Basic Login Failed'
>>> basic_login.login()
'Basic Login Failed'
>>> request._response.getHeader('WWW-Authenticate', literal=True)
'basic realm="Zope"'
>>> request._response.getStatus()
401Of course, an unauthorized principal is confirmed to be logged out:>>> from zope.app.security.browser.auth import HTTPAuthenticationLogout
>>> logout = HTTPAuthenticationLogout(None, request)
>>> logout.logout(nextURL="bye.html")
'bye.html'
>>> logout.confirmation = lambda: 'Good Bye'
>>> logout.logout()
'Good Bye'Logout, however, behaves differently. Not all authentication protocols (i.e.
credentials extractors/challengers) support ‘logout’. Furthermore, we don’t
know how an admin may have configured Zope’s authentication. Our solution is
to rely on the admin to tell us explicitly that the site supports logout.By default, the LoginLogout snippet will not provide a logout link for an
unauthenticated principal. To illustrate, we’ll first setup a request with an
unauthenticated principal:>>> from zope.security.interfaces import IPrincipal
>>> from zope.interface import implementer
>>> @implementer(IPrincipal)
... class Bob:
... id = 'bob'
... title = description = ''
>>> bob = Bob()
>>> IUnauthenticatedPrincipal.providedBy(bob)
False
>>> request.setPrincipal(bob)In this case, the default behavior is to return None for the snippet:>>> print(LoginLogout(None, request)())
NoneAnd at this time, login will correctly direct us to the next URL, or
to the confirmation page:>>> login = HTTPAuthenticationLogin()
>>> login.request = request
>>> login.context = None
>>> login.login(nextURL='good.html')
>>> login.confirmation = lambda: "You Passed"
>>> login.login()
'You Passed'Likewise for HTTP Basic authentication:>>> login = HTTPBasicAuthenticationLogin()
>>> login.request = request
>>> login.context = None
>>> login.confirmation = lambda: "You Passed"
>>> login.login()
'You Passed'To show a logout prompt, an admin must register a marker adapter that provides
the interface:>>> from zope.authentication.interfaces import ILogoutSupportedThis flags to LoginLogout that the site supports logout. There is a ‘no-op’
adapter that can be registered for this:>>> from zope.authentication.logout import LogoutSupported
>>> from zope.component import provideAdapter
>>> provideAdapter(LogoutSupported, (None,), ILogoutSupported)Now when we use LoginLogout with an unauthenticated principal, we get a logout
prompt:>>> print(LoginLogout(None, request)())
<a href="@@logout.html?nextURL=http%3A//127.0.0.1">[Logout]</a>And we can log this principal out, passing a URL to redirect to:>>> logout = HTTPAuthenticationLogout(None, request)
>>> logout.redirect = lambda: 'You have been redirected.'
>>> logout.logout(nextURL="loggedout.html")
'You have been redirected.'CHANGES6.0 (2023-02-17)Add support for Python 3.10, 3.11.Drop support for Python 2.7, 3.5, 3.6.5.1.0 (2020-10-28)Add support for Python 3.8 and 3.9.Drop support for Python 3.5.Drop security declarations for the deprecatedbinhexstandard library
module from globalmodules.zcml.Note that globalmodules.zcml should be avoided. It’s better to make
declarations for only what you actually need to use.5.0.0 (2019-07-12)Add support for Python 3.7.Drop support for Python 3.4.Drop security declarations for the deprecatedformatterstandard library
module from globalmodules.zcml.Note that globalmodules.zcml should be avoided. It’s better to make
declarations for only what you actually need to use.4.0.0 (2017-04-27)Removed use of ‘zope.testing.doctestunit’ in favor of stdlib’s doctest.Removed use ofzope.app.testingin favor ofzope.app.wsgi.Add support for PyPy, Python 3.4, 3.5 and 3.6.3.7.5 (2010-01-08)Move ‘zope.ManageApplication’ permission to zope.app.applicationcontrolFix tests using a newer zope.publisher that requires zope.login.3.7.3 (2009-11-29)provide a clean zope setup and move zope.app.testing to a test dependencyremoved unused dependencies like ZODB3 etc. from install_requires3.7.2 (2009-09-10)Added data attribute to ‘_protections.zcml’ for PersistentList
and PersistentDict to accomodate UserList and UserDict behavior
when they are proxied.3.7.1 (2009-08-15)Changed globalmodules.zcml to avoid making declarations for
deprecated standard modules, to avoid deprecation warnings.Note that globalmodules.zcml should be avoided. It’s better to make
declarations for only what you actually need to use.3.7.0 (2009-03-14)All interfaces, as well as some authentication-related helper classes and
functions (checkPrincipal, PrincipalSource, PrincipalTerms, etc.) were moved
into the newzope.authenticationpackage. Backward-compatibility imports
are provided.The “global principal registry” along with its zcml directives was moved into
new “zope.principalregistry” package. Backward-compatibility imports are
provided.The IPrincipal -> zope.publisher.interfaces.logginginfo.ILoggingInfo
adapter was moved tozope.publisher. Backward-compatibility import
is provided.The PermissionsVocabulary and PermissionIdsVocabulary has been moved
to thezope.securitypackage. Backward-compatibility imports are
provided.The registration of the “zope.Public” permission as well as some other
common permissions, like “zope.View” have been moved tozope.security.
Its configure.zcml is now included by this package.The “protect” function is now a no-op and is not needed anymore, because
zope.security now knows about i18n messages and __name__ and __parent__
attributes and won’t protect them by default.The addCheckerPublic was moved from zope.app.security.tests to
zope.security.testing. Backward-compatibility import is provided.TheLocalPermissionclass is now moved to newzope.app.localpermissionpackage. This package now only has backward-compatibility imports and
zcml includes.Cleanup dependencies after refactorings. Also, don’t depend on
zope.app.testing for tests anymore.Update package’s description to point about refactorings done.3.6.2 (2009-03-10)TheAllow,DenyandUnsetpermission settings was preferred to
be imported fromzope.securitypolicy.interfacesfor a long time
and now they are completely moved there fromzope.app.security.settingsas well as thePermissionSettingclass. The only thing left for
backward compatibility is the import of Allow/Unset/Deny constants ifzope.securitypolicyis installed to allow unpickling of security
settings.3.6.1 (2009-03-09)Depend on newzope.passwordpackage instead ofzope.app.authenticationto get password managers for the authentication utility, thus remove
dependency onzope.app.authentication.Use template for AuthUtilitySearchView instead of ugly HTML
constructing in the python code.Bug: Theshaandmd5modules has been deprecated in Python 2.6.
Whenever the ZCML of this package was included when using Python 2.6,
a deprecation warning had been raised stating thatmd5andshahave
been deprecated. Provided a simple condition to check whether Python 2.6
or later is installed by checking for the presense ofjsonmodule
thas was added only in Python 2.6 and thus optionally load the security
declaration formd5andsha.Remove deprecated code, thus removing explicit dependency on
zope.deprecation and zope.deferredimport.Cleanup code a bit, replace old __used_for__ statements byadaptscalls.3.6.0 (2009-01-31)Changed mailing list address to zope-dev at zope.org, because
zope3-dev is retired now. Changed “cheeseshop” to “pypi” in
the package homepage.Moved theprotectclassmodule tozope.securityleaving only a
compatibility module here that imports from the new location.Moved the <module> directive implementation tozope.security.Usezope.containerinstead ofzope.app.container;.3.5.3 (2008-12-11)use zope.browser.interfaces.ITerms instead ofzope.app.form.browser.interfaces.3.5.2 (2008-07-31)Bug: It turned out that checking for regex was not much better of an
idea, since it causes deprecation warnings in Python 2.4. Thus let’s
look for a library that was added in Python 2.5.3.5.1 (2008-06-24)Bug: Thegopherlibmodule has been deprecated in Python 2.5. Whenever the
ZCML of this package was included when using Python 2.5, a deprecation
warning had been raised stating thatgopherlibhas been
deprecated. Provided a simple condition to check whether Python 2.5 or later
is installed by checking for the deletedregexmodule and thus optionally
load the security declaration forgopherlib.3.5.0 (2008-02-05)Feature:zope.app.security.principalregistry.PrincipalRegistry.getPrincipalreturnszope.security.management.system_userwhen its id is used for the search
key.3.4.0 (2007-10-27)Initial release independent of the main Zope tree. |
zope.app.securitypolicy | This package provides management views forzope.securitypolicy.
It’s intended to be used within the “ZMI-based” browser interface.It used to contain a security policy implementation ages ago, but the
implementation was moved to the UI-independentzope.securitypolicypackage.CHANGES3.6.1 (2010-09-25)Added missing minimum version declaration forzope.app.authentication,
namely 3.8.3.6.0 (2010-09-25)LP: #161906: Remove superfluous “helpful” message. Improve wording of of the
relation between roles and permissions in the manage_permissionform.Moved the following views tozope.app.authenticationto inverse
dependency between these two packages, aszope.app.securitypolicyis
deprecated in ZTK 1.0 (leaving BBB imports in place):@@grant.html@@AllRolePermissions.html@@RolePermissions.html@@RolesWithPermission.html3.5.2 (2010-01-08)Remove deprecated compatibility imports. Now, this package only
contains ZMI views for zope.securitypolicy.Update package’s description and mailing list address.Fix tests using a newer zope.publisher that requires zope.login.3.5.1 (2009-01-27)Added missing dependency for tests: zope.app.zcmlfiles3.5.0 (2008-12-11)use zope.browser.interfaces.ITerms instead of zope.app.form.browser.interfaces
This version requires zope.app.form 3.7.0 or higher if you use the browser
part of this package. (grant form)Substitute zope.app.zapi by direct calls to its wrapped apis. See bug 2193023.4.6 (2007-11-09)zope.app.securitypolicy needs at least zope.i18nmessageid 3.4.2, it
wasn’t stating that in its dependencies.3.4.5 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.Re-activated the functional tests.3.4.4 (2007-10-23)Avoid deprecation warnings.3.4.3 (2007-10-01)Correct deferred import for BBB.3.4.2 (2007-09-27)Add back securitypolicy.zcml
(https://bugs.launchpad.net/zope3/+bug/145655)3.4.1 (2007-09-26)Zip releases don’t seem to work, so let’s create a new one.3.4.0 (2007-09-25)Initial documented release |
zope.app.server | This package integrates ZServer – Zope’s HTTP and FTP server – into a Zope 3
application setup. It also defines the script skeleton for a classic Zope 3
application.CHANGES5.0 (2023-02-28)Add support for Python 3.10, 3.11.Drop support for Python 2.7, 3.5, 3.6.4.1.0 (2020-11-11)Add support for Python 3.7, 3.8, and 3.9.Drop support for Python 3.4 and 3.5.4.0.0 (2017-11-15)Add support for Python 3.4, 3.5, and 3.6.Add support for PyPy.3.6.0 (2011-03-23)Movedzope.app.server.zpasswdtozope.password.zpasswd.3.5.0 (2009-12-19)Usezope.passwordinstead ofzope.app.authenticationDepend on newzope.processlifetimeimplementations instead of
using BBB imports fromzope.app.appsetup.3.4.2 (2008-08-18)Moved a doctest into a unittest to fix failures in the KGS test suite
(see LP #257954)3.4.1 (2008-02-25)Fixed restart so that the process exits with a non-zero exit status
so it gets restarted by zdaemon, or an equivalent mechanism.Removed the use ofThreadedAsync.3.4.0 (2007-10-27)Initial release independent of the main Zope tree. |
zope.app.session | This package provides session support.Zope3 Session ImplementationNoteAll interfaces and implementations provided by this package
have been migrated tozope.session. This package now
merely provides ZMI menu configuration.OverviewCaution!Session data is maintained on the server. This gives a security
advantage in that we can assume that a client has not tampered with
the data. However, this can have major implications for scalability
as modifying session data too frequently can put a significant load
on servers and in extreme situations render your site unusable.
Developers should keep this in mind when writing code or risk
problems when their application is run in a production environment.Applications requiring write-intensive session implementations (such
as page counters) should consider using cookies or specialized
session implementations.Sessions allow us to fake state over a stateless protocol - HTTP.
We do this by having a unique identifier stored across multiple
HTTP requests, be it a cookie or some id mangled into the URL.TheIClientIdManagerUtility provides this unique id. It is
responsible for propagating this id so that future requests from the
client get the same id (eg. by setting an HTTP cookie). (Note that
this, and all interfaces, are imported from this package for
demonstration purposes only. They have been moved tozope.session.interfaces) This utility is used when we adapt the
request to the unique client id:>>> from zope.app.session.interfaces import IClientId
>>> IClientId
<InterfaceClass zope.session.interfaces.IClientId>
>>> client_id = IClientId(request)TheISessionadapter gives us a mapping that can be used to store
and retrieve session data. A unique key (the package id) is used
to avoid namespace clashes:>>> from zope.app.session.interfaces import ISession
>>> pkg_id = 'products.foo'
>>> session = ISession(request)[pkg_id]
>>> session['color'] = 'red'>>> session2 = ISession(request)['products.bar']
>>> session2['color'] = 'blue'>>> session['color']
'red'
>>> session2['color']
'blue'Data StorageThe actual data is stored in anISessionDataContainerutility.ISessionchooses whichISessionDataContainershould be used by
looking up as a named utility using the package id. This allows
the site administrator to configure where the session data is actually
stored by adding a registration for desiredISessionDataContainerwith the correct name.>>> from zope.app.session.interfaces import ISessionDataContainer
>>> from zope.component import getUtility
>>> sdc = getUtility(ISessionDataContainer, pkg_id)
>>> sdc[client_id][pkg_id] is session
True
>>> sdc[client_id][pkg_id]['color']
'red'If noISessionDataContainerutility can be located by name using the
package id, then the unnamedISessionDataContainerutility is used as
a fallback. An unnamedISessionDataContaineris automatically created
for you, which may replaced with a different implementation if desired.>>> ISession(request)['unknown'] \
... is getUtility(ISessionDataContainer)[client_id]['unknown']
TrueTheISessionDataContainercontainsISessionDataobjects, andISessionDataobjects in turn containISessionPkgDataobjects. You
should never need to know this unless you are writing administrative
views for the session machinery.>>> from zope.app.session.interfaces import ISessionData, ISessionPkgData
>>> ISessionData.providedBy(sdc[client_id])
True
>>> ISessionPkgData.providedBy(sdc[client_id][pkg_id])
TrueTheISessionDataContaineris responsible for expiring session data.
The expiry time can be configured by settings itstimeoutattribute.>>> sdc.timeout = 1200 # 1200 seconds or 20 minutesRestrictionsData stored in the session must be persistent or picklable.>>> class NoPickle(object):
... def __getstate__(self):
... raise TypeError("Cannot serialize")
>>> session['oops'] = NoPickle()
>>> import transaction
>>> transaction.commit()
Traceback (most recent call last):
...
TypeError: Cannot serializePage TemplatesSession data may be accessed in page template documents using
TALES:<span tal:content="request/session:products.foo/color | default">
green
</span>or:<div tal:define="session request/session:products.foo">
<script type="text/server-python">
try:
session['count'] += 1
except KeyError:
session['count'] = 1
</script>
<span tal:content="session/count" />
</div>CHANGES5.0 (2023-02-10)Drop support for Python 2.7, 3.5, 3.6.Add support for Python 3.8, 3.9, 3.10, 3.11.4.1.0 (2018-10-22)Add support for Python 3.7.4.0.0 (2017-05-29)Add support for Python 3.4, 3.5, 3.6 and PyPy.Remove dependency onZODB3and other packages that are not used
by this package, leaving behind onlyzope.session. Packages that
are used during testing are now test dependencies.3.6.2 (2010-09-01)Remove undeclared dependency onzope.deferredimport.3.6.1 (2010-02-06)Include meta.zcml from zope.securitypolicy3.6.0 (2009-02-01)Usezope.siteinstead ofzope.app.folderin tests.3.5.2 (2009-01-27)Fixed tearDown-Error in tests.3.5.1 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.3.5.0 (2007-09-27)A release to override an untagged, unreasoned dev release indownload.zope.org/distribution.3.4.3 (2007-09-27)Fix package meta-data.3.4.2 (2007-09-24)rebumped to replace faulty eggadded missing dependecy tozope.session3.4.1 (2007-09-24)Added missing files to egg distribution3.4.0 (2007-09-24)Initial documented release |
zope.app.skins | A meta-package in which generated skin interfaces are placed.CHANGES3.4.0 (2007-10-27)Initial release independent of the main Zope tree. |
zope.app.sqlexpr | The goal of the SQL TALES expression is to allow quick SQL queries
right out of TALES expressions and Zope Page Templates. While this
is certainly not the Zopeish way of doing things, it allows the
newbie Web scripter an easier entrance to the world of Zope 3.Detailed DocumentationCHANGESVersion 0.1 (2009-07-24)Initial Release as an egg. |
zope.app.sqlscript | This package provides the SQL Script content type for Zope 3 applications. SQL
Scripts are connected to execute SQL statements and the result is return in an
object-oriented data structure.Detailed DocumentationUsing additional DTML tags in SQLScriptInserting optional tests with ‘sqlgroup’It is sometimes useful to make inputs to an SQL statement optinal.
Doing so can be difficult, because not only must the test be inserted
conditionally, but SQL boolean operators may or may not need to be
inserted depending on whether other, possibly optional, comparisons
have been done. The ‘sqlgroup’ tag automates the conditional
insertion of boolean operators.The ‘sqlgroup’ tag is a block tag that has no attributes. It can have
any number of ‘and’ and ‘or’ continuation tags.Suppose we want to find all people with a given first or nick name and
optionally constrain the search by city and minimum and maximum age.
Suppose we want all inputs to be optional. We can use DTML source
like the following:<dtml-sqlgroup>
<dtml-sqlgroup>
<dtml-sqltest name column=nick_name type=nb multiple optional>
<dtml-or>
<dtml-sqltest name column=first_name type=nb multiple optional>
</dtml-sqlgroup>
<dtml-and>
<dtml-sqltest home_town type=nb optional>
<dtml-and>
<dtml-if minimum_age>
age >= <dtml-sqlvar minimum_age type=int>
</dtml-if>
<dtml-and>
<dtml-if maximum_age>
age <= <dtml-sqlvar maximum_age type=int>
</dtml-if>
</dtml-sqlgroup>This example illustrates how groups can be nested to control boolean
evaluation order. It also illustrates that the grouping facility can
also be used with other DTML tags like ‘if’ tags.The ‘sqlgroup’ tag checks to see if text to be inserted contains other
than whitespace characters. If it does, then it is inserted with the
appropriate boolean operator, as indicated by use of an ‘and’ or ‘or’
tag, otherwise, no text is inserted.Inserting optional tests with ‘sqlgroup’It is sometimes useful to make inputs to an SQL statement optinal.
Doing so can be difficult, because not only must the test be inserted
conditionally, but SQL boolean operators may or may not need to be
inserted depending on whether other, possibly optional, comparisons
have been done. The ‘sqlgroup’ tag automates the conditional
insertion of boolean operators.The ‘sqlgroup’ tag is a block tag. It can have any number of ‘and’ and
‘or’ continuation tags.The ‘sqlgroup’ tag has an optional attribure, ‘required’ to specify
groups that must include at least one test. This is useful when you
want to make sure that a query is qualified, but want to be very
flexible about how it is qualified.Suppose we want to find people with a given first or nick name, city
or minimum and maximum age. Suppose we want all inputs to be
optional, but want to requiresomeinput. We can use DTML source
like the following:<dtml-sqlgroup required>
<dtml-sqlgroup>
<dtml-sqltest name column=nick_name type=nb multiple optional>
<dtml-or>
<dtml-sqltest name column=first_name type=nb multiple optional>
</dtml-sqlgroup>
<dtml-and>
<dtml-sqltest home_town type=nb optional>
<dtml-and>
<dtml-if minimum_age>
age >= <dtml-sqlvar minimum_age type=int>
</dtml-if>
<dtml-and>
<dtml-if maximum_age>
age <= <dtml-sqlvar maximum_age type=int>
</dtml-if>
</dtml-sqlgroup>This example illustrates how groups can be nested to control boolean
evaluation order. It also illustrates that the grouping facility can
also be used with other DTML tags like ‘if’ tags.The ‘sqlgroup’ tag checks to see if text to be inserted contains other
than whitespace characters. If it does, then it is inserted with the
appropriate boolean operator, as indicated by use of an ‘and’ or ‘or’
tag, otherwise, no text is inserted.Inserting values with the ‘sqlvar’ tagThe ‘sqlvar’ tag is used to type-safely insert values into SQL text.
The ‘sqlvar’ tag is similar to the ‘var’ tag, except that it replaces
text formatting parameters with SQL type information.The sqlvar tag has the following attributes:nameThe name of the variable to insert. As with other DTML tags, the
‘name=’ prefix may be, and usually is, ommitted.typeThe data type of the value to be inserted. This attribute is
required and may be one of ‘string’, ‘int’, ‘float’, or ‘nb’. The
‘nb’ data type indicates a string that must have a length that is
greater than 0.optionalA flag indicating that a value is optional. If a value is optional
and is not provided (or is blank when a non-blank value is
expected), then the string ‘null’ is inserted.For example, given the tag:<dtml-sqlvar x type=nb optional>if the value of ‘x’ is:Let\'s do itthen the text inserted is:‘Let’’s do it’however, if x is ommitted or an empty string, then the value inserted
is ‘null’.CHANGES3.5.0 (2009-02-01)Usezope.containerinstead ofzope.app.container.3.4.1 (2007-10-31)ResolveZopeSecurityPolicydeprecation warning.3.4.0 (2007-10-27)Initial release independent of the main Zope tree. |
zope.app.testing | zope.app.testingThis package provides testing support for Zope 3 applications. Besides
providing numerous setup convenience functions, it implements a testing setup
that allows the user to make calls to the publisher allowing to write
functional tests.Contentszope.app.testingFDocTest (How-To)DocTest Functional TestsRequest/Response Functional TestsAccess to the object systemCHANGES5.0 (2023-02-10)4.0.0 (2018-10-24)3.10.0 (2012-01-13)3.9.0 (2011-03-14)3.8.1 (2011-01-07)3.8.0 (2010-09-14)3.7.7 (2010-09-14)3.7.6 (2010-09-14)3.7.5 (2010-04-10)3.7.4 (2010-01-08)3.7.3 (2009-08-20)3.7.2 (2009-07-24)3.7.1 (2009-07-21)3.7.0 (2009-06-19)3.6.2 (2009-04-26)3.6.1 (2009-03-12)3.6.0 (2009-02-01)3.5.6 (2008-10-13)3.5.5 (2008-10-10)3.5.4 (2008-08-25)3.5.3 (2008-08-22)3.5.2 (2008-08-21)3.5.1 (2008-08-20)3.5.0 (2008-08-20)3.4.3 (2008-07-25)3.4.2 (2008-02-02)3.4.1 (2007-10-31)3.4.0 (2007-10-27)FDocTest (How-To)Steps to get started:Use a clean/missing Data.fsCreate a manager with the name “mgr”, password “mgrpw”, and grant
the zope.Manager role.Install tcpwatch.Create a temporary directory to record tcpwatch output.Run tcpwatch using:
tcpwatch.py -L 8081:8080 -s -r tmpdir
(the ports are the listening port and forwarded-to port; the
second need to match the Zope configuration)In a browser, connect to the listening port and do whatever needs
to be recorded.Shut down tcpwatch.Run the script src/zope/app/testing/dochttp.py:
python2.4 src/zope/app/testing/dochttp.py tmpdir > somefile.txtEdit the generated text file to add explanations and elide
uninteresting portions of the output.In a functional test module (usually ftests.py), import
FunctionalDocFileSuite from zope.app.testing.functional and
instantiate it, passing the name of the text file containing
the test.DocTest Functional TestsThis file documents and tests doctest-based functional tests and basic
Zope web-application functionality.Request/Response Functional TestsYou can create Functional tests as doctests. Typically, this is done
by using a script such as src/zope/app/testing/dochttp.py to convert
tcpwatch recorded output to a doctest, which is then edited to provide
explanation and to remove uninteresting details. That is how this
file was created.Here we’ll test some of the most basic types of access.First, we’ll test accessing a protected page without credentials:>>> print(http(r"""
... GET /@@contents.html HTTP/1.1
... """))
HTTP/1.1 401 Unauthorized
Cache-Control: no-store, no-cache, must-revalidate
Content-Length: ...
Content-Type: text/html;charset=utf-8
Expires: Mon, 26 Jul 1997 05:00:00 GMT
Pragma: no-cache
WWW-Authenticate: basic realm="Zope"
<BLANKLINE>
<!DOCTYPE html PUBLIC ...Here we see that we got:A 401 response,A WWW-Authenticate header, andAn html body with an error messageSome technical headers to keep squid happyNote that we used ellipsis to indicate ininteresting details.Next, we’ll access the same page with credentials:>>> print(http(r"""
... GET /@@contents.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """))
HTTP/1.1 200 OK
Content-Length: ...
Content-Type: text/html;charset=utf-8
<BLANKLINE>
<!DOCTYPE html PUBLIC ...Important note: you must use the user named “mgr” with a password
“mgrpw”.And we get a normal output.Next we’ll try accessing site management. Since we used “/manage”,
we got redirected:>>> print(http(r"""
... GET /++etc++site/@@manage HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Referer: http://localhost:8081/
... """))
HTTP/1.1 303 See Other
Content-Length: 0
Content-Type: text/plain;charset=utf-8
Location: @@contents.html
<BLANKLINE>Note that, in this case, we got a 303 response. A 303 response is the
prefered response for this sort of redirect with HTTP 1.1. If we used
HTTP 1.0, we’d get a 302 response:>>> print(http(r"""
... GET /++etc++site/@@manage HTTP/1.0
... Authorization: Basic mgr:mgrpw
... Referer: http://localhost:8081/
... """))
HTTP/1.0 302 Moved Temporarily
Content-Length: 0
Content-Type: text/plain;charset=utf-8
Location: @@contents.html
<BLANKLINE>Lets visit the page we were redirected to:>>> print(http(r"""
... GET /++etc++site/@@contents.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Referer: http://localhost:8081/
... """))
HTTP/1.1 200 OK
Content-Length: ...
Content-Type: text/html;charset=utf-8
<BLANKLINE>
<!DOCTYPE html PUBLIC ...Finally, lets access the default page for the site:>>> print(http(r"""
... GET / HTTP/1.1
... Authorization: Basic mgr:mgrpw
... """))
HTTP/1.1 200 OK
Content-Length: ...
Content-Type: text/html;charset=utf-8
<BLANKLINE>
<!DOCTYPE html PUBLIC ...Access to the object systemYou can use thegetRootFolder()function:>>> root = getRootFolder()
>>> root
<zope.site.folder.Folder object at ...>You can intermix HTTP requests with regular Python calls. Note,
however, that making anhttp()call implied a transaction commit.
If you want to throw away changes made in Python code, abort the
transaction before the HTTP request.>>> print(http(r"""
... POST /@@contents.html HTTP/1.1
... Authorization: Basic mgr:mgrpw
... Content-Length: 73
... Content-Type: application/x-www-form-urlencoded
...
... type_name=BrowserAdd__zope.site.folder.Folder&new_value=f1""",
... handle_errors=False))
HTTP/1.1 303 See Other
Content-Length: ...
Content-Type: text/html;charset=utf-8
Location: http://localhost/@@contents.html
<BLANKLINE>
<!DOCTYPE html ...Now we can see that the new folder was added:>>> [str(x) for x in root.keys()]
['f1']CHANGES5.0 (2023-02-10)Add support for Python 3.8, 3.9, 3.10, 3.11.Drop support for Python 2.7, 3.5, 3.6.4.0.0 (2018-10-24)Removezope.app.testing.testbrowser. It was not compatible with
zope.testbrowser version 5.Add basic support for Python 3.5, 3.6 and 3.7.3.10.0 (2012-01-13)Removed test dependency onzope.app.authentication.zope.testbrowser 4 depends on this change (seriously) if it find
zope.app.testing.3.9.0 (2011-03-14)Move zope.app.testing testbrowser functionality into zope.app.testing. This
requires zope.testbrowser version 4.0.0 or above.3.8.1 (2011-01-07)Include REMOTE_ADDR (‘127.0.0.1’) in the request environment.3.8.0 (2010-09-14)Remove invalid HTTP_REFERER default. (We both don’t want a default to allow
others testing without a referer and ‘localhost’ is not a reasonable
default anyway.) This improves the situation for #98437Made the xmlrpc code compatible with Python 2.7.Removed test dependency onzope.app.zptpage.Switched test dependency fromzope.app.securitypolicytozope.securitypolicy.3.7.7 (2010-09-14)Rereleasing 3.7.5 as 3.7.7 to fix brown bag release.3.7.6 (2010-09-14)Brown bag release: It broke the tests ofzope.testbrowser.3.7.5 (2010-04-10)Switch doctests to use the stdlibdoctestmodule, rather than the
deprecatedzope.testing.doctestvariant.3.7.4 (2010-01-08)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.Fix tests using a newer zope.publisher that requires zope.login.3.7.3 (2009-08-20)Fixed tests for python 2.4 as well as python 2.5 and 2.6; the change in
version 3.7.1 introduced test regressions in python 2.4.3.7.2 (2009-07-24)Adjusted tests after the referenced memory leak problem has been fixed inzope.component.3.7.1 (2009-07-21)Fixed failing tests. The code revealed that the tests expected the wrong
value.3.7.0 (2009-06-19)Depend on newzope.processlifetimeinterfaces instead of using
BBB imports fromzope.app.appsetup.Removed unused dependency onzope.app.component.3.6.2 (2009-04-26)Removed deprecated back35 module and loose the dependency onzope.deferredimport.Adapt tozope.app.authenticationrefactoring. We depend onzope.passwordnow instead.Adapt to latestzope.app.securityrefactoring. We don’t need this
package anymore.3.6.1 (2009-03-12)Use ISkinnable.providedBy(request) instead of IBrowserRequest as condition
for calling setDefaultSkin in HTTPCaller. This at the same time removes
dependency to the browser part of zope.publisher.Adapt to the move of IDefaultViewName from zope.component.interfaces
to zope.publisher.interfaces.Remove the DEPENDENCIES.cfg file for zpkg.3.6.0 (2009-02-01)Fix AttributeError inzope.app.testing.setup.setUpTestAsModule(when called without name argument).Usezope.containerinstead ofzope.app.container.Usezope.siteinstead ofzope.app.folderandzope.app.componentfor some parts.3.5.6 (2008-10-13)Change argument variable name in provideAdapter to not conflict with
buitin keyword in Python 2.6.3.5.5 (2008-10-10)Re-configured functional test setup to create test-specific instances
of HTTPCaller to ensure that cookies are not shared by doctests
in a test suite.3.5.4 (2008-08-25)Clean up some transaction management in the functional test setup.3.5.3 (2008-08-22)Fix isolation enforcement for product configuration around individual tests.3.5.2 (2008-08-21)Added missing dependency information in setup.py.Added missing import.Repair memory leak fix released in 3.4.3 to be more sane in the presence of
generations.3.5.1 (2008-08-20)Correct Fred’s “I’m a doofus” release.3.5.0 (2008-08-20)Add support for product-configuration as part of functional layers; this
more closely mirrors the configuration order for normal operation.3.4.3 (2008-07-25)Fix memory leak in all functional tests.
see:https://bugs.launchpad.net/zope3/+bug/2512733.4.2 (2008-02-02)Fix of 599 error on conflict error in request
see:http://mail.zope.org/pipermail/zope-dev/2008-January/030844.html3.4.1 (2007-10-31)Fixed deprecation warning forZopeSecurityPolicy.3.4.0 (2007-10-27)Initial release independent of the main Zope tree. |
zope.app.traversing | The zope.traversing package provides adapteres for resolving object paths by
traversing an object hierarchy. This also includes support for traversal
namespaces (e.g.++view++,++skin++, etc.) as well as computing URLs via the@@absolute_urlview.DEPRECATED: This package has been deprecated and its functionality moved tozope.traversing.CHANGES3.4.0 (2007-10-24)Initial release independent of the main Zope tree. |
zope.app.tree | This package was designed to be a light-weight and easy-to-use static tree
implementation. It allows the developer to quickly create trees with nodes
that can be opened and closed without the use of JavaScript. The tree state
can be retained over multiple sessions.Documentation is hosted athttps://zopeapptree.readthedocs.ioCHANGES4.1.0 (2021-03-22)Add support for Python 3.7, 3.8 and 3.9.Add support forzope.component >= 5.Drop support for Python 3.4.Update PyPy versions.4.0.0 (2017-05-16)Add support for Python 3.4, 3.5, 3.6 and PyPy.Fix #264614: Test for node filter didn’t do what it was expected to do.Import ISite from zope.component after it was moved there from
zope.location.3.6.0 (2009-02-01)Converted from using zope.app.container to zope.container.3.5.1 (2009-01-29)Add compatibility for newer zope.traversing releases that require us
to explicitly set up testing. This also works with older releases.3.5.0 (2009-01-17)Get rid of zope.app.zapi dependency, replacing its uses with
direct imports.Clean up dependencies, move testing and rotterdam dependencies
to extra requires.Fix mailing list address [email protected] of [email protected]. Changecheeseshoptopypiin the package
url.Replace __used_for__ in adapters.py with zope.component.adapts
calls to make more sense.Remove obsolete zpkg files, zcml include file for mkzopeinstance-based
installations, versions.txt that makes no sense now.3.4.0 (2007-10-28)Initial release independent of the main Zope tree.v1.2 (2004-02-19) – ‘Scruffy’Moved tozope.app.treeIt is now called ‘ZopeTree’ again. Hoorray!Refactored browser stuff into its own browser subpackage.Separated the handling of tree state from the cookie functionality
to provide a base class for views based on other tree state sources.v1.1 (2004-02-16) – ‘Zapp’Added support for displaying lines in a tree (Stephan Richter)Changes inNode.getFlatDict()to provide more data. Removed
‘depth’ from node info, but added ‘row-state’ and
‘last-level-node’. Changed interface and test accordingly.Updated templates forStaticTreeskin and example. Note that
third party templates from 1.0.x will not work anymore and must be
updated as well!v1.0.1 (2004-01-16) – ‘Nibbler’Added last remaining pieces for unit testsUpdated documentationRounded some rough edges in the skinIntegrated it into the Zope3 distribution below thezope.productspackagev1.0 (2003-11-24) – ‘Lur’Ported to Zope 3Renamed it to ‘statictree’Much more unit testsAdded filter functionalityProvided sample implementations as well as an alternate
rotterdam-like skin using the static tree |
zope.app.twisted | This package integrates the Twisted HTTP and FTP server into a Zope 3
application setup. It also defines the script skeleton for a classic Zope 3
application.Detailed DocumentationZope 3 Application Server SupportThis package is responsible for initializing and starting the servers that
will provide access to the Zope 3 application. This package is heavily
twisted-depedent, though some pieces can be reused to bring up the Zope 3
application server in other environemnts.Server TypesZope 3 needs to support many server types – HTTP, FTP, HTTP with postmortem
debugging, etc. All of them are registered asIServerTypeutilities in
ZCML. This allows developers to easily develop and register new servers for
Zope 3.ServerTypeis an implementation ofIServerTypethat is specific to the
standard Twisted servers.. The constructor ofServerTypetakes three
arguments: the factory that will create a TwistedIServerFactoryobject
and the default port and IP to which to bind the server.Thefactoryargument should be a callable expecting one argument, the ZODB
instance. It is up to the factory, to implement the necessary glue between the
server and the application:>>> class TwistedServerFactoryStub(object):
... def doStart(self): pass>>> def factory(db):
... print 'ZODB: %s' %db
... return TwistedServerFactoryStub()For the other two constructor arguments ofServerType, thedefaultPortargument specifies the default TCP port number for the server. ThedefaultIPargument specifies the network interface for listening on. You
can specify the network interface IP address, or an empty string if you want
to listen on all interfaces.We are now ready to instantiate the server type:>>> from zope.app.twisted.server import ServerType
>>> st = ServerType(factory, defaultPort=8080)and let’s make sure it really implements the promised interface:>>> from zope.interface.verify import verifyObject
>>> from zope.app.twisted.interfaces import IServerType
>>> verifyObject(IServerType, st)
TrueA server type is then registered as a named utility. These utilities are used
while interpreting<server>sections ofzope.confto create instances of
servers listening on a specific port.When you create an instance of a server using thecreate()method of the
server type, you need to tell it an identifying name and a the ZODB database
object. The IP address, port and backlog count can be optionally passed to the
method.>>> db = 'my database'
>>> server = st.create('Example-HTTP', db, port=0)
ZODB: my database
>>> server #doctest:+ELLIPSIS
<zope.app.twisted.server.ZopeTCPServer instance at ...>As you can see the server type creates a Zope-specific TCP server, which is
simply a standardtwisted.internet.TCPServerthat creates a log entry upon
startup.>>> server.startService()
>>> print log.getvalue()
-- Example-HTTP Server started.
Hostname: localhost
Port: 0You can, of course, create multiple instances of the same server type, and
bind them to different ports.>>> server2 = st.create('Example-HTTP-2', db, port=0)
ZODB: my database>>> server2.startService()
>>> print log.getvalue()
-- Example-HTTP Server started.
Hostname: localhost
Port: 0
-- Example-HTTP-2 Server started.
Hostname: localhost
Port: 0A special type of server type is the SSL server type; it requires some
additional information (private key path, certificate path, and TLS flag) to
start up the server. The setup will only work, if OpenSSL is installed:# >>> from zope.app.twisted.server import SSLServerType
# >>> ssl_st = SSLServerType(factory, defaultPort=8443)
#
# >>> ssl_server = ssl_st.create(‘Example-HTTPS’, db,
# … ‘server.pem’, ‘server.pem’)
# ZODB: my database
# >>> ssl_server #doctest:+ELLIPSIS
# <zope.app.twisted.server.ZopeSSLServer instance at …>Server FactoriesNow, of course we do not hardwire the setup of actual servers in
Python. Instead, we are using ZConfig to setup the servers. Unfortunately that
means that we need yet another abstraction layer to setup the
servers. ZConfig-based configuration code creates so calledServerFactoryandSSLServerFactoryobjects that then use the server types to create the
servers.>>> from zope.interface import implements
>>> from zope.app.twisted.interfaces import IServerType
>>> class MyServerType:
... implements(IServerType)
... def create(self, name, db,
... port='unknown', ip='', backlog=50):
... if not ip:
... ip = '*' # listen on all interfaces
... return ('%s server on %s:%d, registered with %s, backlog %d'
... % (name, ip, port, db, backlog))>>> from zope.app.testing import ztapi
>>> ztapi.provideUtility(IServerType, MyServerType(), name='HTTP')
>>> ztapi.provideUtility(IServerType, MyServerType(), name='FTP')ServerFactoryis used to hook into ZConfig and create instances of servers
specified inzope.conf. It gets asectionargument that contains settings
specified in a ZConfig<server>section.>>> class ServerSectionStub:
... type = 'HTTP'
... address = ('', 8080)
... backlog = 30
>>> my_section = ServerSectionStub()>>> from zope.app.twisted.server import ServerFactory
>>> sf = ServerFactory(my_section)The server factory object knows how to create a server, given a ZODB database
object. The name is a combination of type, ip, and port, so that the Twisted
code can distinguish between the different HTTP servers.>>> db = 'my db'
>>> print sf.create(db)
HTTP:localhost:8080 server on *:8080, registered with my db, backlog 30It can create more than one, using different ports.>>> my_section.address = ('', 8081)
>>> sf = ServerFactory(my_section)
>>> print sf.create(db)
HTTP:localhost:8081 server on *:8081, registered with my db, backlog 30The settings should actually work with FTP as well.>>> my_section.type = 'FTP'
>>> my_section.address = ('127.0.0.1', 8021)
>>> sf = ServerFactory(my_section)
>>> print sf.create(db)
FTP:127.0.0.1:8021 server on 127.0.0.1:8021, registered with my db, backlog 30CHANGES3.5.0 (2009-07-24)Update tests to work with latest packages.3.4.2 (2009-01-27)Fix tests. Remove unused code.Add zope.testbrowser to testing dependencies for ZEO tests.Remove unneeded dependency on ZODB3.Remove dependency on zope.app.zapi, substituting its uses with direct
imports.Change “cheeseshop” to “pypi” in the package homepage.3.4.1 (2008-02-02)Fix of 599 error on conflict error in request
see:http://mail.zope.org/pipermail/zope-dev/2008-January/030844.html3.4.0 (2007-10-27)Initial release independent of the main Zope tree. |