code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
from __future__ import print_function import os import re import smtplib import optparse try: from email.MIMEText import MIMEText except ImportError: # pragma: nocover from email.mime.text import MIMEText def matches(string, list_of_regexes): """Check whether a string matches any of a list of regexes. >>> matches('foo', map(re.compile, ['x', 'o'])) True >>> matches('foo', map(re.compile, ['x', 'f$'])) False >>> matches('foo', []) False """ return any(regex.search(string) for regex in list_of_regexes) def filter_files(files, include=(), exclude=()): """Filters a file list by considering only the include patterns, then excluding exclude patterns. Patterns are regular expressions. Examples: >>> filter_files(['ivija.food', 'ivija.food.tests', 'other.ivija'], ... include=['^ivija'], exclude=['tests']) ['ivija.food'] >>> filter_files(['ivija.food', 'ivija.food.tests', 'other.ivija'], ... exclude=['tests']) ['ivija.food', 'other.ivija'] >>> filter_files(['ivija.food', 'ivija.food.tests', 'other.ivija'], ... include=['^ivija']) ['ivija.food', 'ivija.food.tests'] >>> filter_files(['ivija.food', 'ivija.food.tests', 'other.ivija']) ['ivija.food', 'ivija.food.tests', 'other.ivija'] """ if not include: include = ['.'] # include everything by default if not exclude: exclude = [] # exclude nothing by default include = list(map(re.compile, include)) exclude = list(map(re.compile, exclude)) return [fn for fn in files if matches(fn, include) and not matches(fn, exclude)] def find_coverage_files(dir): """Find all test coverage files in a given directory. The files are expected to end in '.cover'. Weird filenames produced by tracing "fake" code (like '<doctest ...>') are ignored. """ return [fn for fn in os.listdir(dir) if fn.endswith('.cover') and not fn.startswith('<')] def filter_coverage_files(dir, include=(), exclude=()): """Find test coverage files in a given directory matching given patterns. The files are expected to end in '.cover'. Weird filenames produced by tracing "fake" code (like '<doctest ...>') are ignored. Include/exclude patterns are regular expressions. Include patterns are considered first, then the results are trimmed by the exclude patterns. """ return filter_files(find_coverage_files(dir), include, exclude) def warn(filename, message): """Warn about test coverage regression. >>> warn('/tmp/z3c.somepkg.cover', '5 untested lines, ouch!') z3c.somepkg: 5 untested lines, ouch! """ module = strip(os.path.basename(filename), '.cover') print('%s: %s' % (module, message)) def compare_dirs(olddir, newdir, include=(), exclude=(), warn=warn): """Compare two directories of coverage files.""" old_coverage_files = filter_coverage_files(olddir, include, exclude) new_coverage_files = filter_coverage_files(newdir, include, exclude) old_coverage_set = set(old_coverage_files) for fn in sorted(new_coverage_files): if fn in old_coverage_set: compare_file(os.path.join(olddir, fn), os.path.join(newdir, fn), warn=warn) else: new_file(os.path.join(newdir, fn), warn=warn) def count_coverage(filename): """Count the number of covered and uncovered lines in a file.""" covered = uncovered = 0 with open(filename) as file: for line in file: if line.startswith('>>>>>>'): uncovered += 1 elif len(line) >= 7 and not line.startswith(' ' * 7): covered += 1 return covered, uncovered def compare_file(oldfile, newfile, warn=warn): """Compare two coverage files.""" old_covered, old_uncovered = count_coverage(oldfile) new_covered, new_uncovered = count_coverage(newfile) if new_uncovered > old_uncovered: increase = new_uncovered - old_uncovered warn(newfile, "%d new lines of untested code" % increase) def new_file(newfile, warn=warn): """Look for uncovered lines in a new coverage file.""" covered, uncovered = count_coverage(newfile) if uncovered: total = covered + uncovered msg = "new file with %d lines of untested code (out of %d)" % ( uncovered, total) warn(newfile, msg) def strip(string, suffix): """Strip a suffix from a string if it exists: >>> strip('go bar a foobar', 'bar') 'go bar a foo' >>> strip('go bar a foobar', 'baz') 'go bar a foobar' >>> strip('allofit', 'allofit') '' """ if string.endswith(suffix): string = string[:-len(suffix)] return string def urljoin(base, *suburls): """Join base URL and zero or more subURLs. This function is best described by examples: >>> urljoin('http://example.com') 'http://example.com/' >>> urljoin('http://example.com/') 'http://example.com/' >>> urljoin('http://example.com', 'a', 'b/c', 'd') 'http://example.com/a/b/c/d' >>> urljoin('http://example.com/', 'a', 'b/c', 'd') 'http://example.com/a/b/c/d' >>> urljoin('http://example.com/a', 'b/c', 'd') 'http://example.com/a/b/c/d' >>> urljoin('http://example.com/a/', 'b/c', 'd') 'http://example.com/a/b/c/d' SubURLs should not contain trailing or leading slashes (with one exception: the last subURL may have a trailing slash). SubURLs should not be empty. """ if not base.endswith('/'): base += '/' return base + '/'.join(suburls) class MailSender(object): """Send emails over SMTP""" connection_class = smtplib.SMTP def __init__(self, smtp_host='localhost', smtp_port=25): self.smtp_host = smtp_host self.smtp_port = smtp_port def send_email(self, from_addr, to_addr, subject, body): """Send an email.""" # Note that this won't handle non-ASCII characters correctly. # See http://mg.pov.lt/blog/unicode-emails-in-python.html msg = MIMEText(body) if from_addr: msg['From'] = from_addr if to_addr: msg['To'] = to_addr msg['Subject'] = subject smtp = self.connection_class(self.smtp_host, self.smtp_port) smtp.sendmail(from_addr, to_addr, msg.as_string()) smtp.quit() class ReportPrinter(object): """Reporter to sys.stdout.""" def __init__(self, web_url=None): self.web_url = web_url def warn(self, filename, message): """Warn about test coverage regression.""" module = strip(os.path.basename(filename), '.cover') print('%s: %s' % (module, message)) if self.web_url: url = urljoin(self.web_url, module + '.html') print('See ' + url) print('') class ReportEmailer(object): """Warning collector and emailer.""" def __init__(self, from_addr, to_addr, subject, web_url=None, mailer=None): if not mailer: mailer = MailSender() self.from_addr = from_addr self.to_addr = to_addr self.subject = subject self.web_url = web_url self.mailer = mailer self.warnings = [] def warn(self, filename, message): """Warn about test coverage regression.""" module = strip(os.path.basename(filename), '.cover') self.warnings.append('%s: %s' % (module, message)) if self.web_url: url = urljoin(self.web_url, module + '.html') self.warnings.append('See ' + url + '\n') def send(self): """Send the warnings (if any).""" if self.warnings: body = '\n'.join(self.warnings) self.mailer.send_email(self.from_addr, self.to_addr, self.subject, body) def main(): """Parse command line arguments and do stuff.""" parser = optparse.OptionParser("usage: %prog [options] olddir newdir") parser.add_option('--include', metavar='REGEX', help='only consider files matching REGEX', action='append') parser.add_option('--exclude', metavar='REGEX', help='ignore files matching REGEX', action='append') parser.add_option('--email', metavar='ADDR', help='send the report to a given email address' ' (only if regressions were found)',) parser.add_option('--from', metavar='ADDR', dest='sender', help='set the email sender address') parser.add_option('--subject', metavar='SUBJECT', default='Unit test coverage regression', help='set the email subject') parser.add_option('--web-url', metavar='BASEURL', dest='web_url', help='include hyperlinks to HTML-ized coverage' ' reports at a given URL') opts, args = parser.parse_args() if len(args) != 2: parser.error("wrong number of arguments") olddir, newdir = args if opts.email: reporter = ReportEmailer( opts.sender, opts.email, opts.subject, opts.web_url) else: reporter = ReportPrinter(opts.web_url) compare_dirs(olddir, newdir, include=opts.include, exclude=opts.exclude, warn=reporter.warn) if opts.email: reporter.send() if __name__ == '__main__': main()
z3c.coverage
/z3c.coverage-2.1.0.tar.gz/z3c.coverage-2.1.0/src/z3c/coverage/coveragediff.py
coveragediff.py
===================== Test Coverage Reports ===================== The main objective of this package is to convert the text-based coverage output into an HTML coverage report. This is done by specifying the directory of the test reports and the desired output directory. Luckily we already have the text input ready: >>> import os >>> import z3c.coverage >>> inputDir = os.path.join( ... os.path.dirname(z3c.coverage.__file__), 'sampleinput') Let's create a temporary directory for the output >>> import tempfile, shutil >>> tempDir = tempfile.mkdtemp(prefix='tmp-z3c.coverage-report-') The output directory will be created if it doesn't exist already >>> outputDir = os.path.join(tempDir, 'report') We can now create the coverage report as follows: >>> from z3c.coverage import coveragereport >>> coveragereport.main([inputDir, outputDir, '--quiet']) Looking at the output directory, we now see several files: >>> print('\n'.join(sorted(os.listdir(outputDir)))) all.html z3c.coverage.__init__.html z3c.coverage.coveragediff.html z3c.coverage.coveragereport.html z3c.coverage.html z3c.html Let's clean up >>> shutil.rmtree(tempDir) coverage.py support ~~~~~~~~~~~~~~~~~~~ We also support coverage reports generated by coverage.py >>> inputFile = os.path.join( ... os.path.dirname(z3c.coverage.__file__), 'sampleinput.coverage') >>> from z3c.coverage import coveragereport >>> coveragereport.main([ ... inputFile, outputDir, '-q', ... '--path-alias=/home/mg/src/zopefoundation/z3c.coverage/src/z3c/coverage=%s' ... % os.path.dirname(z3c.coverage.__file__), ... '--strip-prefix=%s' ... % os.path.realpath(os.path.dirname(os.path.dirname( ... os.path.dirname(z3c.coverage.__file__)))), ... ]) >>> print('\n'.join(sorted(os.listdir(outputDir)))) all.html z3c.coverage.__init__.html z3c.coverage.coveragediff.html z3c.coverage.coveragereport.html z3c.coverage.html z3c.html It also works without the --strip-prefix option, but the paths would be uglier and not necessarily fixed (e.g. src/z3c/coverage/... versus .tox/lib/python2.X/site/packages/z3c/coverage/..., depending on how you run the tests). >>> coveragereport.main([ ... inputFile, outputDir, '-q', ... '--path-alias=/home/mg/src/zopefoundation/z3c.coverage/src/z3c/coverage=%s' ... % os.path.dirname(z3c.coverage.__file__), ... ]) `coveragereport.py` is a script ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For convenience you can download the ``coveragereport.py`` module and run it as a script: >>> import sys >>> sys.argv = ['coveragereport', inputDir, outputDir, '--quiet'] >>> script_file = os.path.join( ... z3c.coverage.__path__[0], 'coveragereport.py') >>> with open(script_file) as f: ... code = compile(f.read(), script_file, 'exec') ... exec(code, dict(__name__='__main__')) Let's clean up >>> shutil.rmtree(tempDir)
z3c.coverage
/z3c.coverage-2.1.0.tar.gz/z3c.coverage-2.1.0/src/z3c/coverage/README.txt
README.txt
Zope Public License (ZPL) Version 2.1 A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
z3c.csvvocabulary
/z3c.csvvocabulary-3.0.tar.gz/z3c.csvvocabulary-3.0/LICENSE.rst
LICENSE.rst
============== CSV Vocabulary ============== This package provides a very simple vocabulary implementation using CSV files. The advantage of CSV files is that they provide an external point to specify data, which allows a non-developer to adjust the data themselves. >>> import z3c.csvvocabulary >>> import os.path >>> path = os.path.dirname(z3c.csvvocabulary.__file__) CSV Vocabulary -------------- The CSV Vocabulary implementation is really just a function that creates a simple vocabulary with titled terms. There is a ``sample.csv`` file in the ``data`` directory of the ``testing`` sub-package, so let's create a vocabulary from that: >>> csvfile = os.path.join(path, 'testing', 'data', 'sample.csv') >>> samples = z3c.csvvocabulary.CSVVocabulary(csvfile) >>> samples <zope.schema.vocabulary.SimpleVocabulary object at ...> >>> sorted([term.value for term in samples]) ['value1', 'value2', 'value3', 'value4', 'value5'] Let's now look at a term: >>> term1 = samples.getTerm('value1') >>> term1 <zope.schema.vocabulary.SimpleTerm object at ...> As you can see, the vocabulary automatically prefixes the value: >>> term1.value 'value1' >>> term1.token 'value1' >>> term1.title 'sample-value1' While it looks like the title is the wrong unicode string, it is really an I18n message: >>> type(term1.title) <class 'zope.i18nmessageid.message.Message'> >>> term1.title.default 'Title 1' >>> term1.title.domain 'zope' Of course, it is not always acceptable to make 'zope' the domain of the message. You can specify the message factory when initializing the vocabulary: >>> from zope.i18nmessageid import MessageFactory >>> exampleDomain = MessageFactory('example') >>> samples = z3c.csvvocabulary.CSVVocabulary(csvfile, exampleDomain) >>> term1 = samples.getTerm('value1') >>> term1.title.domain 'example' The vocabulary is designed to work with small data sets, typically choices in user interfaces. All terms are created upon initialization, so the vocabulary does not detect updates in the csv file or loads the data when needed. But as I said, this is totally okay. Encoding ```````` By default the vocabulary expects the csv file to be latin1 encoded. >>> csvfile = os.path.join(path, 'testing', 'data', 'utf-8.csv') >>> wrongEncoding = z3c.csvvocabulary.CSVVocabulary(csvfile) >>> wrongEncoding.getTerm('ae').title.default '\xc3\xa4' If you csv file has a different encoding you can specify it explicitly: >>> utf8Encoded = z3c.csvvocabulary.CSVVocabulary(csvfile, encoding='utf-8') >>> term = utf8Encoded.getTerm('ae') >>> term.title.default '\xe4' CSV Message String Extraction ----------------------------- There is a simple function in ``i18nextract.py`` that extracts all message strings from the CSV files in a particular sub-tree. Here we just want to make sure that the function completes and some dummy data from the testing package will be used: >>> basedir = os.path.dirname(path) >>> catalog = z3c.csvvocabulary.csvStrings(path, basedir) >>> pprint(catalog) {'sample-value1': [('...sample.csv', 1)], 'sample-value2': [('...sample.csv', 2)], 'sample-value3': [('...sample.csv', 3)], 'sample-value4': [('...sample.csv', 4)], 'sample-value5': [('...sample.csv', 5)], 'utf-8-ae': [('...utf-8.csv', 1)], 'utf-8-oe': [('...utf-8.csv', 2)]}
z3c.csvvocabulary
/z3c.csvvocabulary-3.0.tar.gz/z3c.csvvocabulary-3.0/src/z3c/csvvocabulary/README.rst
README.rst
Zope Public License (ZPL) Version 2.1 A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
z3c.currency
/z3c.currency-2.0-py3-none-any.whl/z3c.currency-2.0.dist-info/LICENSE.rst
LICENSE.rst
================== The Currency Field ================== The currency field is a numerical field, specifically designed to manage monetary values. >>> from z3c.currency import field, interfaces >>> price = field.Currency( ... title='Price', ... description='The price of the item.') Besides the common attributes, the currency field also provides two additional attributes, the precision and unit. The precision is intended to allow for specifying whether the value is provided whole units or 1/100th of the whole unit -- in the US dollar and cents. By default this field is set to cents: >>> price.precision is interfaces.CENTS True It can be set to be dollars: >>> price.precision = interfaces.DOLLARS >>> price.precision is interfaces.DOLLARS True For financial applications, we also sometimes needsub-cents: >>> price.precision = interfaces.SUBCENTS >>> price.precision is interfaces.SUBCENTS True Note: Is there a more "internationalized" word for the whole unit of a currency? The unit specifies the symbol of the currency used. It is also used for formatting the numerical value to a string. >>> price.unit '$' >>> price.unit = 'SEK' >>> price.unit 'SEK' Of course, both of those attributes are available as constructor arguments: >>> price = field.Currency( ... title='Price', ... description='The price of the item.', ... precision=interfaces.DOLLARS, ... unit='SEK') >>> price.precision is interfaces.DOLLARS True >>> price.unit 'SEK' Let's now have a look at the validation. First of all, the value must always be a decimal: >>> import decimal >>> price.validate(decimal.Decimal('12')) >>> price.validate(12) Traceback (most recent call last): ... z3c.currency.interfaces.WrongCurrencyType: int >>> price.validate(12.0) Traceback (most recent call last): ... z3c.currency.interfaces.WrongCurrencyType: float Also, when the precision is set to DOLLARS as it is the case here, the value must be a whole number: >>> price.validate(decimal.Decimal('12')) >>> price.validate(decimal.Decimal('12.01')) Traceback (most recent call last): ... z3c.currency.interfaces.IncorrectValuePrecision: 0 >>> price.validate(decimal.Decimal('12.00')) Traceback (most recent call last): ... z3c.currency.interfaces.IncorrectValuePrecision: 0 When the precision is set to cents, >>> price.precision = interfaces.CENTS then values only with two decimal places are accepted: >>> price.validate(decimal.Decimal('12.00')) >>> price.validate(decimal.Decimal('12')) Traceback (most recent call last): ... z3c.currency.interfaces.IncorrectValuePrecision: 1 >>> price.validate(decimal.Decimal('12.0')) Traceback (most recent call last): ... z3c.currency.interfaces.IncorrectValuePrecision: 1 If we allow sub-cents, >>> price.precision = interfaces.SUBCENTS any precision is allowed: >>> price.validate(decimal.Decimal('12.0')) >>> price.validate(decimal.Decimal('12')) >>> price.validate(decimal.Decimal('12.00001')) If the field is not required, ... >>> price.required = False let's make sure that the validation still passes. >>> price.validate(None) Note that the ``IFromUnicode`` interface is purposefully not supported: >>> price.fromUnicode Traceback (most recent call last): ... AttributeError: 'Currency' object has no attribute 'fromUnicode' ``z3c.form`` Support -------------------- This package also provides support for integration with the ``z3c.form`` package. In particular it implements a data converter from the ``Currency`` field to any widget accepting a unicode string. >>> from z3c.currency import converter >>> conv = converter.CurrencyConverter(price, None) >>> conv <DataConverter from Currency to NoneType> The converter easily produces a string from any value: >>> conv.toWidgetValue(decimal.Decimal(12)) '12' >>> conv.toWidgetValue(decimal.Decimal(1200)) '1,200' >>> conv.toWidgetValue(decimal.Decimal(-12)) '-12' >>> conv.toWidgetValue(decimal.Decimal('-12.0')) '-12.00' >>> conv.toWidgetValue(decimal.Decimal('-12.00')) '-12.00' Note that always two decimal places are printed. You can also set the precision to DOLLARS: >>> conv.field.precision = interfaces.DOLLARS >>> conv.toWidgetValue(decimal.Decimal(12)) '12' >>> conv.toWidgetValue(decimal.Decimal('12.00')) '12' Let's try sub-cents as well: >>> conv.field.precision = interfaces.SUBCENTS >>> conv.toWidgetValue(decimal.Decimal('12.00')) '12.00' >>> conv.toWidgetValue(decimal.Decimal('12')) '12' >>> conv.toWidgetValue(decimal.Decimal('12.0001')) '12.0001' If the value is missing, then handle it gracefully. >>> conv.toWidgetValue(None) '' Let's now parse a value. The parser is a little bit flexible, not only accepting the output values, ... >>> conv.field.precision = interfaces.CENTS >>> conv.toFieldValue('12') Decimal('12.00') >>> conv.toFieldValue('1,200') Decimal('1200.00') >>> conv.toFieldValue('-12') Decimal('-12.00') >>> conv.toFieldValue('-12.00') Decimal('-12.00') >>> conv.field.precision = interfaces.DOLLARS >>> conv.toFieldValue('12') Decimal('12') >>> conv.toFieldValue('12.00') Decimal('12') >>> conv.field.precision = interfaces.SUBCENTS >>> conv.toFieldValue('12') Decimal('12') >>> conv.toFieldValue('12.00') Decimal('12.00') >>> conv.toFieldValue('12.0000') Decimal('12.0000') >>> conv.toFieldValue('12.0001') Decimal('12.0001') but also other input values: >>> conv.toFieldValue('1200') Decimal('1200') If the browser sends an empty string, then handle it gracefully. >>> conv.toFieldValue('')
z3c.currency
/z3c.currency-2.0-py3-none-any.whl/z3c/currency/README.rst
README.rst
======= CHANGES ======= 2.1.1 (2014-04-07) ------------------ - Bug: FileDataGenerator used the full filename to generate the random seed. That is definitely going to break consistency/tests on someone else's system. 2.1.0 (2013-03-15) ------------------ - Switched code base to use ``random2``, so that Python 2 and 3 have the same output. No need for running different test files now. - Simplified and unified test setup. 2.0.1 (2013-02-12) ------------------ - Updated manifest to include buildout and tox configuration files. - Updated Trove classifiers. - Renamed text files from *.txt to *.rst,s o Github renders them nicely. 2.0.0 (2013-02-06) ------------------ - Feature: Support for Python 3. - Bug: Make sure that all files are closed properly. - Bug: When generating a username, make sure it does not include any special characters passed through by the first or lastname, for example "O'Dorothy". 1.0.0 (2013-02-06) ------------------ - Feature: Added tests for all data generators. - Feature: Added an ID data generator that can generate all sorts of IDs that could occur in systems. - Feature: To properly support Windows, ``consistent_hash()`` returns an integer. - Bug: The IPv4 generator ignored the seed making the generator "unstable". 0.0.3 (2008-12-03) ------------------ - Refined the seed generation further: zlib.crc32() in 32 bit Python can generate negative hashes, while 64 bit Python does not. Enforced positive hashes. - Began a test suite. 0.0.2 (2008-12-02) ------------------ - Use the crc32 function to hash random seeds so that the same random sequences are generated on both 32 bit and 64 bit builds of Python. 0.0.1 (2008-02-14) ------------------ - Initial Release
z3c.datagenerator
/z3c.datagenerator-2.1.1.zip/z3c.datagenerator-2.1.1/CHANGES.rst
CHANGES.rst
import os import shutil import sys import tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout version") parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) options, args = parser.parse_args() ###################################################################### # load/install setuptools to_reload = False try: import pkg_resources import setuptools except ImportError: ez = {} try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen # XXX use a more permanent ez_setup.py URL when available. exec(urlopen('https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py' ).read(), ez) setup_args = dict(to_dir=tmpeggs, download_delay=0) ez['use_setuptools'](**setup_args) if to_reload: reload(pkg_resources) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set cmd = [sys.executable, '-c', 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0: raise Exception( "Failed to execute command:\n%s", repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
z3c.datagenerator
/z3c.datagenerator-2.1.1.zip/z3c.datagenerator-2.1.1/bootstrap.py
bootstrap.py
=============== Data Generators =============== Data Generators are meant to create data for your application quickly. They are most useful for generating sample data. Sample Data, in turn, allows you to test your application with much more realistic data volumes and is considered for some development groups as essential as tests themselves. An essential part of this package is a consistent hash generator. Verify its output. >>> from z3c.datagenerator import generator >>> generator.consistent_hash('seed') == 1149756166 True >>> generator.consistent_hash('') == 0 True >>> generator.consistent_hash('0') == 4108050209 True Generic Generators ================== Date Generator -------------- This generator creates a date from a given range: >>> import datetime >>> gen = generator.DateDataGenerator( ... 'seed', ... start=datetime.date(2012, 1, 1), ... end=datetime.date(2013, 1, 1)) >>> gen.get() datetime.date(2012, 11, 20) >>> gen.getMany(2) [datetime.date(2012, 7, 11), datetime.date(2012, 8, 26)] ID Generator ------------ This generator can create a wide variety of IDs. >>> gen = generator.IdDataGenerator( ... 'seed', ... prefix='ID', ... separator='*', ... numbers=3, ... max_value=8000) >>> gen.get() 'ID4954*7244*4825' >>> gen.getMany(3) ['ID4056*571*7689', 'ID1794*3687*5166', 'ID2585*1495*6947'] Demographics Generators ======================= This module contains a set of every day demographics data generators. >>> from z3c.datagenerator import demographics Last Name Generator ------------------- This generator creates last names from a predefined set. >>> gen = demographics.LastNameGenerator('seed') >>> gen.get() u'Lambert' >>> gen.getMany(3) [u'Oliver', u'Meyer', u'Jones'] First Name Generator -------------------- This generator creates first names from a predefined set. >>> gen = demographics.FirstNameGenerator('seed') >>> gen.get() u'Agnieszka' >>> gen.getMany(3) [u'Lisa', u'Tony', u'Madison'] SSN Generator ------------- This generator creates valid US social security numbers (SSN). >>> gen = demographics.SSNDataGenerator('seed') >>> gen.get() u'958-10-9260' >>> gen.getMany(3) [u'428-28-5754', u'975-01-6049', u'351-79-6709'] US Address Generator -------------------- This generator creates US addresses that look realistic but are completely randomly generated. Street and city names are selected from a pre-defined set. Note that you can change all the data files to generate addresses of other contries. >>> gen = demographics.AddressDataGenerator('seed') >>> gen.get() (u'440 Graymalkin Cove', u'Whitefield', u'RI', u'63293') >>> gen.getMany(1) [(u'1963 Bryn Mahr Cove', u'Ashfield', u'NV', u'20388')] You can also get all components by themselves: >>> gen.getStreet() u'1629 Clinton Terrace' >>> gen.getCity() u'Farmington' >>> gen.getState() u'PA' >>> gen.getZip() u'19658' US Phone Number Generator ------------------------- This generator creates correctly formatted US-style phone numbers. >>> gen = demographics.PhoneDataGenerator('seed') >>> gen.get() u'889-666-7726' >>> gen.getMany(3) [u'410-163-7715', u'668-898-5122', u'868-998-6087'] You can also force the area code to be "555", which is a dummy area code. >>> gen = demographics.PhoneDataGenerator('seed', True) >>> gen.get() u'555-877-6664' Network Generators ================== This module contains a set of computer and network related generators >>> from z3c.datagenerator import net IPv4 Generator -------------- This generator creates valid IPv4 addresses. >>> gen = net.IPv4DataGenerator('seed') >>> gen.get() '163.085.173.022' >>> gen.getMany(3) ['108.209.065.019', '236.049.181.080', '075.110.011.122'] Username Generator ------------------ This generator creates usernames from real names. >>> gen = net.UsernameDataGenerator('seed') >>> gen.get() u'alambert' >>> gen.getMany(3) [u'loliver', u'tmeyer', u'mjones'] You can also pass in the first and last name to the generator method. >>> gen.get('Stephan', 'Richter') u'srichter' Let's change the pattern: >>> gen = net.UsernameDataGenerator( ... 'seed', u'%(firstName).s%(lastName)s.%(number)s') >>> gen.get() u'lambert.13' The available variables are: * firstName * firstInitial * lastName * lastInitial * number E-mail Generator ---------------- This generator creates properly formatted E-mail addresses with proper TLDs. >>> gen = net.EMailDataGenerator('seed') >>> gen.get() u'[email protected]' >>> gen.getMany(3) [u'[email protected]', u'[email protected]', u'[email protected]'] You can also pass in the username to the generator method. >>> gen.get('srichter') u'[email protected]'
z3c.datagenerator
/z3c.datagenerator-2.1.1.zip/z3c.datagenerator-2.1.1/src/z3c/datagenerator/README.rst
README.rst
"""Demographics Data Generators""" __docformat__ = "reStructuredText" import os import random2 as random import zope.interface from z3c.datagenerator import demographics, generator, interfaces @zope.interface.implementer(interfaces.IDataGenerator) class IPv4DataGenerator(object): """IPv4 generator.""" def __init__(self, seed): self.random = random.Random(generator.consistent_hash(seed+'ip')) def get(self): """Select a value from the values list and return it.""" return '%.3i.%.3i.%.3i.%.3i' %( self.random.randint(1, 255), self.random.randint(0, 255), self.random.randint(0, 255), self.random.randint(0, 255)) def getMany(self, number): """Select a set of values from the values list and return them.""" return [self.get() for count in range(number)] @zope.interface.implementer(interfaces.IDataGenerator) class UsernameDataGenerator(object): """Username generator.""" pattern = u'%(firstInitial)s%(lastName)s' def __init__(self, seed, pattern=None): self.random = random.Random(generator.consistent_hash(seed+'username')) self.firstNames = demographics.FirstNameGenerator(seed) self.lastNames = demographics.LastNameGenerator(seed) if pattern: self.pattern = pattern def get(self, firstName=None, lastName=None): """Select a value from the values list and return it.""" fname = firstName or self.firstNames.get() lname = lastName or self.lastNames.get() return self.pattern % { 'firstName': ''.join(c for c in fname.lower() if c.isalnum()), 'lastName': ''.join(c for c in lname.lower() if c.isalnum()), 'firstInitial': fname[0].lower(), 'lastInitial': lname[0].lower(), 'number': self.random.randint(1, 100)} def getMany(self, number): """Select a set of values from the values list and return them.""" return [self.get() for count in range(number)] @zope.interface.implementer(interfaces.IDataGenerator) class EMailDataGenerator(object): """E-Mail generator.""" wordsFile = 'words.txt' tldsFile = 'gTLD.csv' pattern = '%(uname)s@%(domain)s%(tld)s' def __init__(self, seed): self.random = random.Random(generator.consistent_hash(seed+'enail')) self.usernames = UsernameDataGenerator(seed) self.words = generator.TextDataGenerator(seed, self.wordsFile) self.tlds = generator.CSVDataGenerator(seed, self.tldsFile) def get(self, username=None): """Select a value from the values list and return it.""" return self.pattern %{ 'uname': username or self.usernames.get(), 'domain': self.words.get(), 'tld': self.tlds.get()[0]} def getMany(self, number): """Select a set of values from the values list and return them.""" return [self.get() for count in range(number)]
z3c.datagenerator
/z3c.datagenerator-2.1.1.zip/z3c.datagenerator-2.1.1/src/z3c/datagenerator/net.py
net.py
=============== Data Generators =============== :Note: This is the Python 3 version of the documentation. The random number generator changed, so that the output will differ! For now, we are using `random2` as long as we support Python 2, but once that support is dropped, the README.txt cann be replaced with this file. Data Generators are meant to create data for your application quickly. They are most useful for generating sample data. Sample Data, in turn, allows you to test your application with much more realistic data volumes and is considered for some development groups as essential as tests themselves. An essential part of this package is a consistent hash generator. Verify its output. >>> from z3c.datagenerator import generator >>> generator.consistent_hash('seed') == 1149756166 True >>> generator.consistent_hash('') == 0 True >>> generator.consistent_hash('0') == 4108050209 True Generic Generators ================== Date Generator -------------- This generator creates a date from a given range: >>> import datetime >>> gen = generator.DateDataGenerator( ... 'seed', ... start=datetime.date(2012, 1, 1), ... end=datetime.date(2013, 1, 1)) >>> gen.get() datetime.date(2012, 9, 25) >>> gen.getMany(2) [datetime.date(2012, 11, 29), datetime.date(2012, 4, 16)] ID Generator ------------ This generator can create a wide variety of IDs. >>> gen = generator.IdDataGenerator( ... 'seed', ... prefix='ID', ... separator='*', ... numbers=3, ... max_value=8000) >>> gen.get() 'ID5073*3888*7417' >>> gen.getMany(3) ['ID035*4940*3819', 'ID4152*7603*585', 'ID6058*7872*7015'] Demographics Generators ======================= This module contains a set of every day demographics data generators. >>> from z3c.datagenerator import demographics Last Name Generator ------------------- This generator creates last names from a predefined set. >>> gen = demographics.LastNameGenerator('seed') >>> gen.get() "O'Doherty" >>> gen.getMany(3) ['Black', 'Tan', 'Rivera'] First Name Generator -------------------- This generator creates first names from a predefined set. >>> gen = demographics.FirstNameGenerator('seed') >>> gen.get() 'Al' >>> gen.getMany(3) ['Amy', 'Sean', 'Malgorzata'] SSN Generator ------------- This generator creates valid US social security numbers (SSN). >>> gen = demographics.SSNDataGenerator('seed') >>> gen.get() '982-17-1631' >>> gen.getMany(3) ['508-91-7006', '122-35-9428', '914-91-0060'] US Address Generator -------------------- This generator creates US addresses that look realistic but are completely randomly generated. Street and city names are selected from a pre-defined set. Note that you can change all the data files to generate addresses of other contries. >>> gen = demographics.AddressDataGenerator('seed') >>> gen.get() ('451 Archer Lane', 'Clarksburg', 'MI', '04382') >>> gen.getMany(1) [('1970 Ninth Lane Apt. 25', 'Chatham', 'MO', '48781')] You can also get all components by themselves: >>> gen.getStreet() '82 Morton Circle' >>> gen.getCity() 'Maynard' >>> gen.getState() 'VT' >>> gen.getZip() '60332' US Phone Number Generator ------------------------- This generator creates correctly formatted US-style phone numbers. >>> gen = demographics.PhoneDataGenerator('seed') >>> gen.get() '998-100-5657' >>> gen.getMany(3) ['651-167-3489', '890-004-8393', '172-875-9973'] You can also force the area code to be "555", which is a dummy area code. >>> gen = demographics.PhoneDataGenerator('seed', True) >>> gen.get() '555-899-1588' Network Generators ================== This module contains a set of computer and network related generators >>> from z3c.datagenerator import net IPv4 Generator -------------- This generator creates valid IPv4 addresses. >>> gen = net.IPv4DataGenerator('seed') >>> gen.get() '163.128.170.133' >>> gen.getMany(3) ['174.045.216.212', '210.131.039.157', '237.098.199.244'] Username Generator ------------------ This generator creates usernames from real names. >>> gen = net.UsernameDataGenerator('seed') >>> gen.get() 'aodoherty' >>> gen.getMany(3) ['ablack', 'stan', 'mrivera'] You can also pass in the first and last name to the generator method. >>> gen.get('Stephan', 'Richter') 'srichter' Let's change the pattern: >>> gen = net.UsernameDataGenerator( ... 'seed', u'%(firstName).s%(lastName)s.%(number)s') >>> gen.get() 'odoherty.16' The available variables are: * firstName * firstInitial * lastName * lastInitial * number E-mail Generator ---------------- This generator creates properly formatted E-mail addresses with proper TLDs. >>> gen = net.EMailDataGenerator('seed') >>> gen.get() '[email protected]' >>> gen.getMany(3) ['[email protected]', '[email protected]', '[email protected]'] You can also pass in the username to the generator method. >>> gen.get('srichter') '[email protected]'
z3c.datagenerator
/z3c.datagenerator-2.1.1.zip/z3c.datagenerator-2.1.1/src/z3c/datagenerator/README3.rst
README3.rst
"""Demographics Data Generators""" __docformat__ = "reStructuredText" import io import os import random2 as random import zope.interface from z3c.datagenerator import generator class LastNameGenerator(generator.TextDataGenerator): """Last Name Generator""" def __init__(self, seed): super(LastNameGenerator, self).__init__(seed, 'lastnames.txt') class FirstNameGenerator(generator.TextDataGenerator): """First Name Generator""" def __init__(self, seed): super(FirstNameGenerator, self).__init__(seed, 'firstnames.txt') class SSNDataGenerator(object): """A social security data generator.""" def __init__(self, seed): self.random = random.Random(generator.consistent_hash(seed+'ssn')) def get(self): """Compute a social security number.""" randint = self.random.randint return u'%.3i-%.2i-%.4i' %( randint(1, 999), randint(1, 99), randint(1, 9999)) def getMany(self, number): """Select a set of values from the values list and return them.""" return [self.get() for count in range(number)] class AddressDataGenerator(object): """An address data generator.""" streetNamesFile = 'us-street-names.txt' streetPostfixFile = 'us-street-postfix.txt' citiesFile = 'us-cities.txt' statesFile = 'us-states.txt' apts = True def __init__(self, seed): self.random = random.Random(generator.consistent_hash(seed+'address')) path = os.path.dirname(__file__) with io.open(os.path.join(path, self.streetNamesFile), 'r', encoding='latin-1') as file: self.streetNames = [e.strip() for e in file.readlines()] with io.open(os.path.join(path, self.streetPostfixFile), 'r', encoding='latin-1') as file: self.streetPostfix = [e.strip() for e in file.readlines()] with io.open(os.path.join(path, self.citiesFile), 'r', encoding='latin-1') as file: self.cities = [e.strip() for e in file.readlines()] with io.open(os.path.join(path, self.statesFile), 'r', encoding='latin-1') as file: self.states = [e.strip() for e in file.readlines()] def getStreet(self): street = u'%i ' % self.random.randint(1, 2000) street += u'%s ' % self.random.sample(self.streetNames, 1)[0] street += self.random.sample(self.streetPostfix, 1)[0] if self.apts and self.random.random() < 0.3: street += u' Apt. %i' %self.random.randint(1, 30) return street def getCity(self): return self.random.sample(self.cities, 1)[0] def getState(self): return self.random.sample(self.states, 1)[0] def getZip(self): return u'%.5i' % self.random.randint(1000, 99999) def get(self): """Select a value from the values list and return it.""" return self.getStreet(), self.getCity(), self.getState(), self.getZip() def getMany(self, number): """Select a set of values from the values list and return them.""" return [self.get() for count in range(number)] class PhoneDataGenerator(object): """A phone data generator.""" template = u'%i-%.3i-%.4i' fivesAreaCode = False def __init__(self, seed, fivesAreaCode=False): self.random = random.Random(generator.consistent_hash(seed+'phone')) self.fivesAreaCode = fivesAreaCode def get(self): """Compute a social security number.""" randint = self.random.randint areaCode = 555 if self.fivesAreaCode else randint(100, 999) return self.template %(areaCode, randint(1, 999), randint(1, 9999)) def getMany(self, number): """Select a set of values from the values list and return them.""" return [self.get() for count in range(number)]
z3c.datagenerator
/z3c.datagenerator-2.1.1.zip/z3c.datagenerator-2.1.1/src/z3c/datagenerator/demographics.py
demographics.py
"""Data Generators""" __docformat__ = "reStructuredText" import csv import datetime import math import io import os import random2 as random import zope.interface from zlib import crc32 from z3c.datagenerator import interfaces def consistent_hash(buf): # Produce a hash of a string that behaves consistently in Python 32 and # 64 bit. The "& 0xffffffff" interprets negative numbers as positive. return crc32(buf.encode('UTF-8')) & 0xffffffff @zope.interface.implementer(interfaces.IDataGenerator) class VocabularyDataGenerator(object): """Vocabulary-based data generator""" def __init__(self, seed, vocabulary): self.random = random.Random(consistent_hash(seed)) self.vocabulary = vocabulary def get(self): """Select a value from the values list and return it.""" return self.random.sample(self.vocabulary, 1)[0].value def getMany(self, number): """Select a set of values from the values list and return them.""" return [term.value for term in self.random.sample(self.vocabulary, number)] @zope.interface.implementer(interfaces.IFileBasedGenerator) class FileDataGenerator(object): """Base functionality for a file data generator.""" path = os.path.dirname(__file__) def __init__(self, seed, filename): justname = os.path.basename(filename) self.random = random.Random(consistent_hash(seed+justname)) self.values = self._read(filename) def get(self): """Select a value from the values list and return it.""" return self.random.sample(self.values, 1)[0] def getMany(self, number): """Select a set of values from the values list and return them.""" return self.random.sample(self.values, number) class CSVDataGenerator(FileDataGenerator): """CSV-based data generator.""" def _read(self, filename): fullpath = os.path.join(self.path, filename) with io.open(fullpath, 'r', encoding='latin-1') as file: reader = csv.reader(file, delimiter=';') return [[cell for cell in row] for row in reader] class TextDataGenerator(FileDataGenerator): """Text lines based data generator.""" def _read(self, filename): fullpath = os.path.join(self.path, filename) with io.open(fullpath, 'r', encoding='latin-1') as file: return [e.strip() for e in file.readlines()] @zope.interface.implementer(interfaces.IDateDataGenerator) class DateDataGenerator(object): """A date data generator.""" def __init__(self, seed, start=None, end=None): self.random = random.Random(consistent_hash(seed+'date')) self.start = start or datetime.date(2000, 1, 1) self.end = end or datetime.date(2007, 1, 1) def get(self, start=None, end=None): """Create a new date between the start and end date.""" start = start or self.start end = end or self.end delta = end - start return start + datetime.timedelta(self.random.randint(0, delta.days)) def getMany(self, number): """Select a set of values from the values list and return them.""" return [self.get() for count in range(number)] class IdDataGenerator(object): """An ID data generator.""" prefix = 'ID' separator = '-' numbers = 4 max_value = 99 def __init__(self, seed, prefix='ID', separator='-', numbers=4, max_value=99): self.random = random.Random(consistent_hash(seed + 'id')) self.prefix = prefix self.separator = separator self.numbers = numbers self.max_value = max_value self._num_format = '%.' + str(int(math.log10(self.max_value + 1))) + 'i' def get(self): """Compute a social security number.""" randint = self.random.randint value = self.prefix value += self.separator.join( self._num_format % randint(0, self.max_value) for idx in range(self.numbers)) return value def getMany(self, number): """Select a set of values from the values list and return them.""" return [self.get() for count in range(number)]
z3c.datagenerator
/z3c.datagenerator-2.1.1.zip/z3c.datagenerator-2.1.1/src/z3c/datagenerator/generator.py
generator.py
__docformat__ = 'restructuredtext' import urlparse from zope import interface from zope import component import zope.publisher.interfaces.http from zope.copypastemove.interfaces import IObjectCopier, IObjectMover from zope.traversing.api import traverse, getRoot from zope.traversing.interfaces import TraversalError from zope.traversing.browser import absoluteURL from zope.app.publication.http import MethodNotAllowed import z3c.dav.interfaces class Base(object): component.adapts(interface.Interface, zope.publisher.interfaces.http.IHTTPRequest) def __init__(self, context, request): self.context = context self.request = request def getOverwrite(self): overwrite = self.request.getHeader("overwrite", "t").lower().strip() if overwrite == "t": overwrite = True elif overwrite == "f": overwrite = False else: raise z3c.dav.interfaces.BadRequest( self.request, message = u"Invalid overwrite header") return overwrite def getDestinationPath(self): dest = self.request.getHeader("destination", None) while dest and dest[-1] == "/": dest = dest[:-1] if not dest: raise z3c.dav.interfaces.BadRequest( self.request, message = u"No `destination` header sent.") scheme, location, destpath, query, fragment = urlparse.urlsplit(dest) # XXX - this is likely to break under virtual hosting. if location and self.request.get("HTTP_HOST", None) is not None: if location.split("@", 1)[-1] != self.request.get("HTTP_HOST"): # This may occur when the destination is on another # server, repository or URL namespace. Either the source # namespace does not support copying to the destination # namespace, or the destination namespace refuses to accept # the resource. The client may wish to try GET/PUT and # PROPFIND/PROPPATCH instead. raise z3c.dav.interfaces.BadGateway( self.context, self.request) return destpath def getDestinationNameAndParentObject(self): """Returns a tuple for destionation name, the parent folder object and a boolean flag indicating wheater the the destinatin object will have to be created or not. """ destpath = self.getDestinationPath() try: destob = traverse(getRoot(self.context), destpath) except TraversalError: destob = None overwrite = self.getOverwrite() parentpath = destpath.split('/') destname = parentpath.pop() try: parent = traverse(getRoot(self.context), parentpath) except TraversalError: raise z3c.dav.interfaces.ConflictError( self.context, message = u"Destination resource has no parent") if destob is not None and not overwrite: raise z3c.dav.interfaces.PreconditionFailed( self.context, message = "destination exists and OverWrite header is F") elif destob is not None and destob == self.context: raise z3c.dav.interfaces.ForbiddenError( self.context, message = "destionation and source objects are the same") elif destob is not None: del parent[destname] return destname, destob, parent class COPY(Base): """COPY handler for all objects.""" def COPY(self): copier = IObjectCopier(self.context, None) if copier is None or not copier.copyable(): raise MethodNotAllowed(self.context, self.request) # get the destination destname, destob, parent = self.getDestinationNameAndParentObject() if not copier.copyableTo(parent, destname): # Conflict raise z3c.dav.interfaces.ConflictError( self.context, message = u"can not copy to the destionation folder") newdestname = copier.copyTo(parent, destname) if destob is not None: self.request.response.setStatus(204) else: self.request.response.setStatus(201) self.request.response.setHeader( "Location", absoluteURL(parent[newdestname], self.request)) return "" class MOVE(Base): """MOVE handler for all objects.""" def MOVE(self): mover = IObjectMover(self.context, None) if mover is None or not mover.moveable(): raise MethodNotAllowed(self.context, self.request) # get the destination destname, destob, parent = self.getDestinationNameAndParentObject() if not mover.moveableTo(parent, destname): raise z3c.dav.interfaces.ConflictError( self.context, message = u"can not copy to the destionation folder") newdestname = mover.moveTo(parent, destname) if destob is not None: self.request.response.setStatus(204) else: self.request.response.setStatus(201) self.request.response.setHeader( "Location", absoluteURL(parent[newdestname], self.request)) return ""
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/copymove.py
copymove.py
__docformat__ = 'restructuredtext' import UserDict from zope import interface from zope.interface.interfaces import IInterface from zope.interface.common.interfaces import IException from zope.interface.common.mapping import IMapping from zope.interface.common.sequence import IFiniteSequence from zope import schema from zope.schema.interfaces import IField from zope.component.interfaces import IView from zope.publisher.interfaces.http import IHTTPRequest, IHTTPResponse from zope.app.publication.interfaces import IRequestFactory ################################################################################ # # Common WebDAV specific errors # ################################################################################ class IBadRequest(IException): """ Some information passed in the request is in invalid. """ request = interface.Attribute("""The request in which the error occured.""") message = interface.Attribute("""Message to send back to the user.""") class BadRequest(Exception): interface.implements(IBadRequest) def __init__(self, request, message = None): self.request = request self.message = message def __str__(self): return "%r, %r" %(self.request, self.message) class IUnsupportedMediaType(IException): """ Unsupported media type. """ context = interface.Attribute(""" """) message = interface.Attribute(""" """) class UnsupportedMediaType(Exception): interface.implements(IUnsupportedMediaType) def __init__(self, context, message = u""): self.context = context self.message = message def __str__(self): return "%r, %r" %(self.context, self.message) class IBadGateway(IException): """ The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request. """ context = interface.Attribute(""" """) request = interface.Attribute(""" """) class BadGateway(Exception): interface.implements(IBadGateway) def __init__(self, context, request): self.context = context self.request = request def __str__(self): return "%r, %r" %(self.context, self.request) class IDAVException(IException): """ Base interface for a common set of exceptions that should be raised to inform the client that something has gone a bit to the left. """ resource = interface.Attribute(""" Possible resource on which this error was raised. """) ## XXX - this attribute was added has an after-thought. It currently ## isn't being used and has such it properly should be removed. propertyname = interface.Attribute(""" Possible property name for which the error applies. """) message = interface.Attribute(""" Human readable message detailing what went wrong. """) class DAVException(Exception): def __init__(self, resource, propertyname = None, message = None): self.resource = resource self.propertyname = propertyname self.message = message def __str__(self): return self.message class IConflictError(IDAVException): """ The client has provided a value whose semantics are not appropriate for current state of the resource. """ class ConflictError(DAVException): interface.implements(IConflictError) class IForbiddenError(IDAVException): """ The client, for reasons the server chooses not to specify, cannot alter the resource. """ class ForbiddenError(DAVException): interface.implements(IForbiddenError) class IUnprocessableError(IDAVException): """ The entity body couldn't be parsed or is invalid. """ class UnprocessableError(DAVException): interface.implements(IUnprocessableError) # XXX - PropertyNotFound should go away and instead we should # reuse the NotFound exception class IPropertyNotFound(IDAVException): """ The requested property was not found. """ class PropertyNotFound(DAVException): interface.implements(IPropertyNotFound) class IPreconditionFailed(IDAVException): """ Some condition header failed to evalute to True. """ class PreconditionFailed(DAVException): interface.implements(IPreconditionFailed) class IFailedDependency(IDAVException): """ Method could not be performed on the resource because the requested action depended on another action and that action failed. """ class FailedDependency(DAVException): interface.implements(IFailedDependency) class IAlreadyLocked(IDAVException): """ The resource is already locked. """ class AlreadyLocked(Exception): interface.implements(IAlreadyLocked) def __init__(self, context, message = None): self.resource = context self.propertyname = None self.message = None def __str__(self): # This stops zope.app.error.error from failing in getPrintable return "%r: %r" %(self.resource, self.message) class IWebDAVErrors(IFiniteSequence, IException): """ List-like container of all exceptions that occured during the process of a request. All the exceptions should be viewed and returned to the client via a multi-status response. """ def append(error): """ Append a error to the collection of errors. """ class WebDAVErrors(Exception): """ Collect has many errors has we can and then provide a view of all the errors to the user. """ interface.implements(IWebDAVErrors) def __init__(self, context, errors = ()): Exception.__init__(self) self.errors = errors self.context = context def append(self, error): self.errors += (error,) def __len__(self): return len(self.errors) def __iter__(self): return iter(self.errors) def __getitem__(self, index): return self.errors[index] class IWebDAVPropstatErrors(IMapping, IException): """ Exception containing a mapping of property names to exceptions. This is used to collect all the exceptions that occured when modifying the properties on a resource. """ context = interface.Attribute(""" The context on which all the properties are defined. """) class WebDAVPropstatErrors(UserDict.IterableUserDict, Exception): interface.implements(IWebDAVPropstatErrors) def __init__(self, context): ## Allowing users to pass the list of errors into this exception ## is causing problems. This optional dictionary was remembering ## the arguements from previous functional tests. ## See the test_remove_live_prop in test_propfind. UserDict.IterableUserDict.__init__(self) Exception.__init__(self) self.context = context ################################################################################ # # WebDAV related publication interfaces. # ################################################################################ class IWebDAVMethod(interface.Interface): """ A object implementing this method is a callable object that implements one of the WebDAV specific methods. """ class IWebDAVResponse(IHTTPResponse): """ A WebDAV Response object. """ class IWebDAVRequest(IHTTPRequest): """ A WebDAV Request. This request should only be used to respond to a WebDAV specific request that contains either XML or nothing has a payload. """ xmlDataSource = interface.Attribute(""" xml.dom.Document instance representing the input stream has an XML document. If there was no input or the input wasn't in XML then this attribute is None. """) content_type = interface.Attribute(""" A string representing the content type of the input stream without any parameters. """) class IWebDAVRequestFactory(IRequestFactory): """ WebDAV request factory. """ ################################################################################ # # WebDAV interfaces for widgets, properties and management of the widgets # and properties. # ################################################################################ class IBaseDAVWidget(IView): """ DAVWidget are views of IDAVProperty objects, generally used by PROPFIND - context is a IDAVProperty. - request is a IHTTPRequest. """ name = interface.Attribute(""" The local naem of the property. """) namespace = interface.Attribute(""" The XML namespace to which the property belongs. """) class IIDAVWidget(IInterface): """ Meta-interface marker for classes that when instanciated will implement IDAVWidget. """ class IIDAVInputWidget(IInterface): """ Meta-interface marker for classes that when instanciated will implement IDAVInputWidget. """ class IDAVInputWidget(IBaseDAVWidget): """ For use with in the PROPPATCH method. """ def toFieldValue(element): """ Convert the ElementTree element to a value which can be legally assigned to the field. """ def getInputValue(): """ Return value suitable for the widget's field. The widget must return a value that can be legally assigned to its bound field or otherwise raise ``WidgetInputError``. The return value is not affected by `setRenderedValue()`. """ def hasInput(): """ Returns ``True`` if the widget has input. Input is used by the widget to calculate an 'input value', which is a value that can be legally assigned to a field. Note that the widget may return ``True``, indicating it has input, but still be unable to return a value from `getInputValue`. Use `hasValidInput` to determine whether or not `getInputValue` will return a valid value. A widget that does not have input should generally not be used to update its bound field. Values set using `setRenderedValue()` do not count as user input. A widget that has been rendered into a form which has been submitted must report that it has input. If the form containing the widget has not been submitted, the widget shall report that it has no input. """ class IDAVWidget(IBaseDAVWidget): """ For use in rendering dav properties. """ def render(): """ Render the property to a XML fragment, according to the relevent specification. """ class IDAVErrorWidget(interface.Interface): """ Widget used to render any errors that should be included in a multi-status response. """ status = interface.Attribute(""" The HTTP status code. """) errors = interface.Attribute(""" List of etree elements that is a precondition or a postcondition code. """) propstatdescription = interface.Attribute(""" Contains readable information about an error that occured and applies to all properties contained within the current propstat XML element. """) responsedescription = interface.Attribute(""" Contains readable information about an error that occured and applies to all resources contained within the current response XML element. """) ################################################################################ # # Namespace management # ################################################################################ class IDAVProperty(interface.Interface): """ Data structure that holds information about a live WebDAV property. """ __name__ = schema.ASCII( title = u"Name", description = u"Local name of the WebDAV property.", required = True) namespace = schema.URI( title = u"Namespace", description = u"WebDAV namespace to which this property belongs.", required = True) field = schema.Object( title = u"Field", description = u"""Zope schema field that defines the data of the live WebDAV property.""", schema = IField, required = True) custom_widget = schema.Object( title = u"Custom Widget", description = u"""Factory to use for widget construction. If None then a multi-adapter implementing IDAVWidget.""", default = None, schema = IIDAVWidget, required = False) custom_input_widget = schema.Object( title = u"Custom Input Widget", description = u"""Factory to use for widget construction. If None then a multi-adapter implementing IDAVInputWidget.""", default = None, schema = IIDAVInputWidget, required = False) restricted = schema.Bool( title = u"Restricted property", description = u"""If True then this property should not be included in the response to an allprop PROPFIND request.""", default = False, required = False) iface = schema.Object( title = u"Storage interface", description = u"""Interface which declares how to find, store the property""", schema = IInterface, required = True) ################################################################################ # # Application specific interfaces. # ################################################################################ class IOpaquePropertyStorage(interface.Interface): """ Declaration of an adapter that is used to store, remove and query all dead properties on a resource. """ def getAllProperties(): """ Return iterable of all IDAVProperty objects defined for the current context. """ def hasProperty(tag): """ Return boolean indicating whether the named property exists has a dead property for the current resource. """ def getProperty(tag): """ Return a IDAVProperty utility for the named property. """ def setProperty(tag, value): """ Set the value of the named property to value. """ def removeProperty(tag): """ Remove the named property from this property. """ class IDAVLockmanager(interface.Interface): """ Helper adapter for manage locks in an independent manner. Different Zope systems are going to have there own locking mechanisms for example Zope3 and CPS have two conflicting locking mechanisms. """ def islockable(): """ Return False when the current context can never be locked or locking is not support in your setup. For example in Zope3, z3c.dav.lockingutils.DAVLockmanager depends on a persistent zope.locking.interfaces.ITokenUtility utility being present and registered. If this utility can not be locked be then we can never use this implementation of IDAVLockmanager. """ def lock(scope, type, owner, duration, depth): """ Lock the current context passing in all the possible information neccessary for generating a lock token. If the context can't be locked raise an exception that has a corresponding IDAVErrorWidget implementation so that we can extract what went wrong. If `depth` has the value `infinity` and the context is a folder then recurse through all the subitems locking them has you go. Raise a AlreadyLockedError if some resource is already locked. Return the locktoken associated with the token that we just created. """ def refreshlock(timeout): """ Refresh to lock token associated with this resource. """ def unlock(locktoken): """ Find the lock token on this resource with the same locktoken as the argument and unlock it. """ def islocked(): """ Is the current context locked or not. Return True, otherwise False. """
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/interfaces.py
interfaces.py
import re import urlparse from cStringIO import StringIO import zope.component import zope.interface import zope.schema import zope.traversing.api import zope.app.http.interfaces import z3c.dav.coreproperties import z3c.dav.interfaces import z3c.conditionalviews.interfaces # Resource-Tag = "<" Simple-ref ">" resource_tag = re.compile(r"<(?P<resource>.+?)>") # Condition = ["Not"] (State-token | "[" entity-tag "]") condition = re.compile( r"(?P<notted>not)?\s*(<(?P<state_token>.*?)>|\[(?P<entity_tag>\S+?)\])+", re.I) STATE_ANNOTS = "z3c.conditionalviews.stateresults" class IStateTokens(zope.interface.Interface): schemes = zope.schema.List( title = u"State token schemes", description = \ u"List of possible state schemes producible by the system") tokens = zope.schema.List( title = u"State tokens", description = u"List of the current state tokens.") class IFStateToken(object): def __init__(self, scheme, token): self.scheme = scheme self.token = token class ListCondition(object): def __init__(self, notted = False, state_token = None, entity_tag = None): self.notted = notted self.state_token = state_token self.entity_tag = entity_tag class IFValidator(object): """ >>> import UserDict >>> import zope.interface.verify >>> import zope.publisher.interfaces.http >>> from zope.publisher.interfaces import IPublishTraverse >>> from zope.publisher.browser import TestRequest >>> from zope.traversing.interfaces import IPhysicallyLocatable >>> from zope.app.publication.zopepublication import ZopePublication >>> from zope.security.proxy import removeSecurityProxy The validator is a utility that implements the IF header conditional request as specified in the WebDAV specification. >>> validator = IFValidator() >>> zope.interface.verify.verifyObject( ... z3c.conditionalviews.interfaces.IHTTPValidator, validator) True We can only evaluate this request if the request contains an `IF` header. >>> request = TestRequest() >>> validator.evaluate(None, request, None) False >>> request = TestRequest(environ = {'IF': '(<DAV:no-lock>)'}) >>> validator.evaluate(None, request, None) True We need to set up following adapters for the validator to work. >>> class ReqAnnotation(UserDict.IterableUserDict): ... zope.interface.implements(zope.annotation.interfaces.IAnnotations) ... def __init__(self, request): ... self.data = request._environ.setdefault('annotation', {}) >>> zope.component.getGlobalSiteManager().registerAdapter( ... ReqAnnotation, (zope.publisher.interfaces.http.IHTTPRequest,)) >>> class ETag(object): ... zope.interface.implements(z3c.conditionalviews.interfaces.IETag) ... def __init__(self, context, request, view): ... pass ... etag = None ... weak = False >>> zope.component.getGlobalSiteManager().registerAdapter( ... ETag, (None, TestRequest, None)) >>> class Statetokens(object): ... zope.interface.implements(IStateTokens) ... def __init__(self, context, request, view): ... self.context = context ... schemes = ('', 'opaquetoken') ... @property ... def tokens(self): ... context = removeSecurityProxy(self.context) # ??? ... if getattr(context, '_tokens', None) is not None: ... return context._tokens ... return [] >>> zope.component.getGlobalSiteManager().registerAdapter( ... Statetokens, (None, TestRequest, None)) >>> class Demo(object): ... zope.interface.implements(IPublishTraverse) ... def __init__(self, name): ... self.__name__ = name ... self.__parent__ = None ... self.children = {} ... def add(self, value): ... self.children[value.__name__] = value ... value.__parent__ = self ... def publishTraverse(self, request, name): ... child = self.children.get(name, None) ... if child: ... return child ... raise zope.publisher.interfaces.NotFound(self, name, request) >>> class PhysicallyLocatable(object): ... zope.interface.implements(IPhysicallyLocatable) ... def __init__(self, context): ... self.context = context ... def getRoot(self): ... return root ... def getPath(self): ... return '/' + self.context.__name__ >>> zope.component.getGlobalSiteManager().registerAdapter( ... PhysicallyLocatable, (Demo,)) We store the results of the parsing of the state tokens in a dictionary structure. Its keys are the path to the object and its value is a dictionary of locktokens and whether or not the `NOT` keyword was present. >>> def getStateResults(request): ... reqannot = zope.annotation.interfaces.IAnnotations(request) ... return reqannot.get(STATE_ANNOTS, {}) Firstly nothing matches the <DAV:no-lock> state token. >>> resource = Demo('test') >>> validator.valid(resource, request, None) False >>> resource._tokens = ['test'] >>> validator.valid(resource, request, None) False The invalid status for this protocol is 412, for all methods. >>> validator.invalidStatus(resource, request, None) 412 Non-tagged lists ================ Entity tag condition -------------------- >>> ETag.etag = 'xx' >>> request = TestRequest(environ = {'IF': '(["xx"])'}) >>> validator.valid(resource, request, None) True >>> request._environ['IF'] = '(["xx"] ["yy"])' >>> validator.valid(resource, request, None) False >>> request._environ['IF'] = '(["xx"])(["yy"])' >>> validator.valid(resource, request, None) True >>> request._environ['IF'] = '(["yy"])(["xx"])' >>> validator.valid(resource, request, None) True >>> request._environ['IF'] = '([W/"xx"])' >>> validator.valid(resource, request, None) True The request object gets annotated with the results of the matching any state tokens, so that I only need to parse this data once. But since only entity tags have been passed so far the request object will not be annotated with the results of the state tokens. >>> getStateResults(request) {} Not - entity tag conditions --------------------------- >>> request = TestRequest(environ = {'IF': '(not ["xx"])'}) >>> validator.valid(resource, request, None) False >>> request._environ['IF'] = '(not ["xx"] ["yy"])' >>> validator.valid(resource, request, None) False >>> request._environ['IF'] = '(not ["xx"])(["yy"])' >>> validator.valid(resource, request, None) False >>> request._environ['IF'] = '(not ["yy"])' >>> validator.valid(resource, request, None) True >>> request._environ['IF'] = '(NOT [W/"xx"])' >>> validator.valid(resource, request, None) False >>> getStateResults(request) {} State-tokens ------------ We collect the parsed state tokens from the `IF` as we find them and store them as an annotation on the request object. >>> request = TestRequest(environ = {'IF': '(<locktoken>)'}) >>> validator.valid(resource, request, None) False >>> getStateResults(request) {'/test': {'locktoken': False}} >>> resource._tokens = ['locktoken'] >>> validator.valid(resource, request, None) True >>> getStateResults(request) {'/test': {'locktoken': False}} If there are multiple locktokens associated with a resource, we only are interested in the token that is represented in the IF header, so we only have one entry in the state results variable. >>> resource._tokens = ['locktoken', 'nolocktoken'] >>> validator.valid(resource, request, None) True >>> getStateResults(request) {'/test': {'locktoken': False}} >>> request._environ['IF'] = '(NOT <locktoken>)' >>> validator.valid(resource, request, None) False >>> getStateResults(request) {'/test': {'locktoken': True}} >>> request._environ['IF'] = '(NOT <invalidlocktoken>)' >>> validator.valid(resource, request, None) True >>> getStateResults(request) {'/test': {'invalidlocktoken': True}} Combined entity / state tokens ------------------------------ >>> request = TestRequest(environ = {'IF': '(<locktoken> ["xx"])'}) >>> validator.valid(resource, request, None) True >>> resource._tokens = ['nolocktoken'] >>> validator.valid(resource, request, None) False >>> request._environ['IF'] = '(<nolocktoken> ["xx"]) (["yy"])' >>> validator.valid(resource, request, None) True >>> request._environ['IF'] = '(<nolocktoken> ["yy"]) (["xx"])' >>> validator.valid(resource, request, None) True Now if the resource isn't locked, that is it has no state tokens associated with it, then the request must be valid. >>> resource._tokens = [] >>> request._environ['IF'] = '(<locktoken>)' >>> validator.valid(resource, request, None) True >>> getStateResults(request) {'/test': {'locktoken': False}} But we if the condition in the state token contains a state token belong to the URL scheme that we don't know about then the condition false, and in this case the header evaluation fails. >>> request._environ['IF'] = '(<DAV:no-lock>)' >>> validator.valid(resource, request, None) False Resources ========= We now need to test the situation when a resource is specified in the the `IF` header. We need to define a context here so that we can find the specified resource from the header. Make the context implement IPublishTraverse so that we know how to traverse to the next segment in the path. Setup up three content object. One is the context for validation, the second is a locked resource, and the last is the root of the site. >>> root = Demo('') >>> locked = Demo('locked') >>> root.add(locked) >>> demo = Demo('demo') >>> root.add(demo) The request needs more setup in order for the traversal to work. We need and a publication object and since our TestRequets object extends the BrowserRequest pretend that the method is `PUT` so that the traversal doesn't try and find a default view for the resource. This would require more setup. >>> request.setPublication(ZopePublication(None)) >>> request._environ['REQUEST_METHOD'] = 'PUT' Test that we can find the locked resource from the demo resource. >>> resource = validator.get_resource( ... demo, request, 'http://localhost/locked') >>> resource.__name__ 'locked' >>> resource = validator.get_resource(demo, request, '/locked') >>> resource.__name__ 'locked' Setup all the state tokens for all content objects to be their `__name__` attribute. >>> demo._tokens = ['demo'] >>> locked._tokens = ['locked'] >>> request._environ['IF'] = '<http://localhost/locked> (<demo>)' >>> validator.valid(demo, request, None) False >>> request._environ['IF'] = '<http://localhost/locked> (<locked>)' >>> validator.valid(demo, request, None) True If a specified resource does not exist then the only way for the IF header to match is for the state tokens to be `(Not <locktoken>)`. >>> request._environ['IF'] = '<http://localhost/missing> (<locked>)' >>> validator.valid(demo, request, None) True In this case when we try to match against `(Not <locked>)` but we stored state is still matched. >>> request._environ['IF'] = '<http://localhost/missing> (Not <locked>)' >>> validator.valid(demo, request, None) False >>> getStateResults(request) {'/missing': {'locked': True}} If we have specify multiple resources then we need to parse the whole `IF` header so that the state results method knows about the different resources. >>> request._environ['IF'] = '</demo> (<demo>) </locked> (<notlocked>)' >>> validator.valid(demo, request, None) True >>> getStateResults(request) {'/locked': {'notlocked': False}, '/demo': {'demo': False}} Null resources ============== >>> import zope.app.http.put When validating certain tagged-list productions we can get back zope.app.http.interfaces.INullResource objects from the get_resource method, plus the original context can be a null resource too. >>> class Demo2(Demo): ... def publishTraverse(self, request, name): ... child = self.children.get(name, None) ... if child: ... return child ... if request.method in ('PUT', 'LOCK', 'MKCOL'): ... return zope.app.http.put.NullResource(self, name) ... raise zope.publisher.interfaces.NotFound(self, name, request) >>> root2 = Demo2('') >>> locked2 = Demo2('locked') >>> root2.add(locked2) >>> demo2 = Demo2('demo') >>> root2.add(demo2) >>> class PhysicallyLocatable2(PhysicallyLocatable): ... def getRoot(self): ... return root2 >>> zope.component.getGlobalSiteManager().registerAdapter( ... PhysicallyLocatable2, (Demo2,)) Now generate a request with an IF header, and LOCK method that fails to find a resource, we get a NullResource instead of a NotFound exception. >>> request = TestRequest(environ = {'IF': '</missing> (<locked>)', ... 'REQUEST_METHOD': 'LOCK'}) >>> request.setPublication(ZopePublication(None)) >>> missingdemo2 = validator.get_resource(demo2, request, '/missing') >>> missingdemo2 = removeSecurityProxy(missingdemo2) >>> missingdemo2 #doctest:+ELLIPSIS <zope.app.http.put.NullResource object at ...> Now this request evaluates to true and we take the path from the `IF` header and store the state tokens in the request annotation against this path. >>> validator.valid(demo2, request, None) True >>> getStateResults(request) {'/missing': {'locked': False}} >>> matchesIfHeader(demo2, request) True >>> matchesIfHeader(missingdemo2, request) True The demo object is not locked so it automatically matches the if header. >>> root2._tokens = ['locked'] >>> validator.valid(demo2, request, None) True >>> getStateResults(request) {'/missing': {'locked': False}} >>> matchesIfHeader(demo2, request) True Even though the correct lock token is supplied in the `IF` header for the root2 resource, it is on for an alternative resource and the root object is not within the scope of that indirect lock token. >>> matchesIfHeader(root2, request) False >>> root2._tokens = ['otherlocktoken'] >>> validator.valid(demo2, request, None) True >>> getStateResults(request) {'/missing': {'locked': False}} >>> validator.valid(missingdemo2, request, None) True >>> matchesIfHeader(missingdemo2, request) True >>> root2._tokens = ['locked'] >>> validator.valid(missingdemo2, request, None) True When a null resource is created it if sometimes replaced by an other persistent object. If this is a PUT method then the object created should be locked with an indirect lock token, associated with the same root token as the folder, so as the matchesIfHeader method returns True. >>> demo3 = Demo('missing') >>> root2.add(demo3) >>> matchesIfHeader(demo3, request) True Invalid data ============ When the if header fails to parse then the request should default to True, but if we matched any resources / state tokens before the parse error then we should still store this. Need to clear the request annotation for these tests to run. >>> request = TestRequest(environ = {'IF': '</ddd> (hi)'}) >>> request.setPublication(ZopePublication(None)) >>> request._environ['REQUEST_METHOD'] = 'PUT' >>> validator.valid(demo, request, None) Traceback (most recent call last): ... BadRequest: <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>, "Invalid IF header: unclosed '(' list production" >>> getStateResults(request) {} The IF header parses until the list condition which is missing the angular brackets. >>> request._environ['IF'] = '</ddd> (<hi>) (there)' >>> validator.valid(demo, request, None) Traceback (most recent call last): ... BadRequest: <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>, "Invalid IF header: unclosed '(' list production" >>> getStateResults(request) {} Try what happens when there is no starting '(' for a list. >>> request._environ['IF'] = '</ddd> <hi>' >>> validator.valid(demo, request, None) Traceback (most recent call last): ... BadRequest: <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>, "Invalid IF header: unexcepted charactor found, expected a '('" >>> getStateResults(request) {} Expected a '(' in the IF header but the header was already parsed. >>> request._environ['IF'] = '</ddd> (<hi>) <hi>' >>> validator.valid(demo, request, None) Traceback (most recent call last): ... BadRequest: <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>, "Invalid IF header: unexcepted charactor found, expected a '('" >>> getStateResults(request) {} Expected a '(' in the IF header. >>> request._environ['IF'] = '</ddd> (<hi>) hi' >>> validator.valid(demo, request, None) Traceback (most recent call last): ... BadRequest: <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>, "Invalid IF header: unexcepted charactor found, expected a '('" >>> getStateResults(request) {} matchesIfHeader method ====================== Test the state of the context to see if matches the list of states supplied in the `IF` header. >>> request = TestRequest(environ = {'REQUEST_METHOD': 'PUT'}) >>> request.setPublication(ZopePublication(None)) When the resource is not locked and hence are no state tokens for the object then this method returns True >>> matchesIfHeader(root, request) True When the resource is locked, and there is no `IF` header then we haven't matched anything. >>> matchesIfHeader(demo, request) False Specifying a `DAV:no-lock` state token always causes the validation to succeed, but the locktoken is never in the header so we don't match it. >>> request._environ['IF'] = '</demo> (NOT <DAV:no-lock>)' >>> validator.valid(demo, request, None) True >>> matchesIfHeader(demo, request) False The parsed state token in the `IF` header for the demo object matches the current state token. >>> demo._tokens = ['test'] # setup the state tokens >>> request._environ['IF'] = '</demo> (<test>)' >>> validator.valid(demo, request, None) True >>> matchesIfHeader(demo, request) True The parsed state token for the demo object does not match that in the `IF` header. Note that we needed to specify the <DAV:no-lock> in order for the request to be valid. In this case we the request will be executed but there are event handlers that might call the matchesIfHeader which does return False since we don't have any locktoken. >>> request._environ['IF'] = '</demo> (<falsetest>) (NOT <DAV:no-lock>)' >>> validator.valid(demo, request, None) True >>> matchesIfHeader(demo, request) False The state token for the root object matches that in the `IF` header. And this as special meaning for any children of the root folder, if there state token is the same then we get a match. >>> root._tokens = ['roottest'] >>> request._environ['IF'] = '</> (<roottest>)' >>> validator.valid(demo, request, None) True >>> matchesIfHeader(root, request) True Demo is locked with the state token 'test' and so doesnot validate against the `IF` header. >>> matchesIfHeader(demo, request) False Two resources are specified in the `IF` header, so the root object fails to match the `IF` header whereas the demo object does match. >>> request._environ['IF'] = '</> (<falseroottest>) </demo> (<test>)' >>> validator.valid(demo, request, None) True >>> matchesIfHeader(root, request) False >>> matchesIfHeader(demo, request) True If the demo objects is for example indirectly locked against a root, and its state token appears in the `IF` header for a parent object then the demo object matches the `IF` header. >>> request._environ['IF'] = '</> (<roottest>)' >>> validator.valid(root, request, None) True >>> matchesIfHeader(root, request) True >>> matchesIfHeader(demo, request) False But if the demo object is not locked then it passes. >>> demo._tokens = ['roottest'] >>> validator.valid(demo, request, None) True >>> matchesIfHeader(root, request) True >>> matchesIfHeader(demo, request) True >>> root._tokens = ['notroottest'] >>> matchesIfHeader(root, request) False >>> matchesIfHeader(demo, request) True Cleanup ======= >>> zope.component.getGlobalSiteManager().unregisterAdapter( ... ReqAnnotation, (zope.publisher.interfaces.http.IHTTPRequest,)) True >>> zope.component.getGlobalSiteManager().unregisterAdapter( ... ETag, (None, TestRequest, None)) True >>> zope.component.getGlobalSiteManager().unregisterAdapter( ... Statetokens, (None, TestRequest, None)) True >>> zope.component.getGlobalSiteManager().unregisterAdapter( ... PhysicallyLocatable, (Demo,)) True >>> zope.component.getGlobalSiteManager().unregisterAdapter( ... PhysicallyLocatable2, (Demo2,)) True """ zope.interface.implements(z3c.conditionalviews.interfaces.IHTTPValidator) def evaluate(self, context, request, view): return request.getHeader("If", None) is not None def get_next_list(self, request): header = request.getHeader("If").lstrip() resource = None while header: rmatch = resource_tag.match(header) if rmatch: resource = rmatch.group("resource") header = header[rmatch.end():].lstrip() conditions = [] if not header or header[0] != "(": raise z3c.dav.interfaces.BadRequest( request, "Invalid IF header: unexcepted charactor" \ " found, expected a '('") header = header[1:].lstrip() while header: listitem = condition.match(header) if not listitem: if header[0] != ")": raise z3c.dav.interfaces.BadRequest( request, "Invalid IF header: unclosed '(' list production") header = header[1:].lstrip() break header = header[listitem.end():].lstrip() notted = bool(listitem.group("notted")) state_token = listitem.group("state_token") if state_token: state_token = IFStateToken( urlparse.urlparse(state_token)[0], state_token) entity_tag = listitem.group("entity_tag") if entity_tag: if entity_tag[:2] == "W/": entity_tag = entity_tag[2:] entity_tag = entity_tag[1:-1] conditions.append( ListCondition(notted, state_token, entity_tag)) if not conditions: break yield resource, conditions def get_resource(self, context, request, resource): environ = dict(request.environment) environ["PATH_INFO"] = urlparse.urlparse(resource)[2] req = request.__class__(StringIO(""), environ) req.setPublication(request.publication) if zope.app.http.interfaces.INullResource.providedBy(context): context = context.container root = zope.traversing.api.getRoot(context) return req.traverse(root) def valid(self, context, request, view): stateresults = {} conditionalresult = False for resource, conditions in self.get_next_list(request): if resource: try: context = self.get_resource(context, request, resource) except zope.publisher.interfaces.NotFound: # resource is still set so can't match the conditions # against the current context. context = None if context is None or \ zope.app.http.interfaces.INullResource.providedBy(context): path = resource and urlparse.urlparse(resource)[2] else: path = zope.traversing.api.getPath(context) etag = zope.component.queryMultiAdapter( (context, request, view), z3c.conditionalviews.interfaces.IETag, default = None) etag = etag and etag.etag states = zope.component.queryMultiAdapter( (context, request, view), IStateTokens, default = None) statetokens = states and states.tokens or [] listresult = True for condition in conditions: # Each List production describes a series of conditions. # The whole list evaluates to true if and only if each # condition evaluates to true. if condition.entity_tag: result = etag and \ etag == condition.entity_tag or False if condition.notted: result = not result elif condition.state_token: # Each state token is a URL. So first we test to see # if we understand the scheme of the state token # supplied in this condition. If we don't understand # the scheme then this condition evaluates to False. if states: if condition.state_token.scheme in states.schemes: # Now if the context as at least one state token # then we compare the state token supplied in this # condition by simple string comparison. if statetokens and \ condition.state_token.token not in \ statetokens: result = False else: result = True else: # Un-known state token scheme so this condition # is False. result = False else: result = True if condition.notted: result = not result if path is not None: # There is no way we can compare the state results # for this request at a later date if we don't # have a path. stateresults.setdefault(path, {}) stateresults[path][ condition.state_token.token] = condition.notted else: raise TypeError( "Either the entity_tag or the state_token" " needs to be set on a condition") listresult &= result if listresult: # Each No-tag-list and Tagged-list production may contain # one or more Lists. They evaluate to true if and only if # any of the contained lists evaluates to true. That is if # listresult is True then the tag-lists are True. conditionalresult = True # We may have states and entity tags that failed, but we don't want # to reparse the if header to figure this out. reqannot = zope.annotation.interfaces.IAnnotations(request) reqannot[STATE_ANNOTS] = stateresults return conditionalresult def invalidStatus(self, context, request, view): return 412 def updateResponse(self, context, request, view): pass # do nothing def matchesIfHeader(context, request): # Test the state of the context to see if matches the list of state # tokens supplied in the `IF` header. reqannot = zope.annotation.interfaces.IAnnotations(request) stateresults = reqannot.get(STATE_ANNOTS, {}) # We need to specify a None view here. This means that IStateTokens # adapters need to be reqistered for all views. But in some situations # it might be nice to restrict a state token adapter to specific views, # for example is the view's context is a null resource. states = zope.component.queryMultiAdapter( (context, request, None), IStateTokens, default = []) states = states and states.tokens if states: parsedstates = stateresults.get( zope.traversing.api.getPath(context), {}) while not parsedstates and \ getattr(context, "__parent__", None) is not None: # An object might be indirectly locked so we can test its parents # to see if any of there state tokens are listed in the `IF` # header. context = context.__parent__ parsedstates = stateresults.get( zope.traversing.api.getPath(context), {}) for locktoken in states: # From the spec: # Note that for the purpose of submitting the lock token the # actual form doesn't matter; what's relevant is that the # lock token appears in the If header, and that the If header # itself evaluates to true. if locktoken in parsedstates: return True return False # No state tokens so this automatically matches. return True class StateTokens(object): """ Default state tokens implementation. >>> from zope.interface.verify import verifyObject Simple resource content type. >>> class IResource(zope.interface.Interface): ... 'Simple resource.' >>> class Resource(object): ... zope.interface.implements(IResource) ... def __init__(self, name): ... self.__name__ = name >>> resource = Resource('testresource') No activelock so we have no state tokens. >>> states = StateTokens(resource, None, None) >>> verifyObject(IStateTokens, states) True >>> states.tokens [] We will register a simple active lock adapter indicating that the resource is locked. >>> class Activelock(object): ... def __init__(self, context, request): ... self.context = context ... locktoken = ['testlocktoken'] >>> class Lockdiscovery(object): ... zope.interface.implements(z3c.dav.coreproperties.IDAVLockdiscovery) ... zope.component.adapts(IResource, zope.interface.Interface) ... def __init__(self, context, request): ... self.context = context ... self.request = request ... @property ... def lockdiscovery(self): ... return [Activelock(self.context, self.request)] >>> zope.component.getGlobalSiteManager().registerAdapter(Lockdiscovery) >>> states.tokens ['testlocktoken'] Cleanup. >>> zope.component.getGlobalSiteManager().unregisterAdapter(Lockdiscovery) True """ zope.interface.implements(IStateTokens) zope.component.adapts(zope.interface.Interface, zope.publisher.interfaces.http.IHTTPRequest, zope.interface.Interface) def __init__(self, context, request, view): self.context = context self.request = request schemes = ("opaquelocktoken",) @property def tokens(self): lockdiscovery = zope.component.queryMultiAdapter( (self.context, self.request), z3c.dav.coreproperties.IDAVLockdiscovery) lockdiscovery = lockdiscovery and lockdiscovery.lockdiscovery locktokens = [] if lockdiscovery is not None: for activelock in lockdiscovery: locktokens.extend(activelock.locktoken) return locktokens class StateTokensForNullResource(object): zope.interface.implements(IStateTokens) zope.component.adapts(zope.app.http.interfaces.INullResource, zope.publisher.interfaces.http.IHTTPRequest, zope.interface.Interface) def __init__(self, context, request, view): pass schemes = ("opaquelocktoken",) tokens = []
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/ifvalidator.py
ifvalidator.py
__docformat__ = 'restructuredtext' from BTrees.OOBTree import OOBTree from zope import interface from zope import component import zope.annotation.interfaces from zope.dublincore.interfaces import IDCTimes, IDCDescriptiveProperties import z3c.dav.coreproperties class DAVDublinCore(object): """ Common data model that uses zope.dublincore package to handle the `{DAV:}creationdate`, `{DAV:}displayname` or title, and the `{DAV:}getlastmodified` WebDAV properties. >>> from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter >>> from zope.dublincore.interfaces import IWriteZopeDublinCore >>> from zope.annotation.attribute import AttributeAnnotations >>> import datetime >>> from zope.datetime import tzinfo Create some sample content >>> class Resource(object): ... pass >>> resource = Resource() With no IZopeDublinCore adapters register all properties return None. >>> adapter = DAVDublinCore(resource, None) >>> adapter.displayname is None True >>> adapter.creationdate is None True >>> adapter.displayname = u'Test File Title' Traceback (most recent call last): ... ValueError >>> adapter.getlastmodified is None True Now define the IZopeDublinCore adapters, the properties can now have non None values. >>> interface.classImplements(Resource, ... zope.annotation.interfaces.IAttributeAnnotatable) >>> component.getGlobalSiteManager().registerAdapter( ... AttributeAnnotations) >>> component.getGlobalSiteManager().registerAdapter( ... ZDCAnnotatableAdapter, provided = IWriteZopeDublinCore) >>> IWriteZopeDublinCore(resource).created = now = datetime.datetime( ... 2006, 5, 24, 0, 0, 58, tzinfo = tzinfo(60)) >>> IWriteZopeDublinCore(resource).title = u'Example Test File' >>> IWriteZopeDublinCore(resource).modified = now = datetime.datetime( ... 2006, 5, 24, 0, 0, 58, tzinfo = tzinfo(60)) >>> adapter.creationdate == now True >>> adapter.displayname u'Example Test File' >>> adapter.getlastmodified == now True >>> adapter.displayname = u'Changed Test File Title' >>> IWriteZopeDublinCore(resource).title u'Changed Test File Title' Cleanup >>> component.getGlobalSiteManager().unregisterAdapter( ... AttributeAnnotations, ... provided = zope.annotation.interfaces.IAnnotations) True >>> component.getGlobalSiteManager().unregisterAdapter( ... ZDCAnnotatableAdapter, provided = IWriteZopeDublinCore) True """ interface.implements(z3c.dav.coreproperties.IDAVCoreSchema) def __init__(self, context, request): self.context = context @property def creationdate(self): dc = IDCTimes(self.context, None) if dc is None or dc.created is None: return None return dc.created @apply def displayname(): def get(self): descproperties = IDCDescriptiveProperties(self.context, None) if descproperties is None: return None return descproperties.title def set(self, value): descproperties = IDCDescriptiveProperties(self.context, None) if descproperties is None: raise ValueError("") descproperties.title = value return property(get, set) @property def getlastmodified(self): dc = IDCTimes(self.context, None) if dc is None or dc.modified is None: return None return dc.modified _opaque_namespace_key = "z3c.dav.deadproperties.DAVOpaqueProperties" class OpaqueProperties(object): """ >>> from zope.annotation.attribute import AttributeAnnotations >>> from zope.interface.verify import verifyObject >>> component.getGlobalSiteManager().registerAdapter( ... AttributeAnnotations, ... (zope.annotation.interfaces.IAnnotatable,), ... zope.annotation.interfaces.IAnnotations) Initiial the object contains no dead properties. >>> class DemoContent(object): ... interface.implements(zope.annotation.interfaces.IAnnotatable) >>> resource = DemoContent() >>> opaqueProperties = OpaqueProperties(resource) >>> verifyObject(z3c.dav.interfaces.IOpaquePropertyStorage, ... opaqueProperties) True >>> annotations = zope.annotation.interfaces.IAnnotations(resource) >>> list(annotations) [] >>> list(opaqueProperties.getAllProperties()) [] `hasProperty` returns None since we haven't set any properties yet. >>> opaqueProperties.hasProperty('{example:}testprop') False >>> opaqueProperties.getProperty('{example:}testprop') is None True >>> annotations = zope.annotation.interfaces.IAnnotations(resource) >>> list(annotations) [] Set the testprop property >>> opaqueProperties.setProperty('{examplens:}testprop', ... '<E:testprop xmlns:E="examplens:">Test Property Value</E:testprop>') >>> annotations = zope.annotation.interfaces.IAnnotations(resource) >>> list(annotations[_opaque_namespace_key]) ['{examplens:}testprop'] >>> annotations[_opaque_namespace_key]['{examplens:}testprop'] '<E:testprop xmlns:E="examplens:">Test Property Value</E:testprop>' >>> opaqueProperties.hasProperty('{examplens:}testprop') True >>> opaqueProperties.getProperty('{examplens:}testprop') '<E:testprop xmlns:E="examplens:">Test Property Value</E:testprop>' >>> list(opaqueProperties.getAllProperties()) ['{examplens:}testprop'] >>> opaqueProperties.hasProperty('{examplens:}testbadprop') False Now we will remove the property we just set up. >>> opaqueProperties.removeProperty('{examplens:}testprop') >>> annotations = zope.annotation.interfaces.IAnnotations(resource) >>> list(annotations[_opaque_namespace_key]) [] Test multiple sets to this value. >>> opaqueProperties.setProperty('{examplens:}prop0', ... '<E:prop0 xmlns:E="examplens:">PROP0</E:prop0>') >>> opaqueProperties.setProperty('{examplens:}prop1', ... '<E:prop1 xmlns:E="examplens:">PROP1</E:prop1>') >>> opaqueProperties.setProperty('{examplens:}prop2', ... '<E:prop2 xmlns:E="examplens:">PROP2</E:prop2>') >>> list(opaqueProperties.getAllProperties()) ['{examplens:}prop0', '{examplens:}prop1', '{examplens:}prop2'] >>> opaqueProperties.removeProperty('{examplens:}prop0') >>> opaqueProperties.removeProperty('{examplens:}prop1') >>> list(opaqueProperties.getAllProperties()) ['{examplens:}prop2'] The key for the opaque storage is the ElementTree tag. The namespace part of this key can be None. >>> opaqueProperties.setProperty('prop2', ... '<E:prop2 xmlns:E="examplens:">PROP2</E:prop2>') >>> opaqueProperties.hasProperty('prop2') True >>> opaqueProperties.getProperty('prop2') '<E:prop2 xmlns:E="examplens:">PROP2</E:prop2>' >>> opaqueProperties.removeProperty('prop2') >>> list(opaqueProperties.getAllProperties()) ['{examplens:}prop2'] Cleanup this test. >>> component.getGlobalSiteManager().unregisterAdapter( ... AttributeAnnotations, ... (zope.annotation.interfaces.IAnnotatable,), ... zope.annotation.interfaces.IAnnotations) True """ interface.implements(z3c.dav.interfaces.IOpaquePropertyStorage) _annotations = None def __init__(self, context): # __parent__ must be set in order for the security to work self.__parent__ = context annotations = zope.annotation.interfaces.IAnnotations(context) oprops = annotations.get(_opaque_namespace_key) if oprops is None: self._annotations = annotations oprops = OOBTree() self._mapping = oprops def _changed(self): if self._annotations is not None: self._annotations[_opaque_namespace_key] = self._mapping self._annotations = None def getAllProperties(self): for tag in self._mapping.keys(): yield tag def hasProperty(self, tag): return tag in self._mapping def getProperty(self, tag): """Returns None.""" return self._mapping.get(tag, None) def setProperty(self, tag, value): self._mapping[tag] = value self._changed() def removeProperty(self, tag): del self._mapping[tag] self._changed()
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/adapters.py
adapters.py
__docformat__ = 'restructuredtext' from zope import component from zope.interface import implements from zope.publisher.http import HTTPResponse, HTTPRequest from zope.app.publication.http import HTTPPublication from zope.app.publication.interfaces import IRequestPublicationFactory import z3c.etree import z3c.conditionalviews import interfaces class WebDAVResponse(HTTPResponse): implements(interfaces.IWebDAVResponse) class WebDAVRequest(z3c.conditionalviews.ConditionalHTTPRequest): implements(interfaces.IWebDAVRequest) __slot__ = ( 'xmlDataSource', # holds xml.dom representation of the input stream # if it is XML otherwise it is None. 'content_type', # ) def __init__(self, body_instream, environ, reponse = None, positional = None, outstream = None): super(WebDAVRequest, self).__init__(body_instream, environ) self.xmlDataSource = None self.content_type = None def processInputs(self): """See IPublisherRequest.""" content_type = self.getHeader("content-type", None) content_type_params = None if content_type and ";" in content_type: parts = content_type.split(";", 1) content_type = parts[0].strip().lower() content_type_params = parts[1].strip() content_length = self.getHeader("content-length", 0) if content_length: content_length = int(content_length) if content_type in ("text/xml", "application/xml", None) and \ content_length > 0: etree = z3c.etree.getEngine() try: self.xmlDataSource = etree.parse(self.bodyStream).getroot() except: # There was an error parsing the body stream so this is a # bad request if the content was declared as xml if content_type is not None: raise interfaces.BadRequest( self, u"Invalid xml data passed") else: self.content_type = content_type or "application/xml" else: self.content_type = content_type def _createResponse(self): """Create a specific WebDAV response object.""" return WebDAVResponse() class WebDAVRequestFactory(object): implements(IRequestPublicationFactory) def canHandle(self, environment): return True def __call__(self): request_class = component.queryUtility( interfaces.IWebDAVRequestFactory, default = WebDAVRequest) return request_class, HTTPPublication
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/publisher.py
publisher.py
====== WebDAV ====== The *z3c.dav* package is an implementation of the WebDAV protocol for Zope3. *z3c.dav* supports the *zope.app.folder* content type, within the scope of the core RFC2518 protocol. *z3c.dav* also contains a number of components that help developers support WebDAV in their application. These components include the ability to handle WebDAV specific errors, to generate multi-status responses, and an implementation of all core WebDAV methods exist that use zope component to lookup specific adapters that perform the required action. For example locking parses the request and then looks up a IDAVLockmanager adapter to perform the locking and unlocking of objects. But if the required adapter does not exist then a `405 Method Not Allowed` response is returned to the client. Add-on packages exist to support other standard Zope3 content types and services. These include: * z3c.davapp.zopeappfile Defines a common WebDAV data model for zope.app.file.file.File, and zope.app.file.file.Image content objects. * z3c.davapp.zopefile Defines a common WebDAV data model for zope.file.file.File content objects. * z3c.davapp.zopelocking Implements wrappers around the zope.locking utility to integrate with z3c.dav. Each of these packages uses an other Zope3 package to provide the underlying functionality.
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/README.txt
README.txt
__docformat__ = 'restructuredtext' import sys from zope import interface from zope import component from zope.filerepresentation.interfaces import IReadDirectory from zope.app.error.interfaces import IErrorReportingUtility from zope.security.checker import canAccess from zope.security.interfaces import Unauthorized import z3c.etree import z3c.dav.utils import z3c.dav.interfaces import z3c.dav.properties DEFAULT_NS = "DAV:" class PROPFIND(object): """ PROPFIND handler for all objects. """ interface.implements(z3c.dav.interfaces.IWebDAVMethod) component.adapts(interface.Interface, z3c.dav.interfaces.IWebDAVRequest) def __init__(self, context, request): self.context = context self.request = request def getDepth(self): # default is infinity. return self.request.getHeader("depth", "infinity") def PROPFIND(self): if self.request.getHeader("content-length") > 0 and \ self.request.content_type not in ("text/xml", "application/xml"): raise z3c.dav.interfaces.BadRequest( self.request, message = u"PROPFIND requires a valid XML request") depth = self.getDepth() if depth not in ("0", "1", "infinity"): raise z3c.dav.interfaces.BadRequest( self.request, message = u"Invalid Depth header supplied") propertiesFactory = None extraArg = None propfind = self.request.xmlDataSource if propfind is not None: if propfind.tag != "{DAV:}propfind": raise z3c.dav.interfaces.UnprocessableError( self.context, message = u"Request is not a `propfind' XML element.") properties = propfind[0] if properties.tag == "{DAV:}propname": propertiesFactory = self.renderPropnames elif properties.tag == "{DAV:}allprop": propertiesFactory = self.renderAllProperties includes = propfind.findall("{DAV:}include") if includes: # we have "DAV:include" properties extraArg = includes[0] elif properties.tag == "{DAV:}prop": if len(properties) == 0: propertiesFactory = self.renderAllProperties else: propertiesFactory = self.renderSelectedProperties extraArg = properties else: raise z3c.dav.interfaces.UnprocessableError( self.context, message = u"Unknown propfind property element.") else: propertiesFactory = self.renderAllProperties multistatus = z3c.dav.utils.MultiStatus() responses = self.handlePropfindResource( self.context, self.request, depth, propertiesFactory, extraArg) multistatus.responses.extend(responses) etree = z3c.etree.getEngine() self.request.response.setStatus(207) self.request.response.setHeader("content-type", "application/xml") ## Is UTF-8 encoding ok here or is there a better way of doing this. return etree.tostring(multistatus(), encoding = "utf-8") def handlePropfindResource(self, ob, req, depth, \ propertiesFactory, extraArg): """ Recursive method that collects all the `response' XML elements for the current PROPFIND request. `propertiesFactory' is the method that is used to generated the `response' XML element for one resource. It takes the resource, request and `extraArg' used to pass in specific information about the properties we want to return. """ responses = [propertiesFactory(ob, req, extraArg)] if depth in ("1", "infinity"): subdepth = (depth == "1") and "0" or "infinity" readdir = IReadDirectory(ob, None) if readdir is not None and canAccess(readdir, "values"): for subob in readdir.values(): if subob is not None: responses.extend(self.handlePropfindResource( subob, req, subdepth, propertiesFactory, extraArg)) return responses def handleException(self, proptag, exc_info, request, response): error_view = component.queryMultiAdapter( (exc_info[1], request), z3c.dav.interfaces.IDAVErrorWidget) if error_view is None: ## An unexpected error occured here. This error should be ## fixed. In order to easily debug the problem we will ## log the error with the ErrorReportingUtility errUtility = component.getUtility(IErrorReportingUtility) errUtility.raising(exc_info, request) propstat = response.getPropstat(500) # Internal Server Error else: propstat = response.getPropstat(error_view.status) ## XXX - needs testing propstat.responsedescription += error_view.propstatdescription response.responsedescription += error_view.responsedescription etree = z3c.etree.getEngine() propstat.properties.append(etree.Element(proptag)) def renderPropnames(self, ob, req, ignore): """ See doc string for the renderAllProperties method. Note that we don't need to worry about the security in this method has the permissions on the storage adapters should be enough to hide any properties that users don't have permission to see. """ response = z3c.dav.utils.Response( z3c.dav.utils.getObjectURL(ob, req)) etree = z3c.etree.getEngine() for davprop, adapter in \ z3c.dav.properties.getAllProperties(ob, req): rendered_name = etree.Element(etree.QName(davprop.namespace, davprop.__name__)) response.addProperty(200, rendered_name) return response def renderAllProperties(self, ob, req, include): """ The specification says: Properties may be subject to access control. In the case of 'allprop' and 'propname' requests, if a principal does not have the right to know whether a particular property exists then the property MAY be silently excluded from the response. """ response = z3c.dav.utils.Response( z3c.dav.utils.getObjectURL(ob, req)) for davprop, adapter in \ z3c.dav.properties.getAllProperties(ob, req): isIncluded = False if include is not None and \ include.find("{%s}%s" %(davprop.namespace, davprop.__name__)) is not None: isIncluded = True elif davprop.restricted: continue try: # getWidget and render are two possible areas where the # property is silently ignored because of security concerns. davwidget = z3c.dav.properties.getWidget( davprop, adapter, req) response.addProperty(200, davwidget.render()) except Unauthorized: # Users don't have the permission to view this property and # if they didn't explicitly ask for the named property # we can silently ignore this property, pretending that it # is a restricted property.g if isIncluded: self.handleException( "{%s}%s" %(davprop.namespace, davprop.__name__), sys.exc_info(), req, response) else: # Considering that we just silently ignored this property # - log this exception with the error reporting utility # just in case this is a problem that needs sorting out. errUtility = component.getUtility(IErrorReportingUtility) errUtility.raising(sys.exc_info(), req) except Exception: self.handleException( "{%s}%s" %(davprop.namespace, davprop.__name__), sys.exc_info(), req, response) return response def renderSelectedProperties(self, ob, req, props): response = z3c.dav.utils.Response( z3c.dav.utils.getObjectURL(ob, req)) for prop in props: if z3c.dav.utils.parseEtreeTag(prop.tag)[0] == "": # A namespace which is None corresponds to when no prefix is # set, which I think is fine. raise z3c.dav.interfaces.BadRequest( self.request, u"PROPFIND with invalid namespace declaration in body") try: davprop, adapter = z3c.dav.properties.getProperty( ob, req, prop.tag, exists = True) davwidget = z3c.dav.properties.getWidget( davprop, adapter, req) propstat = response.getPropstat(200) propstat.properties.append(davwidget.render()) except Exception: self.handleException(prop.tag, sys.exc_info(), req, response) return response
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/propfind.py
propfind.py
__docformat__ = 'restructuredtext' import copy import time import random import datetime from zope import component from zope import interface import z3c.etree import z3c.dav.interfaces import z3c.dav.properties from z3c.dav.coreproperties import IDAVLockdiscovery, IDAVSupportedlock import z3c.dav.utils import ifvalidator MAXTIMEOUT = (2L ** 32) - 1 DEFAULTTIMEOUT = 12 * 60L _randGen = random.Random(time.time()) def generateLocktoken(): """ Simple utility method to generate a opaque lock token. """ return "opaquelocktoken:%s-%s-00105A989226:%.03f" % \ (_randGen.random(), _randGen.random(), time.time()) @component.adapter(interface.Interface, z3c.dav.interfaces.IWebDAVRequest) @interface.implementer(z3c.dav.interfaces.IWebDAVMethod) def LOCK(context, request): """ If we can adapt the context to a lock manager then we should be able to lock the resource. """ lockmanager = z3c.dav.interfaces.IDAVLockmanager(context, None) if lockmanager is None: return None if not lockmanager.islockable(): return None return LOCKMethod(context, request, lockmanager) class LOCKMethod(object): """ LOCK handler for all objects. """ interface.implements(z3c.dav.interfaces.IWebDAVMethod) component.adapts(interface.Interface, z3c.dav.interfaces.IWebDAVRequest) def __init__(self, context, request, lockmanager): self.context = context self.request = request self.lockmanager = lockmanager def getTimeout(self): """ Return a datetime.timedelta object representing the duration of the requested lock token. This information is passed in the `Timeout' header and corresponds to the following syntax. TimeOut = "Timeout" ":" 1#TimeType TimeType = ("Second-" DAVTimeOutVal | "Infinite") ; No LWS allowed within TimeType DAVTimeOutVal = 1*DIGIT Multiple TimeType entries are listed in order of performace so this method will return the first valid TimeType converted to a `datetime.timedelta' object or else it returns the default timeout. >>> from zope.publisher.browser import TestRequest No supplied value -> default value. >>> LOCKMethod(None, TestRequest(environ = {}), None).getTimeout() datetime.timedelta(0, 720) Infinity lock timeout is too long so revert to the default timeout. >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': 'infinity'}), ... None).getTimeout() datetime.timedelta(0, 720) >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': 'infinite'}), ... None).getTimeout() datetime.timedelta(0, 720) Specify a lock timeout of 500 seconds. >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': 'Second-500'}), ... None).getTimeout() datetime.timedelta(0, 500) Invalid and invalid second. >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': 'XXX500'}), ... None).getTimeout() Traceback (most recent call last): ... BadRequest: <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>, u'Invalid TIMEOUT header' >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': 'XXX-500'}), ... None).getTimeout() Traceback (most recent call last): ... BadRequest: <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>, u'Invalid TIMEOUT header' >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': 'Second-500x'}), ... None).getTimeout() Traceback (most recent call last): ... BadRequest: <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>, u'Invalid TIMEOUT header' Maximum timeout value. >>> timeout = 'Second-%d' %(MAXTIMEOUT + 100) >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': timeout}), ... None).getTimeout() datetime.timedelta(0, 720) >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': 'Second-3600'}), ... None).getTimeout() datetime.timedelta(0, 3600) Specify multiple timeout values. The first applicable time type value is choosen. >>> LOCKMethod(None, TestRequest( ... environ = {'TIMEOUT': 'Infinity, Second-3600'}), ... None).getTimeout() datetime.timedelta(0, 3600) >>> timeout = 'Infinity, Second-%d' %(MAXTIMEOUT + 10) >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': timeout}), ... None).getTimeout() datetime.timedelta(0, 720) >>> timeout = 'Second-1200, Second-450, Second-500' >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': timeout}), ... None).getTimeout() datetime.timedelta(0, 1200) >>> timeout = 'Second-%d, Second-450' %(MAXTIMEOUT + 10) >>> LOCKMethod(None, ... TestRequest(environ = {'TIMEOUT': timeout}), ... None).getTimeout() datetime.timedelta(0, 450) """ timeout = None header = self.request.getHeader("timeout", "infinity") for timeoutheader in header.split(","): timeoutheader = timeoutheader.strip().lower() t = timeoutheader.split("-") if len(t) == 2 and t[0].lower().lower() == "second": th = t[1] elif len(t) == 1 and (t[0] == "infinite" or t[0] == "infinity"): th = t[0] else: raise z3c.dav.interfaces.BadRequest( self.request, message = u"Invalid TIMEOUT header") if th == "infinite" or th == "infinite" or th == "infinity": timeout = None else: try: timeout = long(th) except ValueError: raise z3c.dav.interfaces.BadRequest( self.request, message = u"Invalid TIMEOUT header") if timeout is not None and timeout < MAXTIMEOUT: break # we have gotten a valid timeout we want to use. timeout = None # try again to find a valid timeout value. if timeout is None: timeout = DEFAULTTIMEOUT return datetime.timedelta(seconds = timeout) def getDepth(self): """Default is infinity. >>> from zope.publisher.browser import TestRequest >>> LOCKMethod(None, TestRequest(), None).getDepth() 'infinity' >>> LOCKMethod( ... None, TestRequest(environ = {'DEPTH': '0'}), None).getDepth() '0' >>> LOCKMethod(None, TestRequest( ... environ = {'DEPTH': 'infinity'}), None).getDepth() 'infinity' >>> LOCKMethod(None, TestRequest( ... environ = {'DEPTH': '1'}), None).getDepth() Traceback (most recent call last): ... BadRequest: <zope.publisher.browser.TestRequest instance URL=http://127.0.0.1>, u"Invalid depth header. Must be either '0' or 'infinity'" """ depth = self.request.getHeader("depth", "infinity") if depth not in ("0", "infinity"): raise z3c.dav.interfaces.BadRequest( self.request, u"Invalid depth header. Must be either '0' or 'infinity'") return depth def LOCK(self): # The Lock-Token header is not returned in the response for a # successful refresh LOCK request. refreshlock = False if self.request.xmlDataSource is None: self.handleLockRefresh() refreshlock = True else: # Body => try to lock the resource locktoken = self.handleLock() etree = z3c.etree.getEngine() davprop, adapter = z3c.dav.properties.getProperty( self.context, self.request, "{DAV:}lockdiscovery") davwidget = z3c.dav.properties.getWidget( davprop, adapter, self.request) propel = etree.Element(etree.QName("DAV:", "prop")) propel.append(davwidget.render()) self.request.response.setStatus(200) self.request.response.setHeader("Content-Type", "application/xml") if not refreshlock: self.request.response.setHeader("Lock-Token", "<%s>" % locktoken) return etree.tostring(propel) def handleLockRefresh(self): if not self.lockmanager.islocked(): raise z3c.dav.interfaces.PreconditionFailed( self.context, message = u"Context is not locked.") if not ifvalidator.matchesIfHeader(self.context, self.request): raise z3c.dav.interfaces.PreconditionFailed( self.context, message = u"Lock-Token doesn't match request uri") timeout = self.getTimeout() self.lockmanager.refreshlock(timeout) def handleLock(self): locktoken = None xmlsource = self.request.xmlDataSource if xmlsource.tag != "{DAV:}lockinfo": raise z3c.dav.interfaces.UnprocessableError( self.context, message = u"LOCK request body must be a `lockinfo' XML element") timeout = self.getTimeout() depth = self.getDepth() etree = z3c.etree.getEngine() lockscope = xmlsource.find("{DAV:}lockscope") if not lockscope: raise z3c.dav.interfaces.UnprocessableError( self.context, message = u"No `{DAV:}lockscope' XML element in request") lockscope_str = z3c.dav.utils.parseEtreeTag(lockscope[0].tag)[1] locktype = xmlsource.find("{DAV:}locktype") if not locktype: raise z3c.dav.interfaces.UnprocessableError( self.context, message = u"No `{DAV:}locktype' XML element in request") locktype_str = z3c.dav.utils.parseEtreeTag(locktype[0].tag)[1] supportedlocks = component.getMultiAdapter( (self.context, self.request), IDAVSupportedlock) for entry in supportedlocks.supportedlock: if entry.locktype[0] == locktype_str and \ entry.lockscope[0] == lockscope_str: break else: raise z3c.dav.interfaces.UnprocessableError( self.context, message = u"Unknown lock-token requested.") owner = xmlsource.find("{DAV:}owner") if owner is not None: # The owner element is optional. owner_str = etree.tostring(copy.copy(owner)) else: owner_str = None try: locktoken = self.lockmanager.lock(scope = lockscope_str, type = locktype_str, owner = owner_str, duration = timeout, depth = depth) except z3c.dav.interfaces.AlreadyLocked, error: raise z3c.dav.interfaces.WebDAVErrors(self.context, [error]) return locktoken ################################################################################ # # UNLOCK method. # ################################################################################ @component.adapter(interface.Interface, z3c.dav.interfaces.IWebDAVRequest) @interface.implementer(z3c.dav.interfaces.IWebDAVMethod) def UNLOCK(context, request): """ If we can adapt the context to a lock manager then we should be able to unlock the resource. """ lockmanager = z3c.dav.interfaces.IDAVLockmanager(context, None) if lockmanager is None: return None if not lockmanager.islockable(): return None return UNLOCKMethod(context, request, lockmanager) class UNLOCKMethod(object): """ UNLOCK handler for all objects. """ interface.implements(z3c.dav.interfaces.IWebDAVMethod) component.adapts(interface.Interface, z3c.dav.interfaces.IWebDAVRequest) def __init__(self, context, request, lockmanager): self.context = context self.request = request self.lockmanager = lockmanager def UNLOCK(self): locktoken = self.request.getHeader("lock-token", "") if len(locktoken) > 1 and locktoken[0] == "<" and locktoken[-1] == ">": locktoken = locktoken[1:-1] if not locktoken: raise z3c.dav.interfaces.BadRequest( self.request, message = u"No lock-token header supplied") activelock = component.getMultiAdapter( (self.context, self.request), IDAVLockdiscovery).lockdiscovery if not self.lockmanager.islocked() or \ locktoken not in [ltoken.locktoken[0] for ltoken in activelock]: raise z3c.dav.interfaces.ConflictError( self.context, message = "object is locked or the lock isn't" \ " in the scope the passed.") self.lockmanager.unlock(locktoken) self.request.response.setStatus(204) return ""
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/locking.py
locking.py
__docformat__ = 'restructuredtext' from zope import component from zope import interface from zope.publisher.http import status_reasons from zope.traversing.browser.interfaces import IAbsoluteURL from zope.app.container.interfaces import IReadContainer import z3c.etree class IPropstat(interface.Interface): """Helper interface to render a response XML element. """ properties = interface.Attribute("""List of etree elements that make up the prop element. """) status = interface.Attribute("""Integer status code of all the properties belonging to this propstat XML element. """) error = interface.Attribute("""List of etree elements describing the error condition of the properties within this propstat XML element. """) responsedescription = interface.Attribute("""String containing readable information about the status of all the properties belonging to this propstat element. """) def __call__(): """Render this propstat object to a etree XML element. """ class IResponse(interface.Interface): """Helper object to render a response XML element. """ href = interface.Attribute("""String representation of the HTTP URL pointing to the resource that this response element represents. """) status = interface.Attribute("""Optional integer status code for this response element. """) error = interface.Attribute("""List of etree elements describing the error conditions of all the properties contained within an instance of this response XML element. """) responsedescription = interface.Attribute("""String containing readable information about this response relative to the request or result. """) location = interface.Attribute("""The "Location" HTTP header for use with some status codes like 201 and 300. This value should be set if any of status codes contained within this response XML element are required to have a HTTP "Location" header. """) def addPropstats(status, propstat): """Add a IPropstat instance to this response. This propstat will rendered with a status of 'status'. """ def addProperty(status, element): """Add a etree.Element object to this response XML element. The property will be added within the propstat element that registered under the status code. """ def __call__(): """Render this response object to an etree element. """ class IMultiStatus(interface.Interface): responses = interface.Attribute("""List of IResponse objects that make all the responses contained within this multistatus XML element. """) responsedescription = interface.Attribute("""String containing a readable informatino about the status of all the responses belonging to this multistatus element. """) def __call__(): """Render this multistatus object to an etree element. """ ################################################################################ # # Some helper methods. Which includes: # # - makeelement(namespace, tagname, text_or_el = None) # # - makedavelement(tagname, text_or_el = None) # # - makestatuselement(status) # # - parseEtreeTag(tag) # ################################################################################ def makeelement(namespace, tagname, text_or_el = None): etree = z3c.etree.getEngine() el = etree.Element(etree.QName(namespace, tagname)) if isinstance(text_or_el, (str, unicode)): el.text = text_or_el elif text_or_el is not None: el.append(text_or_el) return el def makedavelement(tagname, text_or_el = None): """ >>> etree.tostring(makedavelement('foo')) #doctest:+XMLDATA '<foo xmlns="DAV:" />' >>> etree.tostring(makedavelement('foo', 'foo content')) #doctest:+XMLDATA '<foo xmlns="DAV:">foo content</foo>' """ return makeelement('DAV:', tagname, text_or_el) def makestatuselement(status): """ >>> etree.tostring(makestatuselement(200)) #doctest:+XMLDATA '<status xmlns="DAV:">HTTP/1.1 200 Ok</status>' >>> etree.tostring(makestatuselement(200L)) #doctest:+XMLDATA '<status xmlns="DAV:">HTTP/1.1 200 Ok</status>' Do we want this? >>> etree.tostring(makestatuselement('XXX')) #doctest:+XMLDATA '<status xmlns="DAV:">XXX</status>' """ if isinstance(status, (int, long)): status = 'HTTP/1.1 %d %s' %(status, status_reasons[status]) return makedavelement('status', status) def parseEtreeTag(tag): """Return namespace, tagname pair. >>> parseEtreeTag('{DAV:}prop') ['DAV:', 'prop'] >>> parseEtreeTag('{}prop') ['', 'prop'] >>> parseEtreeTag('prop') (None, 'prop') """ if tag[0] == "{": return tag[1:].split("}") return None, tag ################################################################################ # # Helper utilities for generating some common XML responses. # ################################################################################ class Propstat(object): """Simple propstat xml handler. >>> from zope.interface.verify import verifyObject >>> pstat = Propstat() >>> verifyObject(IPropstat, pstat) True >>> pstat.status = 200 >>> pstat.properties.append(makedavelement(u'testprop', u'Test Property')) >>> print etree.tostring(pstat()) #doctest:+XMLDATA <propstat xmlns="DAV:"> <prop> <testprop>Test Property</testprop> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> >>> pstat.properties.append(makedavelement(u'test2', u'Second Test')) >>> print etree.tostring(pstat()) #doctest:+XMLDATA <propstat xmlns="DAV:"> <prop> <testprop>Test Property</testprop> <test2>Second Test</test2> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> >>> pstat.responsedescription = u'This is ok' >>> print etree.tostring(pstat()) #doctest:+XMLDATA <propstat xmlns="DAV:"> <prop> <testprop>Test Property</testprop> <test2>Second Test</test2> </prop> <status>HTTP/1.1 200 Ok</status> <responsedescription>This is ok</responsedescription> </propstat> >>> pstat.error = [makedavelement(u'precondition-error')] >>> print etree.tostring(pstat()) #doctest:+XMLDATA <propstat xmlns="DAV:"> <prop> <testprop>Test Property</testprop> <test2>Second Test</test2> </prop> <status>HTTP/1.1 200 Ok</status> <error> <precondition-error /> </error> <responsedescription>This is ok</responsedescription> </propstat> The status must be set. >>> pstat = Propstat() >>> pstat() Traceback (most recent call last): ... ValueError: Must set status before rendering a propstat. """ interface.implements(IPropstat) def __init__(self): # etree.Element self.properties = [] # int or string self.status = None # etree.Element self.error = [] # text self.responsedescription = "" def __call__(self): if self.status is None: raise ValueError("Must set status before rendering a propstat.") propstatel = makedavelement('propstat') propel = makedavelement('prop') propstatel.append(propel) for prop in self.properties: propel.append(prop) propstatel.append(makestatuselement(self.status)) for error in self.error: propstatel.append(makedavelement('error', error)) if self.responsedescription: propstatel.append(makedavelement('responsedescription', self.responsedescription)) return propstatel class Response(object): """WebDAV response XML element We need a URL to initialize the Response object, /container is a good choice. >>> from zope.interface.verify import verifyObject >>> response = Response('/container') >>> verifyObject(IResponse, response) True >>> print etree.tostring(response()) #doctest:+XMLDATA <response xmlns="DAV:"> <href>/container</href> </response> >>> response.status = 200 >>> response.href.append('/container2') >>> print etree.tostring(response()) #doctest:+XMLDATA <response xmlns="DAV:"> <href>/container</href> <href>/container2</href> <status>HTTP/1.1 200 Ok</status> </response> The response XML element can contain a number of Propstat elements organized by status code. >>> response = Response('/container') >>> pstat1 = Propstat() >>> pstat1.status = 200 >>> pstat1.properties.append(makedavelement(u'test1', u'test one')) >>> response.addPropstats(200, pstat1) >>> pstat2 = Propstat() >>> pstat2.status = 404 >>> pstat2.properties.append(makedavelement(u'test2')) >>> response.addPropstats(404, pstat2) >>> print etree.tostring(response()) #doctest:+XMLDATA <response xmlns="DAV:"> <href>/container</href> <propstat> <prop> <test1>test one</test1> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> <propstat> <prop> <test2 /> </prop> <status>HTTP/1.1 404 Not Found</status> </propstat> </response> >>> response.error = [makedavelement(u'precondition-failed')] >>> print etree.tostring(response()) #doctest:+XMLDATA <response xmlns="DAV:"> <href>/container</href> <propstat> <prop> <test1>test one</test1> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> <propstat> <prop> <test2 /> </prop> <status>HTTP/1.1 404 Not Found</status> </propstat> <error> <precondition-failed /> </error> </response> >>> response.responsedescription = u'webdav description' >>> print etree.tostring(response()) #doctest:+XMLDATA <response xmlns="DAV:"> <href>/container</href> <propstat> <prop> <test1>test one</test1> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> <propstat> <prop> <test2 /> </prop> <status>HTTP/1.1 404 Not Found</status> </propstat> <error> <precondition-failed /> </error> <responsedescription>webdav description</responsedescription> </response> >>> response.location = '/container2' >>> print etree.tostring(response()) #doctest:+XMLDATA <response xmlns="DAV:"> <href>/container</href> <propstat> <prop> <test1>test one</test1> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> <propstat> <prop> <test2 /> </prop> <status>HTTP/1.1 404 Not Found</status> </propstat> <error> <precondition-failed /> </error> <responsedescription>webdav description</responsedescription> <location> <href>/container2</href> </location> </response> >>> response = Response('/container1') >>> response.href.append('/container2') >>> response.addPropstats(200, Propstat()) >>> etree.tostring(response()) Traceback (most recent call last): ... ValueError: Response object is in an invalid state. >>> response = Response('/container1') >>> response.status = 200 >>> response.addPropstats(200, Propstat()) >>> etree.tostring(response()) Traceback (most recent call last): ... ValueError: Response object is in an invalid state. Now the must handly method of all the addProperty mehtod: >>> resp = Response('/container') >>> resp.addProperty(200, makedavelement(u'testprop', u'Test Property')) >>> print etree.tostring(resp()) #doctest:+XMLDATA <response xmlns="DAV:"> <href>/container</href> <propstat> <prop> <testprop>Test Property</testprop> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> </response> >>> resp.addProperty(200, makedavelement(u'testprop2', ... u'Test Property Two')) >>> print etree.tostring(resp()) #doctest:+XMLDATA <response xmlns="DAV:"> <href>/container</href> <propstat> <prop> <testprop>Test Property</testprop> <testprop2>Test Property Two</testprop2> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> </response> >>> resp.addProperty(404, makedavelement(u'missing')) >>> print etree.tostring(resp()) #doctest:+XMLDATA <response xmlns="DAV:"> <href>/container</href> <propstat> <prop> <testprop>Test Property</testprop> <testprop2>Test Property Two</testprop2> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> <propstat> <prop> <missing /> </prop> <status>HTTP/1.1 404 Not Found</status> </propstat> </response> """ interface.implements(IResponse) def __init__(self, href): self.href = [href] self.status = None self._propstats = {} # status -> list of propstat Propstat object self.error = [] self.responsedescription = "" self.location = None def getPropstat(self, status): if status not in self._propstats: self._propstats[status] = Propstat() return self._propstats[status] def addPropstats(self, status, propstat): # use getPropstats instead. self._propstats[status] = propstat def addProperty(self, status, element): try: propstat = self._propstats[status] except KeyError: propstat = self._propstats[status] = Propstat() propstat.properties.append(element) def __call__(self): if (len(self.href) > 1 or self.status is not None) and self._propstats: raise ValueError, "Response object is in an invalid state." respel = makedavelement('response') respel.append(makedavelement('href', self.href[0])) if self.status is not None: for href in self.href[1:]: respel.append(makedavelement('href', href)) respel.append(makestatuselement(self.status)) else: for status, propstat in self._propstats.items(): propstat.status = status respel.append(propstat()) for error in self.error: respel.append(makedavelement('error', error)) if self.responsedescription: respel.append(makedavelement('responsedescription', self.responsedescription)) if self.location is not None: respel.append(makedavelement('location', makedavelement('href', self.location))) return respel class MultiStatus(object): """Multistatus element generation >>> from zope.interface.verify import verifyObject >>> ms = MultiStatus() >>> verifyObject(IMultiStatus, ms) True >>> print etree.tostring(ms()) #doctest:+XMLDATA <ns0:multistatus xmlns:ns0="DAV:" /> >>> ms.responsedescription = u'simple description' >>> print etree.tostring(ms()) #doctest:+XMLDATA <multistatus xmlns="DAV:"> <responsedescription>simple description</responsedescription> </multistatus> >>> response = Response('/container') >>> ms.responses.append(response) >>> print etree.tostring(ms()) #doctest:+XMLDATA <multistatus xmlns="DAV:"> <response> <href>/container</href> </response> <responsedescription>simple description</responsedescription> </multistatus> >>> pstat1 = Propstat() >>> pstat1.status = 200 >>> pstat1.properties.append(makedavelement(u'test1', u'test one')) >>> response.addPropstats(200, pstat1) >>> print etree.tostring(ms()) #doctest:+XMLDATA <multistatus xmlns="DAV:"> <response> <href>/container</href> <propstat> <prop> <test1>test one</test1> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> </response> <responsedescription>simple description</responsedescription> </multistatus> >>> response2 = Response('/container2') >>> pstat2 = Propstat() >>> pstat2.status = 404 >>> pstat2.properties.append(makedavelement(u'test2')) >>> response2.addPropstats(404, pstat2) >>> ms.responses.append(response2) >>> print etree.tostring(ms()) #doctest:+XMLDATA <multistatus xmlns="DAV:"> <response> <href>/container</href> <propstat> <prop> <test1>test one</test1> </prop> <status>HTTP/1.1 200 Ok</status> </propstat> </response> <response> <href>/container2</href> <propstat> <prop> <test2 /> </prop> <status>HTTP/1.1 404 Not Found</status> </propstat> </response> <responsedescription>simple description</responsedescription> </multistatus> """ interface.implements(IMultiStatus) def __init__(self): # list of Response objects self.responses = [] # text self.responsedescription = "" def __call__(self): etree = z3c.etree.getEngine() el = etree.Element(etree.QName('DAV:', 'multistatus')) for response in self.responses: el.append(response()) if self.responsedescription: el.append(makedavelement('responsedescription', self.responsedescription)) return el ################################################################################ # # Some other miscellanous helpful methods # ################################################################################ def getObjectURL(ob, req): """Return the URL for the object `ob`. If the object is a container and the url doesn't end in slash '/' then append a slash to the url. """ url = component.getMultiAdapter((ob, req), IAbsoluteURL)() if IReadContainer.providedBy(ob) and url[-1] != "/": url += "/" return url
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/utils.py
utils.py
__docformat__ = 'restructuredtext' from zope import component from zope import interface from zope import schema from zope.schema.interfaces import IField from zope.schema.fieldproperty import FieldProperty import z3c.etree from z3c.dav.interfaces import IDAVProperty, IDAVWidget, IDAVInputWidget from z3c.dav.interfaces import IOpaquePropertyStorage import z3c.dav.widgets import z3c.dav.utils class DAVProperty(object): """ >>> from zope.interface.verify import verifyObject >>> from zope.schema import getFields >>> from zope.interface.interfaces import IInterface >>> from coreproperties import IDAVResourcetype >>> prop = DAVProperty('{DAV:}resourcetype', IDAVResourcetype) >>> verifyObject(IDAVProperty, prop) True >>> prop.namespace 'DAV:' >>> prop.__name__ 'resourcetype' >>> verifyObject(IInterface, prop.iface) True >>> prop.field in getFields(prop.iface).values() True >>> verifyObject(IField, prop.field) True >>> prop.custom_widget is None True >>> prop.restricted False """ interface.implements(IDAVProperty) namespace = FieldProperty(IDAVProperty['namespace']) __name__ = FieldProperty(IDAVProperty['__name__']) ## XXX - If a developer writes his own field and passes it into ## DAVProperty then it is next to impossible to get the to validate ## correctly. ## field = FieldProperty(IDAVProperty['field']) iface = FieldProperty(IDAVProperty['iface']) custom_widget = FieldProperty(IDAVProperty['custom_widget']) custom_input_widget = FieldProperty(IDAVProperty['custom_input_widget']) restricted = FieldProperty(IDAVProperty['restricted']) def __init__(self, tag, iface): namespace, name = z3c.dav.utils.parseEtreeTag(tag) self.namespace = namespace self.__name__ = name self.iface = iface self.field = iface[name] self.custom_widget = None self.custom_input_widget = None self.restricted = False _opaque_namespace_key = "z3c.dav.properties.DAVOpaqueProperties" class DeadField(schema.Field): pass class OpaqueWidget(z3c.dav.widgets.DAVWidget): def render(self): etree = z3c.etree.getEngine() el = etree.fromstring(self._value) return el class OpaqueInputWidget(z3c.dav.widgets.DAVInputWidget): """ >>> class Storage(object): ... interface.implements(IOpaquePropertyStorage) ... def __init__(self): ... self.data = {} ... def setProperty(self, tag, value): ... self.data[tag] = value ... def removeProperty(self, tag): ... del self.data[tag] ... def getProperty(self, tag): ... return self.data[tag] >>> storage = Storage() >>> from cStringIO import StringIO >>> from z3c.dav.publisher import WebDAVRequest >>> reqdata = '''<propertyupdate xmlns="DAV:"> ... <set> ... <prop> ... <high-unicode xmlns="http://webdav.org/neon/litmus/">&#65536;</high-unicode> ... </prop> ... </set> ... </propertyupdate>''' >>> request = WebDAVRequest(StringIO(reqdata), ... {'CONTENT_LENGTH': len(reqdata)}) >>> request.processInputs() >>> prop = OpaqueProperty('{http://webdav.org/neon/litmus/}high-unicode') >>> widget = getWidget(prop, storage, request, type = IDAVInputWidget) >>> print widget.getInputValue() #doctest:+XMLDATA <ns0:high-unicode xmlns:ns0="http://webdav.org/neon/litmus/">\xf0\x90\x80\x80</ns0:high-unicode> """ def getInputValue(self): el = self.request.xmlDataSource.findall( "{DAV:}set/{DAV:}prop/%s" % self.context.tag) etree = z3c.etree.getEngine() # XXX - ascii seems a bit wrong here return etree.tostring(el[-1], "utf-8") class IOpaqueField(IField): tag = schema.BytesLine( title = u"ElementTree tag", description = u"This is the key used by the opaque properties storage", required = True) class OpaqueField(schema.Field): """ >>> from zope.interface.verify import verifyObject >>> field = OpaqueField(__name__ = 'test', ... title = u'Test opaque field', ... tag = '{testns:}test') >>> IOpaqueField.providedBy(field) True >>> field.tag '{testns:}test' >>> from zope.interface.verify import verifyObject >>> field = OpaqueField(__name__ = 'test', ... title = u'Test opaque field', ... tag = 'test') >>> IOpaqueField.providedBy(field) True >>> field.tag 'test' """ interface.implements(IOpaqueField) tag = FieldProperty(IOpaqueField["tag"]) def __init__(self, tag, **kw): super(OpaqueField, self).__init__(**kw) self.tag = tag def get(self, obj): return obj.getProperty(self.tag) def set(self, obj, value): obj.setProperty(self.tag, value) class OpaqueProperty(object): """ >>> from zope.interface.verify import verifyObject >>> prop = OpaqueProperty('{examplens:}testprop') >>> verifyObject(IDAVProperty, prop) True >>> IOpaqueField.providedBy(prop.field) True >>> prop.namespace 'examplens:' The namespace part of a opaque property can be None. >>> prop = OpaqueProperty('testprop') >>> verifyObject(IDAVProperty, prop) True >>> IOpaqueField.providedBy(prop.field) True >>> prop.namespace is None True """ interface.implements(IDAVProperty) def __init__(self, tag): namespace, name = z3c.dav.utils.parseEtreeTag(tag) self.__name__ = name self.namespace = namespace self.iface = IOpaquePropertyStorage self.field = OpaqueField( __name__ = name, tag = tag, title = u"", description = u"") self.custom_widget = OpaqueWidget self.custom_input_widget = OpaqueInputWidget self.restricted = False def getAllProperties(context, request): for name, prop in component.getUtilitiesFor(IDAVProperty): adapter = component.queryMultiAdapter((context, request), prop.iface, default = None) if adapter is None: continue yield prop, adapter adapter = IOpaquePropertyStorage(context, None) if adapter is None: raise StopIteration for tag in adapter.getAllProperties(): yield OpaqueProperty(tag), adapter def hasProperty(context, request, tag): prop = component.queryUtility(IDAVProperty, name = tag, default = None) if prop is None: adapter = IOpaquePropertyStorage(context, None) if adapter is not None and adapter.hasProperty(tag): return True return False adapter = component.queryMultiAdapter((context, request), prop.iface, default = None) if adapter is None: return False return True def getProperty(context, request, tag, exists = False): prop = component.queryUtility(IDAVProperty, name = tag, default = None) if prop is None: adapter = IOpaquePropertyStorage(context, None) if adapter is None: ## XXX - should we use the zope.publisher.interfaces.NotFound ## exceptin here. raise z3c.dav.interfaces.PropertyNotFound(context, tag, tag) if exists and not adapter.hasProperty(tag): ## XXX - should we use the zope.publisher.interfaces.NotFound ## exceptin here. raise z3c.dav.interfaces.PropertyNotFound(context, tag, tag) return OpaqueProperty(tag), adapter adapter = component.queryMultiAdapter((context, request), prop.iface, default = None) if adapter is None: ## XXX - should we use the zope.publisher.interfaces.NotFound ## exceptin here. raise z3c.dav.interfaces.PropertyNotFound(context, tag, tag) return prop, adapter def getWidget(prop, adapter, request, type = IDAVWidget): """prop.field describes the data we want to render. """ if type is IDAVWidget and prop.custom_widget is not None: widget = prop.custom_widget(prop.field, request) elif type is IDAVInputWidget and prop.custom_input_widget is not None: widget = prop.custom_input_widget(prop.field, request) else: widget = component.getMultiAdapter((prop.field, request), type) if IDAVWidget.providedBy(widget): field = prop.field.bind(adapter) widget.setRenderedValue(field.get(adapter)) widget.namespace = prop.namespace return widget
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/properties.py
properties.py
__docformat__ = 'restructuredtext' import datetime import calendar from zope import component from zope import interface from zope.schema import getFieldsInOrder import z3c.etree import interfaces import zope.datetime from zope.app.form.interfaces import ConversionError, MissingInputError DEFAULT_NS = 'DAV:' class DAVWidget(object): """Base class for rendering WebDAV properties through implementations like PROPFIND and PROPPATCH. """ interface.implements(interfaces.IDAVWidget) interface.classProvides(interfaces.IIDAVWidget) def __init__(self, context, request): self.context = context self.request = request self.name = self.context.__name__ self.namespace = None # value to render. self._value = None def setRenderedValue(self, value): self._value = value def toDAVValue(self, value): """Override this method in the base class. This method should either a string, a list or tuple """ raise NotImplementedError, \ "please implemented this method in a subclass of DAVWidget." def render(self): etree = z3c.etree.getEngine() el = etree.Element(etree.QName(self.namespace, self.name)) rendered_value = self.toDAVValue(self._value) el.text = rendered_value return el class TextDAVWidget(DAVWidget): interface.classProvides(interfaces.IIDAVWidget) def toDAVValue(self, value): if value is None: return None return value class IntDAVWidget(DAVWidget): interface.classProvides(interfaces.IIDAVWidget) def toDAVValue(self, value): if value is not None: return str(value) return None class DatetimeDAVWidget(DAVWidget): """Same widget can be used for a date field also.""" interface.classProvides(interfaces.IIDAVWidget) def toDAVValue(self, value): # datetime object if value is None: return None return zope.datetime.rfc1123_date(calendar.timegm(value.utctimetuple())) class DateDAVWidget(DAVWidget): """Same widget can be used for a date field also.""" interface.classProvides(interfaces.IIDAVWidget) def toDAVValue(self, value): # datetime object if value is None: return None return zope.datetime.rfc1123_date(calendar.timegm(value.timetuple())) class ISO8601DatetimeDAVWidget(DAVWidget): """Same widget can be used for a date field also.""" interface.classProvides(interfaces.IIDAVWidget) def toDAVValue(self, value): if value is None: return None if isinstance(value, datetime.datetime) and value.utcoffset() is None: return value.isoformat() + "Z" return value.isoformat() class ObjectDAVWidget(DAVWidget): """ ObjectDAVWidget that will display all properties whether or not the value of specific property in question is the missing value or not. `render_missing_values` attribute is a marker to tell webdav to render all fields which instance value is equal to the fields missing_value. """ interface.classProvides(interfaces.IIDAVWidget) render_missing_values = True def render(self): etree = z3c.etree.getEngine() el = etree.Element(etree.QName(self.namespace, self.name)) if self._value is None: return el interface = self.context.schema for name, field in getFieldsInOrder(interface): field = field.bind(self._value) field_value = field.get(self._value) # Careful this could result in elements not been displayed that # should be. This is tested in test_widgets but it mightened be # what some people think. if field_value == field.missing_value and \ not self.render_missing_values and not field.required: continue widget = component.getMultiAdapter((field, self.request), interfaces.IDAVWidget) widget.namespace = self.namespace widget.setRenderedValue(field.get(self._value)) el.append(widget.render()) return el class ListDAVWidget(DAVWidget): interface.classProvides(interfaces.IIDAVWidget) def render(self): etree = z3c.etree.getEngine() el = etree.Element(etree.QName(self.namespace, self.name)) if self._value is None: return el value_type = self.context.value_type if value_type is None: for value in self._value: el.append(etree.Element(etree.QName(self.namespace, value))) else: # value_type is not None so render each item in the sequence # according to the widget register for this field. for value in self._value: widget = component.getMultiAdapter((value_type, self.request), interfaces.IDAVWidget) widget.setRenderedValue(value) widget.namespace = self.namespace el.append(widget.render()) return el ################################################################################ # # Now for a collection of input widgets. # ################################################################################ class DAVInputWidget(object): interface.implements(interfaces.IDAVInputWidget) interface.classProvides(interfaces.IIDAVInputWidget) def __init__(self, context, request): self.context = context self.request = request self.name = self.context.__name__ self.namespace = None def getProppatchElement(self): """NOTE that the latest specification does NOT specify that a client can't update a property only once during a PROPPATCH request -> this method and implementation is meaningless. """ return self.request.xmlDataSource.findall( '{DAV:}set/{DAV:}prop/{%s}%s' % (self.namespace, self.name))[-1:] def hasInput(self): if self.getProppatchElement(): return True return False def toFieldValue(self, element): raise NotImplementedError( "Please implement the toFieldValue as a subclass of DAVInputWidget") def getInputValue(self): el = self.getProppatchElement() # form input is required, otherwise raise an error if not el: raise MissingInputError(self.name, None, None) # convert input to suitable value - may raise conversion error value = self.toFieldValue(el[0]) return value class TextDAVInputWidget(DAVInputWidget): interface.classProvides(interfaces.IIDAVInputWidget) def toFieldValue(self, element): value = element.text if value is None: return u"" # toFieldValue must validate against the if not isinstance(value, unicode): return value.decode("utf-8") return value class IntDAVInputWidget(DAVInputWidget): interface.classProvides(interfaces.IIDAVInputWidget) def toFieldValue(self, element): value = element.text # XXX - should this be happening - has then the field doesn't validate # in the default case against the corresponding field. if not value: return self.context.missing_value try: return int(value) except ValueError, e: raise ConversionError("Invalid int", e) class FloatDAVInputWidget(DAVInputWidget): interface.classProvides(interfaces.IIDAVInputWidget) def toFieldValue(self, element): value = element.text if not value: # XXX - should this be the case? return self.context.missing_value try: return float(value) except ValueError, e: raise ConversionError("Invalid float", e) class DatetimeDAVInputWidget(DAVInputWidget): interface.classProvides(interfaces.IIDAVInputWidget) def toFieldValue(self, element): value = element.text try: return zope.datetime.parseDatetimetz(value) except (zope.datetime.DateTimeError, ValueError, IndexError), e: raise ConversionError("Invalid datetime date", e) class DateDAVInputWidget(DatetimeDAVInputWidget): interface.classProvides(interfaces.IIDAVInputWidget) def toFieldValue(self, element): value = super(DateDAVInputWidget, self).toFieldValue(element) return value.date()
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/widgets.py
widgets.py
__docformat__ = 'restructuredtext' from zope import interface from zope import component from zope import schema from zope.app.i18n import ZopeMessageFactory as _ import zope.app.container.interfaces import zope.publisher.interfaces.http from z3c.dav.properties import DAVProperty, DeadField import z3c.dav.widgets class IDAVCreationdate(interface.Interface): creationdate = schema.Datetime( title = _("Records the time and date the resource was created."), description = _("""The DAV:creationdate property SHOULD be defined on all DAV compliant resources. If present, it contains a timestamp of the moment when the resource was created. Servers that are incapable of persistently recording the creation date SHOULD instead leave it undefined (i.e. report "Not Found" """), readonly = True) class IDAVDisplayname(interface.Interface): displayname = schema.TextLine( title = _("Provides a name for the resource that is suitable for presentation to a user."), description = _("""Contains a description of the resource that is suitable for presentation to a user. This property is defined on the resource, and hence SHOULD have the same value independent of the Request-URI used to retrieve it (thus computing this property based on the Request-URI is deprecated). While generic clients might display the property value to end users, client UI designers must understand that the method for identifying resources is still the URL. Changes to DAV:displayname do not issue moves or copies to the server, but simply change a piece of meta-data on the individual resource. Two resources can have the same DAV:displayname value even within the same collection."""), readonly = False) class IDAVGetcontentlanguage(interface.Interface): getcontentlanguage = schema.TextLine( title = _("GET Content-Language header."), description = _("""Contains the Content-Language header value (from Section 14.12 of [RFC2616]) as it would be returned by a GET without accept headers. The DAV:getcontentlanguage property MUST be defined on any DAV compliant resource that returns the Content-Language header on a GET."""), readonly = False) class IDAVGetcontentlength(interface.Interface): getcontentlength = schema.Int( title = _("Contains the Content-Length header returned by a GET without accept headers."), description = _("""The DAV:getcontentlength property MUST be defined on any DAV compliant resource that returns the Content-Length header in response to a GET."""), readonly = True) class IDAVGetcontenttype(interface.Interface): getcontenttype = schema.TextLine( title = _("Contains the Content-Type header value as it would be returned by a GET without accept headers."), description = _("""This property MUST be defined on any DAV compliant resource that returns the Content-Type header in response to a GET."""), readonly = False) class IDAVGetetag(interface.Interface): getetag = schema.TextLine( title = _("Contains the ETag header value as it would be returned by a GET without accept headers."), description = _("""The getetag property MUST be defined on any DAV compliant resource that returns the Etag header. Refer to Section 3.11 of RFC2616 for a complete definition of the semantics of an ETag, and to Section 8.6 for a discussion of ETags in WebDAV."""), readonly = True) class IDAVGetlastmodified(interface.Interface): getlastmodified = schema.Datetime( title = _("Contains the Last-Modified header value as it would be returned by a GET method without accept headers."), description = _("""Note that the last-modified date on a resource SHOULD only reflect changes in the body (the GET responses) of the resource. A change in a property only SHOULD NOT cause the last-modified date to change, because clients MAY rely on the last-modified date to know when to overwrite the existing body. The DAV:getlastmodified property MUST be defined on any DAV compliant resource that returns the Last-Modified header in response to a GET."""), readonly = True) class ILockEntry(interface.Interface): """A DAV Sub property of the supportedlock property. """ lockscope = schema.List( title = u"Describes the exclusivity of a lock", description = u"""Specifies whether a lock is an exclusive lock, or a shared lock.""", required = True, readonly = True) locktype = schema.List( title = u"Describes the access type of the lock.", description = u"""Specifies the access type of a lock. At present, this specification only defines one lock type, the write lock.""", required = True, readonly = True) class IActiveLock(ILockEntry): """A DAV Sub property of the lockdiscovery property. """ depth = schema.Text( title = u"Depth", description = u"The value of the Depth header.", required = False, readonly = True) owner = DeadField( title = u"Owner", description = u"""The owner XML element provides information sufficient for either directly contacting a principal (such as a telephone number or Email URI), or for discovering the principal (such as the URL of a homepage) who created a lock. The value provided MUST be treated as a dead property in terms of XML Information Item preservation. The server MUST NOT alter the value unless the owner value provided by the client is empty. """, required = False, readonly = True) timeout = schema.Text( title = u"Timeout", description = u"The timeout associated with a lock", required = False, readonly = True) locktoken = schema.List( title = u"Lock Token", description = u"""The href contains one or more opaque lock token URIs which all refer to the same lock (i.e., the OpaqueLockToken-URI production in section 6.4).""", value_type = schema.URI( __name__ = u"href", title = u"Href", description = u"""The href contains a single lock token URI which refers to the lock.""", ), required = False, readonly = True, max_length = 1) lockroot = schema.URI( title = u"Lock root", description = u""" """, readonly = True, required = True) class IDAVLockdiscovery(interface.Interface): lockdiscovery = schema.List( title = _("Describes the active locks on a resource"), description = _("""Returns a listing of who has a lock, what type of lock he has, the timeout type and the time remaining on the timeout, and the associated lock token. If there are no locks, but the server supports locks, the property will be present but contain zero 'activelock' elements. If there is one or more lock, an 'activelock' element appears for each lock on the resource. This property is NOT lockable with respect to write locks (Section 7)."""), value_type = schema.Object( __name__ = "activelock", title = _(""), description = _(""), schema = IActiveLock, readonly = True), readonly = True) class IDAVResourcetype(interface.Interface): resourcetype = schema.List( title = _("Specifies the nature of the resource."), description = _("""MUST be defined on all DAV compliant resources. Each child element identifies a specific type the resource belongs to, such as 'collection', which is the only resource type defined by this specification (see Section 14.3). If the element contains the 'collection' child element plus additional unrecognized elements, it should generally be treated as a collection. If the element contains no recognized child elements, it should be treated as a non-collection resource. The default value is empty. This element MUST NOT contain text or mixed content. Any custom child element is considered to be an identifier for a resource type."""), readonly = True) class IDAVSupportedlock(interface.Interface): supportedlock = schema.List( title = _("To provide a listing of the lock capabilities supported by the resource."), description = _("""Returns a listing of the combinations of scope and access types which may be specified in a lock request on the resource. Note that the actual contents are themselves controlled by access controls so a server is not required to provide information the client is not authorized to see. This property is NOT lockable with respect to write locks (Section 7)."""), value_type = schema.Object( __name__ = "lockentry", title = _(""), description = _(""), schema = ILockEntry, readonly = True), readonly = True) class IDAVCoreSchema(IDAVCreationdate, IDAVDisplayname, IDAVGetlastmodified): """Base core properties - note that resourcetype is complusory and is in its own interface. """ class IDAVGetSchema(IDAVGetcontentlanguage, IDAVGetcontentlength, IDAVGetcontenttype, IDAVGetetag): """Extended properties that only apply to certain content. """ class IDAVLockSupport(IDAVLockdiscovery, IDAVSupportedlock): """ """ class LockdiscoveryDAVWidget(z3c.dav.widgets.ListDAVWidget): """ Custom widget for the `{DAV:}lockdiscovery` property. This is basically a list widget but it doesn't display any sub XML element whose value is equal to its field missing_value. >>> import zope.schema.interfaces >>> from z3c.dav.tests import test_widgets Setup some adapters for rendering the widget. >>> gsm = component.getGlobalSiteManager() >>> gsm.registerAdapter(z3c.dav.widgets.TextDAVWidget, ... (zope.schema.interfaces.IText, None)) >>> gsm.registerAdapter(z3c.dav.widgets.IntDAVWidget, ... (zope.schema.interfaces.IInt, None)) Setup a field and test object to render. While this is not the same field as the `{DAV:}lockdiscovery` property but it is lot easier to work with during the tests. >>> field = schema.List(__name__ = 'testelement', ... title = u'Test field', ... value_type = schema.Object( ... __name__ = u'testsubelement', ... title = u'Test sub element', ... schema = test_widgets.ISimpleInterface)) >>> objectvalue = test_widgets.SimpleObject(name = None, age = 26) >>> widget = LockdiscoveryDAVWidget(field, None) >>> widget.namespace = 'DAV:' >>> widget.setRenderedValue([objectvalue]) The objectvalue name is None which is equal the Text field missing_value so the name sub XML element doesn't show up. >>> print etree.tostring(widget.render()) #doctest:+XMLDATA <testelement xmlns='DAV:'> <testsubelement> <age>26</age> </testsubelement> </testelement> By setting the name attribute it now shows up in the output. >>> objectvalue.name = u'Michael Kerrin' >>> print etree.tostring(widget.render()) #doctest:+XMLDATA <testelement xmlns='DAV:'> <testsubelement> <name>Michael Kerrin</name> <age>26</age> </testsubelement> </testelement> But the content object needs to be locked for the `{DAV:}lockdiscovery` element to have a value. >>> widget.setRenderedValue(None) >>> print etree.tostring(widget.render()) #doctest:+XMLDATA <testelement xmlns='DAV:' /> Clean up the component registration. >>> gsm.unregisterAdapter(z3c.dav.widgets.TextDAVWidget, ... (zope.schema.interfaces.IText, None)) True >>> gsm.unregisterAdapter(z3c.dav.widgets.IntDAVWidget, ... (zope.schema.interfaces.IInt, None)) True """ interface.classProvides(z3c.dav.interfaces.IIDAVWidget) def render(self): etree = z3c.etree.getEngine() el = etree.Element(etree.QName(self.namespace, self.name)) if self._value is not self.context.missing_value: for value in self._value: widget = z3c.dav.widgets.ObjectDAVWidget( self.context.value_type, self.request) widget.render_missing_values = False widget.setRenderedValue(value) widget.namespace = self.namespace el.append(widget.render()) return el ################################################################################ # # Collection of default properties has defined in Section 15. # subsection 1 -> 10 of draft-ietf-webdav-rfc2518bis-15.txt # ################################################################################ creationdate = DAVProperty("{DAV:}creationdate", IDAVCreationdate) creationdate.custom_widget = z3c.dav.widgets.ISO8601DatetimeDAVWidget displayname = DAVProperty("{DAV:}displayname", IDAVDisplayname) getcontentlanguage = DAVProperty("{DAV:}getcontentlanguage", IDAVGetcontentlanguage) getcontentlength = DAVProperty("{DAV:}getcontentlength", IDAVGetcontentlength) getcontenttype = DAVProperty("{DAV:}getcontenttype", IDAVGetcontenttype) getetag = DAVProperty("{DAV:}getetag", IDAVGetetag) getlastmodified = DAVProperty("{DAV:}getlastmodified", IDAVGetlastmodified) resourcetype = DAVProperty("{DAV:}resourcetype", IDAVResourcetype) lockdiscovery = DAVProperty("{DAV:}lockdiscovery", IDAVLockdiscovery) lockdiscovery.custom_widget = LockdiscoveryDAVWidget supportedlock = DAVProperty("{DAV:}supportedlock", IDAVSupportedlock) ################################################################################ # # Default storage adapter for the only mandatory property. # ################################################################################ class ResourceTypeAdapter(object): """ All content that doesn't implement the IReadContainer interface, their resourcetype value is None. >>> class Resource(object): ... pass >>> resource = Resource() >>> adapter = ResourceTypeAdapter(resource, None) >>> adapter.resourcetype is None True If a content object implements IReadContainer then it value is a list of types, just 'collection' in this case. >>> from zope.app.folder.folder import Folder >>> folder = Folder() >>> adapter = ResourceTypeAdapter(folder, None) >>> adapter.resourcetype [u'collection'] """ interface.implements(IDAVResourcetype) component.adapts(interface.Interface, zope.publisher.interfaces.http.IHTTPRequest) def __init__(self, context, request): self.context = context @property def resourcetype(self): if zope.app.container.interfaces.IReadContainer.providedBy( self.context): return [u'collection'] return None
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/coreproperties.py
coreproperties.py
__docformat__ = 'restructuredtext' from zope import component from zope.filerepresentation.interfaces import IWriteDirectory from zope.filerepresentation.interfaces import IDirectoryFactory import zope.event from zope.lifecycleevent import ObjectCreatedEvent import zope.app.http.interfaces import zope.publisher.interfaces.http import z3c.dav.interfaces class MKCOL(object): """ MKCOL handler for creating collections. This is only supported on unmapped urls. >>> from cStringIO import StringIO >>> import zope.interface >>> from zope import component >>> from zope.publisher.browser import TestRequest >>> from zope.app.http.put import NullResource >>> from zope.app.folder.folder import Folder >>> from zope.app.folder.interfaces import IFolder >>> events = [] >>> def eventLog(event): ... events.append(event) >>> zope.event.subscribers.append(eventLog) >>> container = Folder() >>> context = NullResource(container, 'newdir') A MKCOL request message may contain a message body. But the specification says that if the server receives a entity type that it doesn't understand then it MOST respond with a 415 (Unsupported Media Type). This implementation of MKCOL doesn't understand any message body received with a MKCOL request and thus raise a UnsupportedMediaType exception. >>> mkcol = MKCOL(context, TestRequest(StringIO('some request body'))) >>> mkcol.MKCOL() #doctest:+ELLIPSIS Traceback (most recent call last): ... UnsupportedMediaType: <zope.app.http.put.NullResource object at ...>, u'A request body is not supported for a MKCOL method' >>> events [] >>> request = TestRequest(environ = {'CONTENT_LENGTH': 0}) If no adapter implementing IWriteDirectory is registered for then we will never be able to create a new collection and hence this operation is forbidden. >>> MKCOL(context, request).MKCOL() Traceback (most recent call last): ... ForbiddenError >>> 'newdir' in container False >>> events [] Now we will define and register a IWriteDirectory adapter. But we can't adapt the container to IDirectoryFactory (which creates the new collection object) so again this operation is forbidden. >>> class WriteDirectory(object): ... zope.interface.implements(IWriteDirectory) ... component.adapts(IFolder) ... def __init__(self, context): ... self.context = context ... def __setitem__(self, name, object): ... self.context[name] = object ... def __delitem__(slef, name): ... del self.context[name] >>> component.getGlobalSiteManager().registerAdapter(WriteDirectory) >>> events = [] >>> MKCOL(context, request).MKCOL() Traceback (most recent call last): ... ForbiddenError >>> 'newdir' in container False >>> events [] By defining and registering a directory factory we can create a new collection. >>> class DirectoryFactory(object): ... zope.interface.implements(IDirectoryFactory) ... component.adapts(IFolder) ... def __init__(self, context): ... pass ... def __call__(self, name): ... return Folder() >>> component.getGlobalSiteManager().registerAdapter(DirectoryFactory) >>> events = [] The next call to the mkcol implementation will succeed and create a new folder with the name 'newdir'. >>> MKCOL(context, request).MKCOL() '' >>> request.response.getStatus() 201 >>> 'newdir' in container True >>> container['newdir'] #doctest:+ELLIPSIS <zope.app.folder.folder.Folder object at ...> Verify that the correct events are generated during the creation of the new folder. >>> events[0] #doctest:+ELLIPSIS <zope.app.event.objectevent.ObjectCreatedEvent object at ...> >>> events[1] #doctest:+ELLIPSIS <zope.app.container.contained.ObjectAddedEvent object at ...> >>> events[2] #doctest:+ELLIPSIS <zope.app.container.contained.ContainerModifiedEvent object at ...> >>> events[3:] [] Cleanup. >>> component.getGlobalSiteManager().unregisterAdapter(WriteDirectory) True >>> component.getGlobalSiteManager().unregisterAdapter(DirectoryFactory) True >>> zope.event.subscribers.remove(eventLog) """ component.adapts(zope.app.http.interfaces.INullResource, zope.publisher.interfaces.http.IHTTPRequest) def __init__(self, context, request): self.context = context self.request = request def MKCOL(self): if self.request.getHeader("content-length") > 0: # We don't (yet) support a request body on MKCOL. raise z3c.dav.interfaces.UnsupportedMediaType( self.context, message = u"A request body is not supported for a MKCOL method") container = self.context.container name = self.context.name dir = IWriteDirectory(container, None) dir_factory = IDirectoryFactory(container, None) if dir is None or dir_factory is None: raise z3c.dav.interfaces.ForbiddenError( self.context, message = u"") newdir = dir_factory(name) zope.event.notify(ObjectCreatedEvent(newdir)) dir[name] = newdir self.request.response.setStatus(201) return ""
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/mkcol.py
mkcol.py
__docformat__ = 'restructuredtext' import zope.event from zope import interface from zope import component import zope.lifecycleevent import z3c.etree from zope.security.interfaces import Unauthorized import z3c.dav.utils import z3c.dav.interfaces import z3c.dav.properties class PROPPATCH(object): """PROPPATCH handler for all objects""" interface.implements(z3c.dav.interfaces.IWebDAVMethod) component.adapts(interface.Interface, z3c.dav.interfaces.IWebDAVRequest) def __init__(self, context, request): self.context = context self.request = request def PROPPATCH(self): if self.request.content_type not in ("text/xml", "application/xml") \ or self.request.xmlDataSource is None: raise z3c.dav.interfaces.BadRequest( self.request, message = "All PROPPATCH requests needs a XML body") xmldata = self.request.xmlDataSource if xmldata.tag != "{DAV:}propertyupdate": raise z3c.dav.interfaces.UnprocessableError( self.context, message = u"PROPPATCH request body must be a " "`propertyupdate' XML element.") etree = z3c.etree.getEngine() # propErrors - list of (property tag, error). error is None if no # error occurred in setting / removing the property. propErrors = [] # properties - list of all the properties that we handled correctly. properties = [] # changedAttributes - list of IModificationDescription objects # indicting what as changed during this request changedAttributes = [] for update in xmldata: if update.tag not in ("{DAV:}set", "{DAV:}remove"): continue props = update.findall("{DAV:}prop") if not props: continue props = props[0] for prop in props: if z3c.dav.utils.parseEtreeTag(prop.tag)[0] == "": # A namespace which is None corresponds to when no prefix # is set, which I think is fine. raise z3c.dav.interfaces.BadRequest( self.request, u"PROPFIND with invalid namespace declaration in body") try: if update.tag == "{DAV:}set": changedAttributes.extend(self.handleSet(prop)) else: # update.tag == "{DAV:}remove" changedAttributes.extend(self.handleRemove(prop)) except Unauthorized: # If the use doesn't have the correct permission to modify # a property then we need to re-raise the Unauthorized # exception in order to ask the user to log in. raise except Exception, error: propErrors.append((prop.tag, error)) else: properties.append(prop.tag) if propErrors: errors = z3c.dav.interfaces.WebDAVPropstatErrors(self.context) for prop, error in propErrors: errors[prop] = error for proptag in properties: errors[proptag] = z3c.dav.interfaces.FailedDependency( self.context, proptag) raise errors # this kills the current transaction. if changedAttributes: zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent( self.context, *changedAttributes)) url = z3c.dav.utils.getObjectURL(self.context, self.request) response = z3c.dav.utils.Response(url) propstat = response.getPropstat(200) for proptag in properties: propstat.properties.append(etree.Element(proptag)) multistatus = z3c.dav.utils.MultiStatus() multistatus.responses.append(response) self.request.response.setStatus(207) self.request.response.setHeader("content-type", "application/xml") ## Is UTF-8 encoding ok here or is there a better way of doing this. return etree.tostring(multistatus(), encoding = "utf-8") def handleSet(self, prop): davprop, adapter = z3c.dav.properties.getProperty( self.context, self.request, prop.tag) # Not all properties have a IDAVInputWidget defined field = davprop.field.bind(adapter) if field.readonly: raise z3c.dav.interfaces.ForbiddenError( self.context, prop.tag, message = u"readonly field") widget = z3c.dav.properties.getWidget( davprop, adapter, self.request, type = z3c.dav.interfaces.IDAVInputWidget) value = widget.getInputValue() field.validate(value) if field.get(adapter) != value: field.set(adapter, value) return [ zope.lifecycleevent.Attributes(davprop.iface, davprop.__name__)] return [] def handleRemove(self, prop): davprop = component.queryUtility( z3c.dav.interfaces.IDAVProperty, prop.tag, None) if davprop is not None: raise z3c.dav.interfaces.ConflictError( self.context, prop.tag, message = u"cannot remove a live property") deadproperties = z3c.dav.interfaces.IOpaquePropertyStorage( self.context, None) if deadproperties is not None and deadproperties.hasProperty(prop.tag): deadproperties.removeProperty(prop.tag) return [zope.lifecycleevent.Sequence( z3c.dav.interfaces.IOpaquePropertyStorage, prop.tag)] return []
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/proppatch.py
proppatch.py
__docformat__ = 'restructuredtext' from zope import interface from zope import schema from zope import component import zope.publisher.interfaces.http from zope.app.http.interfaces import IHTTPException import zope.app.publisher.browser import z3c.dav.interfaces import z3c.dav.utils import z3c.etree class DAVError(object): interface.implements(z3c.dav.interfaces.IDAVErrorWidget) component.adapts(interface.Interface, z3c.dav.interfaces.IWebDAVRequest) def __init__(self, context, request): self.context = context self.request = request status = None errors = [] propstatdescription = "" responsedescription = "" class ConflictError(DAVError): status = 409 class ForbiddenError(DAVError): status = 403 class PropertyNotFoundError(DAVError): status = 404 class FailedDependencyError(DAVError): # context is generally None for a failed dependency error. status = 424 class AlreadyLockedError(DAVError): status = 423 class UnauthorizedError(DAVError): status = 401 ################################################################################ # # Multi-status error view # ################################################################################ class MultiStatusErrorView(object): component.adapts(z3c.dav.interfaces.IWebDAVErrors, z3c.dav.interfaces.IWebDAVRequest) interface.implements(IHTTPException) def __init__(self, error, request): self.error = error self.request = request def __call__(self): etree = z3c.etree.getEngine() multistatus = z3c.dav.utils.MultiStatus() if len(self.error.errors) == 1 and \ self.error.errors[0].resource == self.error.context: # If have only one error and the context on which we raised the # exception, then we just try and view the default view of the # error. error = self.error.errors[0] name = zope.app.publisher.browser.queryDefaultViewName( error, self.request) if name is not None: view = component.queryMultiAdapter( (error, self.request), name = name) return view() seenContext = False for error in self.error.errors: if error.resource == self.error.context: seenContext = True davwidget = component.getMultiAdapter( (error, self.request), z3c.dav.interfaces.IDAVErrorWidget) response = z3c.dav.utils.Response( z3c.dav.utils.getObjectURL(error.resource, self.request)) response.status = davwidget.status # we don't generate a propstat elements during this view so # we just ignore the propstatdescription. response.responsedescription += davwidget.responsedescription multistatus.responses.append(response) if not seenContext: response = z3c.dav.utils.Response( z3c.dav.utils.getObjectURL(self.error.context, self.request)) response.status = 424 # Failed Dependency multistatus.responses.append(response) self.request.response.setStatus(207) self.request.response.setHeader("content-type", "application/xml") return etree.tostring(multistatus(), encoding = "utf-8") class WebDAVPropstatErrorView(object): interface.implements(IHTTPException) component.adapts(z3c.dav.interfaces.IWebDAVPropstatErrors, z3c.dav.interfaces.IWebDAVRequest) def __init__(self, error, request): self.error = error self.request = request def __call__(self): etree = z3c.etree.getEngine() multistatus = z3c.dav.utils.MultiStatus() response = z3c.dav.utils.Response( z3c.dav.utils.getObjectURL(self.error.context, self.request)) multistatus.responses.append(response) for prop, error in self.error.items(): error_view = component.getMultiAdapter( (error, self.request), z3c.dav.interfaces.IDAVErrorWidget) propstat = response.getPropstat(error_view.status) if z3c.dav.interfaces.IDAVProperty.providedBy(prop): ## XXX - not tested - but is it needed? prop = "{%s}%s" %(prop.namespace, prop.__name__) propstat.properties.append(etree.Element(prop)) ## XXX - needs testing. propstat.responsedescription += error_view.propstatdescription response.responsedescription += error_view.responsedescription self.request.response.setStatus(207) self.request.response.setHeader("content-type", "application/xml") return etree.tostring(multistatus(), encoding = "utf-8") ################################################################################ # # Some more generic exception view. # ################################################################################ class HTTPForbiddenError(object): interface.implements(IHTTPException) component.adapts(z3c.dav.interfaces.IForbiddenError, zope.publisher.interfaces.http.IHTTPRequest) def __init__(self, error, request): self.error = error self.request = request def __call__(self): self.request.response.setStatus(403) return "" class HTTPConflictError(object): interface.implements(IHTTPException) component.adapts(z3c.dav.interfaces.IConflictError, zope.publisher.interfaces.http.IHTTPRequest) def __init__(self, error, request): self.error = error self.request = request def __call__(self): self.request.response.setStatus(409) return "" class PreconditionFailed(object): interface.implements(IHTTPException) component.adapts(z3c.dav.interfaces.IPreconditionFailed, zope.publisher.interfaces.http.IHTTPRequest) def __init__(self, error, request): self.error = error self.request = request def __call__(self): self.request.response.setStatus(412) return "" class HTTPUnsupportedMediaTypeError(object): interface.implements(IHTTPException) component.adapts(z3c.dav.interfaces.IUnsupportedMediaType, zope.publisher.interfaces.http.IHTTPRequest) def __init__(self, error, request): self.error = error self.request = request def __call__(self): self.request.response.setStatus(415) return "" class UnprocessableError(object): interface.implements(IHTTPException) component.adapts(z3c.dav.interfaces.IUnprocessableError, zope.publisher.interfaces.http.IHTTPRequest) def __init__(self, context, request): self.context = context self.request = request def __call__(self): self.request.response.setStatus(422) return "" class AlreadyLockedErrorView(object): interface.implements(IHTTPException) component.adapts(z3c.dav.interfaces.IAlreadyLocked, zope.publisher.interfaces.http.IHTTPRequest) def __init__(self, context, request): self.request = request def __call__(self): self.request.response.setStatus(423) return "" class BadGateway(object): interface.implements(IHTTPException) component.adapts(z3c.dav.interfaces.IBadGateway, zope.publisher.interfaces.http.IHTTPRequest) def __init__(self, error, request): self.error = error self.request = request def __call__(self): self.request.response.setStatus(502) return ""
z3c.dav
/z3c.dav-1.0b.tar.gz/z3c.dav-1.0b/src/z3c/dav/exceptions/__init__.py
__init__.py
import persistent import zope.component import zope.interface import zope.locking.interfaces import zope.locking.tokens from zope.app.keyreference.interfaces import IKeyReference import interfaces INDIRECT_INDEX_KEY = 'zope.app.dav.lockingutils' class IndirectToken(persistent.Persistent): """ Most of these tests have being copied from the README.txt file in zope.locking Some initial setup including creating some demo content. >>> from zope.locking import utility, utils >>> util = utility.TokenUtility() >>> zope.component.getGlobalSiteManager().registerUtility( ... util, zope.locking.interfaces.ITokenUtility) Setup some content to test on. >>> demofolder = DemoFolder(None, 'demofolderroot') >>> demofolder['demo1'] = Demo() >>> demofolder['demofolder1'] = DemoFolder() >>> demofolder['demofolder1']['demo'] = Demo() Lock the root folder with an exclusive lock. >>> lockroot = zope.locking.tokens.ExclusiveLock(demofolder, 'michael') >>> res = util.register(lockroot) Now indirectly all the descended objects of the root folder against the exclusive lock token we used to lock this folder with. >>> lock1 = IndirectToken(demofolder['demo1'], lockroot) >>> lock2 = IndirectToken(demofolder['demofolder1'], lockroot) >>> lock3 = IndirectToken(demofolder['demofolder1']['demo'], lockroot) >>> res1 = util.register(lock1) >>> lock1 is util.get(demofolder['demo1']) True >>> res2 = util.register(lock2) >>> lock2 is util.get(demofolder['demofolder1']) True >>> res3 = util.register(lock3) >>> lock3 is util.get(demofolder['demofolder1']['demo']) True Make sure that the lockroot contains an index of all the toekns locked against in its annotations >>> len(lockroot.annotations[INDIRECT_INDEX_KEY]) 3 Check that the IEndable properties are None >>> res1.expiration == lockroot.expiration == None True >>> res1.duration == lockroot.duration == None True >>> res1.duration == lockroot.remaining_duration == None True >>> res1.started == lockroot.started True >>> lockroot.started is not None True All the indirect locktokens and the lookroot share the same annotations >>> lockroot.annotations[u'webdav'] = u'test webdav indirect locking' >>> res1.annotations[u'webdav'] u'test webdav indirect locking' All the lock tokens have the same principals >>> list(res1.principal_ids) ['michael'] >>> list(lockroot.principal_ids) ['michael'] None of the locks have ended yet, and they share the same utility. >>> res1.ended is None True >>> lockroot.ended is None True >>> lockroot.utility is res1.utility True Expire the lock root >>> now = utils.now() >>> res3.end() Now all the descendent objects of the lockroot and the lockroot itself are unlocked. >>> util.get(demofolder) is None True >>> util.get(demofolder['demo1']) is None True >>> util.get(demofolder['demofolder1']['demo']) is None True Also all the tokens has ended after now. >>> lock1.ended is not None True >>> lock2.ended > now True >>> lock1.ended is lock2.ended True >>> lock3.ended is lockroot.ended True Test the event subscribers. >>> ev = events[-1] >>> zope.locking.interfaces.ITokenEndedEvent.providedBy(ev) True >>> len(lockroot.annotations[INDIRECT_INDEX_KEY]) 3 >>> ev.object is lockroot True >>> removeEndedTokens(lockroot, ev) >>> len(lockroot.annotations[INDIRECT_INDEX_KEY]) 0 Test all the endable attributes >>> import datetime >>> one = datetime.timedelta(hours = 1) >>> two = datetime.timedelta(hours = 2) >>> three = datetime.timedelta(hours = 3) >>> four = datetime.timedelta(hours = 4) >>> lockroot = zope.locking.tokens.ExclusiveLock( ... demofolder, 'john', three) >>> dummy = util.register(lockroot) >>> indirect1 = IndirectToken(demofolder['demo1'], lockroot) >>> dummy = util.register(indirect1) >>> indirect1.duration datetime.timedelta(0, 10800) >>> lockroot.duration == indirect1.duration True >>> indirect1.ended is None True >>> indirect1.expiration == indirect1.started + indirect1.duration True Now try to >>> indirect1.expiration = indirect1.started + one >>> indirect1.expiration == indirect1.started + one True >>> indirect1.expiration == lockroot.expiration True >>> indirect1.duration == one True Now test changing the duration attribute >>> indirect1.duration = four >>> indirect1.duration == lockroot.duration True >>> indirect1.duration datetime.timedelta(0, 14400) Now check the remain_duration code >>> import pytz >>> def hackNow(): ... return (datetime.datetime.now(pytz.utc) + ... datetime.timedelta(hours=2)) ... >>> import zope.locking.utils >>> oldNow = zope.locking.utils.now >>> zope.locking.utils.now = hackNow # make code think it's 2 hours later >>> indirect1.duration datetime.timedelta(0, 14400) >>> two >= indirect1.remaining_duration >= one True >>> indirect1.remaining_duration -= one >>> one >= indirect1.remaining_duration >= datetime.timedelta() True >>> three + datetime.timedelta(minutes = 1) >= indirect1.duration >= three True Since we modified the remaining_duration attribute a IExpirationChagedEvent should have being fired. >>> ev = events[-1] >>> from zope.interface.verify import verifyObject >>> from zope.locking.interfaces import IExpirationChangedEvent >>> verifyObject(IExpirationChangedEvent, ev) True >>> ev.object is lockroot True Now pretend that it is a day later, the indirect token and the lock root will have timed out sliently. >>> def hackNow(): ... return ( ... datetime.datetime.now(pytz.utc) + datetime.timedelta(days=1)) ... >>> zope.locking.utils.now = hackNow # make code think it is a day later >>> indirect1.ended == indirect1.expiration True >>> lockroot.ended == indirect1.ended True >>> util.get(demofolder['demo1']) is None True >>> util.get(demofolder['demo1'], util) is util True >>> indirect1.remaining_duration == datetime.timedelta() True >>> indirect1.end() Traceback (most recent call last): ... EndedError Once a lock has ended, the timeout can no longer be changed. >>> indirect1.duration = datetime.timedelta(days=2) Traceback (most recent call last): ... EndedError Now undo our hack. >>> zope.locking.utils.now = oldNow # undo the hack >>> indirect1.end() # really end the token >>> util.get(demofolder) is None True Now test the simple SharedLock with an indirect token. >>> lockroot = zope.locking.tokens.SharedLock( ... demofolder, ('john', 'mary')) >>> dummy = util.register(lockroot) >>> sharedindirect = IndirectToken(demofolder['demo1'], lockroot) >>> dummy = util.register(sharedindirect) >>> sorted(sharedindirect.principal_ids) ['john', 'mary'] >>> sharedindirect.add(('jane',)) >>> sorted(lockroot.principal_ids) ['jane', 'john', 'mary'] >>> sorted(sharedindirect.principal_ids) ['jane', 'john', 'mary'] >>> sharedindirect.remove(('mary',)) >>> sorted(sharedindirect.principal_ids) ['jane', 'john'] >>> sorted(lockroot.principal_ids) ['jane', 'john'] >>> lockroot.remove(('jane',)) >>> sorted(sharedindirect.principal_ids) ['john'] >>> sorted(lockroot.principal_ids) ['john'] >>> sharedindirect.remove(('john',)) >>> util.get(demofolder) is None True >>> util.get(demofolder['demo1']) is None True Test using the shared lock token methods on a non shared lock >>> lockroot = zope.locking.tokens.ExclusiveLock(demofolder, 'john') >>> dummy = util.register(lockroot) >>> indirect1 = IndirectToken(demofolder['demo1'], lockroot) >>> dummy = util.register(indirect1) >>> dummy is indirect1 True >>> dummy.add('john') Traceback (most recent call last): ... TypeError: can't add a principal to a non-shared token >>> dummy.remove('michael') Traceback (most recent call last): ... TypeError: can't add a principal to a non-shared token Setup with wrong utility. >>> util2 = utility.TokenUtility() >>> roottoken = zope.locking.tokens.ExclusiveLock(demofolder, 'michael2') >>> roottoken = util2.register(roottoken) >>> roottoken.utility == util2 True >>> indirecttoken = IndirectToken(demofolder['demo1'], roottoken) >>> indirecttoken = util2.register(indirecttoken) >>> indirecttoken.utility is util2 True >>> indirecttoken.utility = util Traceback (most recent call last): ... ValueError: cannot reset utility >>> indirecttoken = IndirectToken(demofolder['demo1'], roottoken) >>> indirecttoken.utility = util Traceback (most recent call last): ... ValueError: Indirect tokens must be registered with the same utility has the root token Cleanup test. >>> zope.component.getGlobalSiteManager().unregisterUtility( ... util, zope.locking.interfaces.ITokenUtility) True """ zope.interface.implements(interfaces.IIndirectToken) def __init__(self, target, token): self.context = self.__parent__ = target self.roottoken = token _utility = None @apply def utility(): # IAbstractToken - this is the only hook I can find since # it represents the lock utility in charge of this lock. def get(self): return self._utility def set(self, value): if self._utility is not None: if value is not self._utility: raise ValueError("cannot reset utility") else: assert zope.locking.interfaces.ITokenUtility.providedBy(value) root = self.roottoken if root.utility != value: raise ValueError("Indirect tokens must be registered with" \ " the same utility has the root token") index = root.annotations.get(INDIRECT_INDEX_KEY, None) if index is None: index = root.annotations[INDIRECT_INDEX_KEY] = \ zope.locking.tokens.AnnotationsMapping() index.__parent__ = root key_ref = IKeyReference(self.context) assert index.get(key_ref, None) is None, \ "context is already locked" index[key_ref] = self self._utility = value return property(get, set) @property def principal_ids(self): # IAbstractToken return self.roottoken.principal_ids @property def started(self): # IAbstractToken return self.roottoken.started @property def annotations(self): # See IToken return self.roottoken.annotations def add(self, principal_ids): # ISharedLock if not zope.locking.interfaces.ISharedLock.providedBy(self.roottoken): raise TypeError, "can't add a principal to a non-shared token" return self.roottoken.add(principal_ids) def remove(self, principal_ids): # ISharedLock if not zope.locking.interfaces.ISharedLock.providedBy(self.roottoken): raise TypeError, "can't add a principal to a non-shared token" return self.roottoken.remove(principal_ids) @property def ended(self): # IEndable return self.roottoken.ended @apply def expiration(): # XXX - needs testing # IEndable def get(self): return self.roottoken.expiration def set(self, value): self.roottoken.expiration = value return property(get, set) @apply def duration(): # XXX - needs testing # IEndable def get(self): return self.roottoken.duration def set(self, value): self.roottoken.duration = value return property(get, set) @apply def remaining_duration(): # IEndable def get(self): return self.roottoken.remaining_duration def set(self, value): self.roottoken.remaining_duration = value return property(get, set) def end(self): # IEndable return self.roottoken.end() @zope.component.adapter(zope.locking.interfaces.IEndableToken, zope.locking.interfaces.ITokenEndedEvent) def removeEndedTokens(object, event): """subscriber handler for ITokenEndedEvent""" assert zope.locking.interfaces.ITokenEndedEvent.providedBy(event) roottoken = event.object assert not interfaces.IIndirectToken.providedBy(roottoken) index = roottoken.annotations.get(INDIRECT_INDEX_KEY, {}) # read the whole index in memory so that we correctly loop over all the # items in this list. indexItems = list(index.items()) for key_ref, token in indexItems: # token has ended so it should be removed via the register method roottoken.utility.register(token) del index[key_ref]
z3c.davapp.zopelocking
/z3c.davapp.zopelocking-1.0b.tar.gz/z3c.davapp.zopelocking-1.0b/src/z3c/davapp/zopelocking/indirecttokens.py
indirecttokens.py
from BTrees.OOBTree import OOBTree import zope.component import zope.interface import zope.security.management import zope.publisher.interfaces.http import zope.lifecycleevent.interfaces from zope.app.container.interfaces import IReadContainer import z3c.dav.interfaces import z3c.dav.locking import z3c.dav.ifvalidator import interfaces import indirecttokens import properties WEBDAV_LOCK_KEY = "z3c.dav.lockingutils.info" class DAVLockmanager(object): """ >>> from zope.interface.verify import verifyObject >>> from zope.locking import utility, utils >>> from zope.locking.adapters import TokenBroker >>> from zope.traversing.browser.absoluteurl import absoluteURL >>> file = Demo() Before we register a ITokenUtility utility make sure that the DAVLockmanager is not lockable. >>> adapter = DAVLockmanager(file) >>> adapter.islockable() False Now create and register a ITokenUtility utility. >>> util = utility.TokenUtility() >>> zope.component.getGlobalSiteManager().registerUtility( ... util, zope.locking.interfaces.ITokenUtility) >>> zope.component.getGlobalSiteManager().registerAdapter( ... TokenBroker, (zope.interface.Interface,), ... zope.locking.interfaces.ITokenBroker) >>> import datetime >>> import pytz >>> def hackNow(): ... return datetime.datetime(2006, 7, 25, 23, 49, 51) >>> oldNow = utils.now >>> utils.now = hackNow Test the DAVLockmanager implements the descried interface. >>> adapter = DAVLockmanager(file) >>> verifyObject(z3c.dav.interfaces.IDAVLockmanager, adapter) True The adapter should also be lockable. >>> adapter.islockable() True Exclusive lock token -------------------- >>> locktoken = adapter.lock(u'exclusive', u'write', ... u'Michael', datetime.timedelta(seconds = 3600), '0') >>> adapter.islocked() True >>> activelock = adapter.getActivelock(locktoken) >>> activelock.lockscope [u'exclusive'] >>> activelock.locktype [u'write'] >>> activelock.depth '0' >>> activelock.timeout u'Second-3600' >>> activelock.lockroot '/dummy' >>> activelock.owner u'Michael' >>> len(activelock.locktoken) 1 >>> activelock.locktoken #doctest:+ELLIPSIS ['opaquelocktoken:... >>> util.get(file) == activelock.token True >>> zope.locking.interfaces.IExclusiveLock.providedBy(activelock.token) True Now refresh the timeout on the locktoken. >>> adapter.refreshlock(datetime.timedelta(seconds = 7200)) >>> adapter.getActivelock(locktoken).timeout u'Second-7200' Unlock the resource. >>> adapter.unlock(locktoken) >>> util.get(file) is None True >>> adapter.islocked() False >>> adapter.getActivelock(locktoken) is None True We can't unlock the resource twice. >>> adapter.unlock(locktoken) Traceback (most recent call last): ... ConflictError: The context is not locked, so we can't unlock it. Shared locking -------------- >>> locktoken = adapter.lock(u'shared', u'write', u'Michael', ... datetime.timedelta(seconds = 3600), '0') >>> activelock = adapter.getActivelock(locktoken) >>> activelock.lockscope [u'shared'] >>> len(activelock.locktoken) 1 >>> activelock.locktoken #doctest:+ELLIPSIS ['opaquelocktoken:... >>> sharedlocktoken = util.get(file) >>> sharedlocktoken == activelock.token True >>> zope.locking.interfaces.ISharedLock.providedBy(activelock.token) True Make sure that the meta-data on the lock token is correct. >>> len(sharedlocktoken.annotations[WEBDAV_LOCK_KEY]) 2 >>> sharedlocktoken.annotations[WEBDAV_LOCK_KEY]['principal_ids'] ['michael'] >>> len(sharedlocktoken.annotations[WEBDAV_LOCK_KEY][locktoken]) 2 >>> sharedlocktoken.annotations[WEBDAV_LOCK_KEY][locktoken]['owner'] u'Michael' >>> sharedlocktoken.annotations[WEBDAV_LOCK_KEY][locktoken]['depth'] '0' >>> sharedlocktoken.duration datetime.timedelta(0, 3600) >>> sharedlocktoken.principal_ids frozenset(['michael']) We can have multiple WebDAV shared locks on a resource. We implement this by storing the data for the second lock token in the annotations. >>> locktoken2 = adapter.lock(u'shared', u'write', u'Michael 2', ... datetime.timedelta(seconds = 1800), '0') >>> len(sharedlocktoken.annotations[WEBDAV_LOCK_KEY]) 3 We need to keep track of the principal associated with the lock token our selves as we can only create one shared lock token with zope.locking, and after removing the first shared lock the zope.locking token will be removed. >>> sharedlocktoken.annotations[WEBDAV_LOCK_KEY]['principal_ids'] ['michael', 'michael'] >>> sharedlocktoken.annotations[WEBDAV_LOCK_KEY][locktoken2]['owner'] u'Michael 2' >>> sharedlocktoken.annotations[WEBDAV_LOCK_KEY][locktoken2]['depth'] '0' Note that the timeout is shared across the two WebDAV tokens. After creating the second shared lock the duration changed to the last lock taken out. We need to do this in order to make sure that the token is ended at some point. What we probable want to do here is to take the largest remaining duration so that a lock token doesn't expire earlier then expected but might last slightly longer then expected for some one. >>> sharedlocktoken.duration datetime.timedelta(0, 1800) After unlocking the first first locktoken the information for this token is removed. >>> adapter.unlock(locktoken) >>> util.get(file) == sharedlocktoken True >>> len(sharedlocktoken.annotations[WEBDAV_LOCK_KEY]) 2 >>> sharedlocktoken.annotations[WEBDAV_LOCK_KEY]['principal_ids'] ['michael'] >>> locktoken in sharedlocktoken.annotations[WEBDAV_LOCK_KEY] False >>> locktoken2 in sharedlocktoken.annotations[WEBDAV_LOCK_KEY] True >>> adapter.unlock(locktoken2) >>> util.get(file) is None True If an exclusive lock already exists on a file from an other application then this should fail with an already locked response. >>> exclusivelock = util.register( ... zope.locking.tokens.ExclusiveLock(file, 'michael')) >>> adapter.lock(u'shared', u'write', u'Michael2', ... datetime.timedelta(seconds = 3600), '0') #doctest:+ELLIPSIS Traceback (most recent call last): ... AlreadyLocked: <z3c.davapp.zopelocking.tests.Demo object at ...>: None >>> exclusivelock.end() If a shared lock is taken out on the resource, then this lock token is probable not annotated with the extra information required by WebDAV. >>> sharedlock = util.register( ... zope.locking.tokens.SharedLock(file, ('michael',))) >>> len(sharedlock.annotations) 0 >>> locktoken = adapter.lock(u'shared', u'write', u'Michael 2', ... datetime.timedelta(seconds = 3600), '0') >>> len(sharedlock.annotations[WEBDAV_LOCK_KEY]) 2 >>> sharedlock.annotations[WEBDAV_LOCK_KEY]['principal_ids'] ['michael'] >>> locktoken in sharedlock.annotations[WEBDAV_LOCK_KEY] True >>> sharedlock.principal_ids frozenset(['michael']) >>> sharedlock.end() Recursive lock support ---------------------- >>> demofolder = DemoFolder() >>> demofolder['demo'] = file >>> adapter = DAVLockmanager(demofolder) >>> locktoken = adapter.lock(u'exclusive', u'write', ... u'MichaelK', datetime.timedelta(seconds = 3600), 'infinity') >>> demotoken = util.get(file) >>> interfaces.IIndirectToken.providedBy(demotoken) True >>> activelock = adapter.getActivelock(locktoken) >>> activelock.lockroot '/dummy/' >>> DAVLockmanager(file).getActivelock(locktoken).lockroot '/dummy/' >>> absoluteURL(file, None) '/dummy/dummy' >>> activelock.lockscope [u'exclusive'] Already locked -------------- Adapter is now defined on the demofolder. >>> adapter.lock(u'exclusive', u'write', u'Michael', ... datetime.timedelta(seconds = 100), 'infinity') #doctest:+ELLIPSIS Traceback (most recent call last): ... AlreadyLocked... >>> adapter.islocked() True >>> adapter.unlock(locktoken[0]) >>> locktoken = DAVLockmanager(file).lock(u'shared', u'write', ... u'Michael', datetime.timedelta(seconds = 3600), '0') >>> adapter.lock(u'shared', u'write', u'Michael 2', ... datetime.timedelta(seconds = 3600), 'infinity') #doctest:+ELLIPSIS Traceback (most recent call last): ... AlreadyLocked:... Some error conditions --------------------- >>> adapter.lock(u'notexclusive', u'write', u'Michael', ... datetime.timedelta(seconds = 100), 'infinity') # doctest:+ELLIPSIS Traceback (most recent call last): ... UnprocessableError: ... Cleanup ------- >>> zope.component.getGlobalSiteManager().unregisterUtility( ... util, zope.locking.interfaces.ITokenUtility) True >>> zope.component.getGlobalSiteManager().unregisterAdapter( ... TokenBroker, (zope.interface.Interface,), ... zope.locking.interfaces.ITokenBroker) True >>> utils.now = oldNow """ zope.interface.implements(z3c.dav.interfaces.IDAVLockmanager) zope.component.adapts(zope.interface.Interface) def __init__(self, context): self.context = self.__parent__ = context def islockable(self): utility = zope.component.queryUtility( zope.locking.interfaces.ITokenUtility, context = self.context, default = None) return utility is not None def maybeRecursivelyLockIndirectly(self, utility, context, roottoken, depth): if depth == "infinity" and IReadContainer.providedBy(context): for subob in context.values(): token = utility.get(subob) if token: raise z3c.dav.interfaces.AlreadyLocked( subob, message = u"Sub-object is already locked") indirecttoken = indirecttokens.IndirectToken(subob, roottoken) utility.register(indirecttoken) self.maybeRecursivelyLockIndirectly( utility, subob, roottoken, depth) def register(self, utility, token): try: return utility.register(token) except zope.locking.interfaces.RegistrationError: raise z3c.dav.interfaces.AlreadyLocked( token.context, message = u"Context is locked") def lock(self, scope, type, owner, duration, depth): principal_id = getPrincipalId() utility = zope.component.getUtility( zope.locking.interfaces.ITokenUtility, context = self.context) locktoken = z3c.dav.locking.generateLocktoken() if scope == u"exclusive": roottoken = self.register( utility, zope.locking.tokens.ExclusiveLock( self.context, principal_id, duration = duration)) annots = roottoken.annotations[WEBDAV_LOCK_KEY] = OOBTree() elif scope == u"shared": # A successful request for a new shared lock MUST result in the # generation of a unique lock associated with the requesting # principal. Thus if five principals have taken out shared write # locks on the same resource there will be five locks and five # lock tokens, one for each principal. roottoken = utility.get(self.context) if roottoken is None: roottoken = self.register( utility, zope.locking.tokens.SharedLock( self.context, (principal_id,), duration = duration)) annots = roottoken.annotations[WEBDAV_LOCK_KEY] = OOBTree() annots["principal_ids"] = [principal_id] else: if not zope.locking.interfaces.ISharedLock.providedBy(roottoken): # We need to some how figure out how to add preconditions # code to the exceptions. As a 'no-conflicting-lock' # precondition code is valid here. raise z3c.dav.interfaces.AlreadyLocked( self.context, message = u"""A conflicting lock already exists for this resource""") roottoken.add((principal_id,)) roottoken.duration = duration if WEBDAV_LOCK_KEY not in roottoken.annotations: # Locked by an alternative application annots = roottoken.annotations[WEBDAV_LOCK_KEY] = OOBTree() # Use OOBTree here annots["principal_ids"] = [principal_id] else: annots = roottoken.annotations[WEBDAV_LOCK_KEY] annots["principal_ids"].append(principal_id) else: raise z3c.dav.interfaces.UnprocessableError( self.context, message = u"Invalid lockscope supplied to the lock manager") annots[locktoken] = OOBTree() annots[locktoken].update({"owner": owner, "depth": depth}) self.maybeRecursivelyLockIndirectly( utility, self.context, roottoken, depth) return locktoken def getActivelock(self, locktoken, request = None): # Note that this is only used for testing purposes. if self.islocked(): token = zope.locking.interfaces.ITokenBroker(self.context).get() return properties.DAVActiveLock( locktoken, token, self.context, request) return None def refreshlock(self, timeout): token = zope.locking.interfaces.ITokenBroker(self.context).get() token.duration = timeout def unlock(self, locktoken): utility = zope.component.getUtility( zope.locking.interfaces.ITokenUtility, context = self.context) token = utility.get(self.context) if token is None: raise z3c.dav.interfaces.ConflictError( self.context, message = "The context is not locked, so we can't unlock it.") if interfaces.IIndirectToken.providedBy(token): token = token.roottoken if zope.locking.interfaces.IExclusiveLock.providedBy(token): token.end() elif zope.locking.interfaces.ISharedLock.providedBy(token): principal_id = getPrincipalId() annots = token.annotations[WEBDAV_LOCK_KEY] del annots[locktoken] annots["principal_ids"].remove(principal_id) if principal_id not in annots["principal_ids"]: # will end token if no principals left token.remove((principal_id,)) else: raise ValueError("Unknown lock token") def islocked(self): tokenBroker = zope.locking.interfaces.ITokenBroker(self.context) return tokenBroker.get() is not None def getPrincipalId(): principal_ids = [ participation.principal.id for participation in zope.security.management.getInteraction().participations] if len(principal_ids) != 1: raise ValueError("There must be only one participant principal") principal_id = principal_ids[0] return principal_id ############################################################################### # # These event handlers enforce the WebDAV lock model. Namely on modification # we need to check the `IF` header to see if the client knows about any # locks on the object, and if they don't then a AlreadyLocked exception # should be raised. # # We only do these checks for non-browser methods (i.e. not GET, HEAD or POST) # as web browsers never send the `IF` header, and will always fail this test. # For the browser methods we should use a specialized security policy like # zc.tokenpolicy instead. # # Note that the events that tigger these handlers are always emitted after # the fact, so any security assertions that might raise an exception will # have done so before these tests, so if any condition outside the WebDAV # lock model occurs then an AlreadyLocked exception must be raised which will # abort the transaction and set the appropriate status and body to send to # the client # ############################################################################### BROWSER_METHODS = ("GET", "HEAD", "POST") @zope.component.adapter(zope.app.container.interfaces.IObjectMovedEvent) def indirectlyLockObjectOnMovedEvent(event): """ This event handler listens for IObjectAddedEvent, IObjectRemovedEvent as while as IObjectMovedEvents and is responsible for testing whether the container modification in question is allowed. >>> import UserDict >>> import datetime >>> from zope.locking import utility >>> from zope.publisher.browser import TestRequest >>> from zope.security.proxy import removeSecurityProxy >>> from zope.app.container.contained import ObjectAddedEvent >>> from zope.app.container.contained import ObjectRemovedEvent >>> from zope.app.container.contained import ObjectMovedEvent >>> class ReqAnnotation(UserDict.IterableUserDict): ... zope.interface.implements(zope.annotation.interfaces.IAnnotations) ... def __init__(self, request): ... self.data = request._environ.setdefault('annotation', {}) >>> zope.component.getGlobalSiteManager().registerAdapter( ... ReqAnnotation, (zope.publisher.interfaces.http.IHTTPRequest,)) >>> class Statetokens(object): ... zope.interface.implements(z3c.dav.ifvalidator.IStateTokens) ... def __init__(self, context, request, view): ... self.context = context ... schemes = ('', 'opaquetoken') ... @property ... def tokens(self): ... context = removeSecurityProxy(self.context) # ??? ... if getattr(context, '_tokens', None) is not None: ... return context._tokens ... return [] >>> zope.component.getGlobalSiteManager().registerAdapter( ... Statetokens, (None, TestRequest, None)) Now some content. >>> util = utility.TokenUtility() >>> zope.component.getGlobalSiteManager().registerUtility( ... util, zope.locking.interfaces.ITokenUtility) >>> demofolder = DemoFolder() Nothing is locked at this stage so the test passes. >>> file1 = Demo() >>> demofolder['file1'] = file1 >>> indirectlyLockObjectOnMovedEvent( ... ObjectAddedEvent(file1, demofolder, 'file1')) >>> util.get(file1) is None True If a collection is locked with an infinite depth lock then all member resources are indirectly locked. Any resource that is added to this collection then becomes indirectly locked against the lockroot for the collection. >>> adapter = DAVLockmanager(demofolder) >>> locktoken = adapter.lock(u'exclusive', u'write', ... u'MichaelK', datetime.timedelta(seconds = 3600), 'infinity') >>> file2 = Demo() >>> demofolder['file2'] = file2 >>> indirectlyLockObjectOnMovedEvent( ... ObjectAddedEvent(file2, demofolder, 'file2')) >>> file2lock = util.get(file2) >>> interfaces.IIndirectToken.providedBy(file2lock) True >>> file2lock.roottoken == util.get(demofolder) True If we rerun the event handler the new object is already locked, we get an AlreadyLocked exception as I don't know how to merge lock tokens, which might be possible under circumstances. >>> indirectlyLockObjectOnMovedEvent( ... ObjectAddedEvent(file2, demofolder, 'file2')) #doctest:+ELLIPSIS Traceback (most recent call last): ... AlreadyLocked: <z3c.davapp.zopelocking.tests.Demo object at ...>: None An `IF` header must be present in the request object in-order for us to be allowed to remove this. >>> file2._tokens = ['statetoken'] >>> indirectlyLockObjectOnMovedEvent( ... ObjectRemovedEvent(file2, demofolder, 'file2')) #doctest:+ELLIPSIS Traceback (most recent call last): ... AlreadyLocked: <z3c.davapp.zopelocking.tests.Demo object at ...>: None Now if we set the request annotation right the event handler doesn't raise a AlreadyLocked request. >>> request = zope.security.management.getInteraction().participations[0] >>> ReqAnnotation(request)[z3c.dav.ifvalidator.STATE_ANNOTS] = { ... '/file2': {'statetoken': True}} >>> indirectlyLockObjectOnMovedEvent( ... ObjectRemovedEvent(file2, demofolder, 'file2')) `IF` access was granted to the source folder, and the destination folder is not locked is this is allowed. >>> demofolder2 = DemoFolder() >>> indirectlyLockObjectOnMovedEvent( ... ObjectMovedEvent(file2, demofolder, 'file2', ... demofolder2, 'file3')) Now the state token for the demofolder2 object matches a state token in the `IF` header but it isn't specific for this resource or any of its parents. >>> demofolder['subfolder'] = demofolder2 >>> adapter2 = DAVLockmanager(demofolder2) >>> locktoken2 = adapter2.lock(u'exclusive', u'write', u'Michael 2', ... datetime.timedelta(seconds = 3600), 'infinity') >>> demofolder2._tokens = ['statetoken'] >>> indirectlyLockObjectOnMovedEvent( ... ObjectMovedEvent(file2, demofolder, 'file2', ... demofolder2, 'file3')) #doctest:+ELLIPSIS Traceback (most recent call last): ... AlreadyLocked: <z3c.davapp.zopelocking.tests.Demo object at ...>: None But if we update the request annotation, we still fail because the object we are moving is still locked. >>> ReqAnnotation(request)[ ... z3c.dav.ifvalidator.STATE_ANNOTS]['/subfolder'] = { ... 'statetoken': True} >>> indirectlyLockObjectOnMovedEvent( ... ObjectMovedEvent(file2, demofolder, 'file2', ... demofolder2, 'file3')) #doctest:+ELLIPSIS Traceback (most recent call last): ... AlreadyLocked: <z3c.davapp.zopelocking.tests.Demo object at ...>: None Move to same folder, the destination folder is locked, but the object is not. >>> file3 = Demo() >>> demofolder['file3'] = file3 >>> indirectlyLockObjectOnMovedEvent( ... ObjectMovedEvent(file3, demofolder, 'file3', ... demofolder, 'file4')) Indirect tokens. >>> roottoken = util.get(demofolder) >>> zope.locking.interfaces.IExclusiveLock.providedBy(roottoken) True >>> subfolder = DemoFolder() >>> demofolder['subfolder'] = subfolder >>> indirectlyLockObjectOnMovedEvent( ... ObjectAddedEvent(subfolder, demofolder, 'subfolder')) >>> subtoken = util.get(subfolder) >>> interfaces.IIndirectToken.providedBy(subtoken) True >>> subtoken.roottoken == roottoken True >>> subsubfolder = DemoFolder() >>> subfolder['subfolder'] = subsubfolder >>> indirectlyLockObjectOnMovedEvent( ... ObjectAddedEvent(subsubfolder, subfolder, 'subsubfolder')) >>> subsubtoken = util.get(subsubfolder) >>> interfaces.IIndirectToken.providedBy(subsubtoken) True >>> subsubtoken.roottoken == roottoken True But this eventhandler never raises exceptions for any of the browser methods, GET, HEAD, POST. >>> del ReqAnnotation(request)[z3c.dav.ifvalidator.STATE_ANNOTS] >>> request.method = 'POST' >>> indirectlyLockObjectOnMovedEvent( ... ObjectRemovedEvent(file2, demofolder, 'file2')) Cleanup ------- >>> zope.component.getGlobalSiteManager().unregisterUtility( ... util, zope.locking.interfaces.ITokenUtility) True >>> zope.component.getGlobalSiteManager().unregisterAdapter( ... ReqAnnotation, (zope.publisher.interfaces.http.IHTTPRequest,)) True >>> zope.component.getGlobalSiteManager().unregisterAdapter( ... Statetokens, (None, TestRequest, None)) True """ utility = zope.component.queryUtility( zope.locking.interfaces.ITokenUtility, context = event.object) if not utility: # If there is no utility then is nothing that we can check against. return # This is an hack to get at the current request object interaction = zope.security.management.queryInteraction() if interaction: request = interaction.participations[0] if zope.publisher.interfaces.http.IHTTPRequest.providedBy(request) \ and request.method not in BROWSER_METHODS: objectToken = utility.get(event.object) if objectToken: # The object is been moved out of its parent - hance we need # to validate that we are allowed to perform this # modification. if event.oldParent is not None and \ not z3c.dav.ifvalidator.matchesIfHeader( event.object, request): raise z3c.dav.interfaces.AlreadyLocked( event.object, "Locked object cannot be moved ") # Otherwise since the oldParent hasn't changed we don't # need to check if we are allowed to perform this action, # this is probable a copy. if event.newParent is not None: # Probable an object added event, the object lock must be # consistent we the lock on its parent. parentToken = utility.get(event.newParent) if parentToken is not None: if not z3c.dav.ifvalidator.matchesIfHeader( event.newParent, request): raise z3c.dav.interfaces.AlreadyLocked( event.object, "Destination folder is locked") if objectToken is not None: # XXX - this needs to be smarter. We the lock on # the parent as depth '0' or the objectToken is # indirectly locked against the parentToken then # we shouldn't raise this exception. raise z3c.dav.interfaces.AlreadyLocked( event.object, "Locked object cannot be moved.") if interfaces.IIndirectToken.providedBy(parentToken): parentToken = parentToken.roottoken utility.register( indirecttokens.IndirectToken(event.object, parentToken)) @zope.component.adapter(zope.lifecycleevent.interfaces.IObjectModifiedEvent) def checkLockedOnModify(event): """ When a content object is modified we need to check that the client submitted an `IF` header that corresponds with the lock. >>> import UserDict >>> import datetime >>> from zope.locking import utility >>> import zope.publisher.interfaces.http >>> from zope.publisher.browser import TestRequest >>> from zope.security.proxy import removeSecurityProxy >>> from zope.lifecycleevent import ObjectModifiedEvent Some adapters needed to represent the data stored in the `IF` header, and the current state tokens for the content. >>> class ReqAnnotation(UserDict.IterableUserDict): ... zope.interface.implements(zope.annotation.interfaces.IAnnotations) ... def __init__(self, request): ... self.data = request._environ.setdefault('annotation', {}) >>> zope.component.getGlobalSiteManager().registerAdapter( ... ReqAnnotation, (zope.publisher.interfaces.http.IHTTPRequest,)) >>> class Statetokens(object): ... zope.interface.implements(z3c.dav.ifvalidator.IStateTokens) ... def __init__(self, context, request, view): ... self.context = context ... schemes = ('', 'opaquetoken') ... @property ... def tokens(self): ... context = removeSecurityProxy(self.context) # ??? ... if getattr(context, '_tokens', None) is not None: ... return context._tokens ... return [] >>> zope.component.getGlobalSiteManager().registerAdapter( ... Statetokens, (None, TestRequest, None)) >>> util = utility.TokenUtility() >>> zope.component.getGlobalSiteManager().registerUtility( ... util, zope.locking.interfaces.ITokenUtility) >>> demofolder = DemoFolder() >>> demofile = Demo() >>> demofolder['demofile'] = demofile The test passes when the object is not locked. >>> checkLockedOnModify(ObjectModifiedEvent(demofile)) Lock the file and setup the request annotation. >>> adapter = DAVLockmanager(demofile) >>> locktoken = adapter.lock(u'exclusive', u'write', ... u'Michael', datetime.timedelta(seconds = 3600), '0') >>> request = zope.security.management.getInteraction().participations[0] >>> ReqAnnotation(request)[z3c.dav.ifvalidator.STATE_ANNOTS] = { ... '/demofile': {'statetoken': True}} >>> demofile._tokens = ['wrongstatetoken'] # wrong token. >>> checkLockedOnModify(ObjectModifiedEvent(demofile)) #doctest:+ELLIPSIS Traceback (most recent call last): ... AlreadyLocked: <z3c.davapp.zopelocking.tests.Demo object at ...>: None With the correct lock token submitted the test passes. >>> demofile._tokens = ['statetoken'] # wrong token. >>> checkLockedOnModify(ObjectModifiedEvent(demofile)) Child of locked token. >>> ReqAnnotation(request)[z3c.dav.ifvalidator.STATE_ANNOTS] = { ... '/': {'statetoken': True}} >>> demofile._tokens = ['statetoken'] >>> checkLockedOnModify(ObjectModifiedEvent(demofile)) Cleanup ------- >>> zope.component.getGlobalSiteManager().unregisterAdapter( ... ReqAnnotation, (zope.publisher.interfaces.http.IHTTPRequest,)) True >>> zope.component.getGlobalSiteManager().unregisterAdapter( ... Statetokens, (None, TestRequest, None)) True >>> zope.component.getGlobalSiteManager().unregisterUtility( ... util, zope.locking.interfaces.ITokenUtility) True """ # This is an hack to get at the current request object interaction = zope.security.management.queryInteraction() if interaction: request = interaction.participations[0] if zope.publisher.interfaces.http.IHTTPRequest.providedBy(request) \ and request.method not in BROWSER_METHODS: if not z3c.dav.ifvalidator.matchesIfHeader(event.object, request): raise z3c.dav.interfaces.AlreadyLocked( event.object, "Modifing locked object is not permitted.")
z3c.davapp.zopelocking
/z3c.davapp.zopelocking-1.0b.tar.gz/z3c.davapp.zopelocking-1.0b/src/z3c/davapp/zopelocking/manager.py
manager.py
__docformat__ = 'restructuredtext' from zope import component from zope import interface import zope.locking.interfaces import zope.publisher.interfaces.http from zope.traversing.browser.absoluteurl import absoluteURL from z3c.dav.coreproperties import ILockEntry, IDAVSupportedlock, \ IActiveLock import z3c.dav.interfaces import interfaces from manager import WEBDAV_LOCK_KEY ################################################################################ # # zope.locking adapters. # ################################################################################ class ExclusiveLockEntry(object): interface.implements(ILockEntry) lockscope = [u"exclusive"] locktype = [u"write"] class SharedLockEntry(object): interface.implements(ILockEntry) lockscope = [u"shared"] locktype = [u"write"] @component.adapter(interface.Interface, z3c.dav.interfaces.IWebDAVRequest) @interface.implementer(IDAVSupportedlock) def DAVSupportedlock(context, request): """ This adapter retrieves the data for rendering in the `{DAV:}supportedlock` property. The `{DAV:}supportedlock` property provides a listing of lock capabilities supported by the resource. When their is no ITokenUtility registered with the system then we can't lock any content object and so this property is undefined. >>> DAVSupportedlock(None, None) is None True >>> from zope.locking import tokens >>> from zope.locking.utility import TokenUtility >>> util = TokenUtility() >>> component.getGlobalSiteManager().registerUtility( ... util, zope.locking.interfaces.ITokenUtility) zope.locking supported both the exclusive and shared lock tokens. >>> slock = DAVSupportedlock(None, None) >>> len(slock.supportedlock) 2 >>> exclusive, shared = slock.supportedlock >>> exclusive.lockscope [u'exclusive'] >>> exclusive.locktype [u'write'] >>> shared.lockscope [u'shared'] >>> shared.locktype [u'write'] Cleanup >>> component.getGlobalSiteManager().unregisterUtility( ... util, zope.locking.interfaces.ITokenUtility) True """ utility = component.queryUtility(zope.locking.interfaces.ITokenUtility, context = context, default = None) if utility is None: return None return DAVSupportedlockAdapter() class DAVSupportedlockAdapter(object): interface.implements(IDAVSupportedlock) component.adapts(interface.Interface, z3c.dav.interfaces.IWebDAVRequest) @property def supportedlock(self): return [ExclusiveLockEntry(), SharedLockEntry()] class DAVActiveLock(object): """ This adapter is responsible for the data for the `{DAV:}activelock` XML element. This XML element occurs within the `{DAV:}lockdiscovery` property. >>> import datetime >>> import pytz >>> from cStringIO import StringIO >>> from BTrees.OOBTree import OOBTree >>> from zope.interface.verify import verifyObject >>> import zope.locking.utils >>> from zope.locking import tokens >>> from zope.locking.utility import TokenUtility >>> from z3c.dav.publisher import WebDAVRequest >>> import indirecttokens >>> def hackNow(): ... return datetime.datetime(2007, 4, 7, tzinfo = pytz.utc) >>> oldNow = zope.locking.utils.now >>> zope.locking.utils.now = hackNow >>> resource = DemoFolder() >>> request = WebDAVRequest(StringIO(''), {}) Now register a ITokenUtility utility and lock the resource with it. >>> util = TokenUtility() >>> component.getGlobalSiteManager().registerUtility( ... util, zope.locking.interfaces.ITokenUtility) >>> locktoken = tokens.ExclusiveLock( ... resource, 'michael', datetime.timedelta(hours = 1)) >>> locktoken = util.register(locktoken) DAVActiveLock is still None since their is no adapter from the demo content object to zope.locking.interfaces.ITokenBroker. This is part of the zope.locking installation that hasn't been completed yet. >>> activelock = DAVActiveLock(None, locktoken, resource, request) >>> IActiveLock.providedBy(activelock) True >>> verifyObject(IActiveLock, activelock) True Now test the data managed by the current activelock property. >>> activelock.lockscope [u'exclusive'] >>> activelock.locktype [u'write'] >>> activelock.timeout u'Second-3600' >>> activelock.lockroot '/dummy/' The depth attribute is required by the WebDAV specification. But this information is stored by the z3c.dav.lockingutils in the lock token's annotation. But if a lock token is taken out by an alternative Zope3 application that uses the zope.locking package then this information will must likely not be set up. So this adapter should provide reasonable default values for this information. Later we will set up the lock token's annotation data to store this information. The data for the owner and locktoken XML elements are also stored on within the lock tokens annotation key but these XML elements are not required by the WebDAV specification so this data just defaults to None. >>> activelock.depth '0' >>> activelock.owner is None True >>> activelock.locktoken is None True Now if we try and render this information all the required fields, as specified by the WebDAV specification get rendered. >>> lockdiscovery = DAVLockdiscovery(resource, request) >>> davwidget = z3c.dav.properties.getWidget( ... z3c.dav.coreproperties.lockdiscovery, ... lockdiscovery, request) >>> print etree.tostring(davwidget.render()) #doctest:+XMLDATA <lockdiscovery xmlns="DAV:"> <activelock> <lockscope><exclusive /></lockscope> <locktype><write /></locktype> <depth>0</depth> <timeout>Second-3600</timeout> <lockroot>/dummy/</lockroot> </activelock> </lockdiscovery> We use the lock tokens annotation to store the data for the owner, depth and locktoken attributes. >>> locktokendata= locktoken.annotations[WEBDAV_LOCK_KEY] = OOBTree() >>> locktokendata['simpletoken'] = OOBTree() >>> locktokendata['simpletoken']['depth'] = 'testdepth' >>> locktokendata['simpletoken']['owner'] = '<owner xmlns="DAV:">Me</owner>' After updating the lock token's annotations we need to regenerate the activelock adapter so that the tokendata internal attribute is setup correctly. >>> activelock = DAVActiveLock( ... 'simpletoken', locktoken, resource, request) The owner attribute is not required by the WebDAV specification, but we can see it anyways, and similarly for the locktoken attribute. >>> activelock.owner '<owner xmlns="DAV:">Me</owner>' Each lock token on a resource as at most one `token` associated with it, but in order to display this information correctly we must return a a list with one item. >>> activelock.locktoken ['simpletoken'] >>> lockdiscovery = DAVLockdiscovery(resource, request) >>> davwidget = z3c.dav.properties.getWidget( ... z3c.dav.coreproperties.lockdiscovery, ... lockdiscovery, request) >>> print etree.tostring(davwidget.render()) #doctest:+XMLDATA <lockdiscovery xmlns="DAV:"> <activelock> <lockscope><exclusive /></lockscope> <locktype><write /></locktype> <depth>testdepth</depth> <owner>Me</owner> <timeout>Second-3600</timeout> <locktoken><href>simpletoken</href></locktoken> <lockroot>/dummy/</lockroot> </activelock> </lockdiscovery> Test the indirect locktoken. These are used when we try and lock a collection with the depth header set to `infinity`. These lock tokens share the same annotation information, expiry information and lock token, as the top level lock token. >>> resource['demo'] = Demo() >>> sublocktoken = indirecttokens.IndirectToken( ... resource['demo'], locktoken) >>> sublocktoken = util.register(sublocktoken) >>> activelock = DAVActiveLock( ... 'simpletoken', sublocktoken, resource['demo'], request) >>> verifyObject(IActiveLock, activelock) True >>> activelock.lockscope [u'exclusive'] >>> activelock.locktype [u'write'] >>> activelock.depth 'testdepth' >>> activelock.owner '<owner xmlns="DAV:">Me</owner>' >>> activelock.timeout u'Second-3600' >>> activelock.locktoken ['simpletoken'] >>> activelock.lockroot '/dummy/' Now rendering the lockdiscovery DAV widget for this new resource we get the following. >>> lockdiscovery = DAVLockdiscovery(resource['demo'], request) >>> davwidget = z3c.dav.properties.getWidget( ... z3c.dav.coreproperties.lockdiscovery, ... lockdiscovery, request) >>> print etree.tostring(davwidget.render()) #doctest:+XMLDATA <lockdiscovery xmlns="DAV:"> <activelock> <lockscope><exclusive /></lockscope> <locktype><write /></locktype> <depth>testdepth</depth> <owner>Me</owner> <timeout>Second-3600</timeout> <locktoken><href>simpletoken</href></locktoken> <lockroot>/dummy/</lockroot> </activelock> </lockdiscovery> >>> locktoken.end() Now a locktoken from an other application could be taken out on our demofolder that we know very little about. For example, a zope.locking.tokens.EndableFreeze` lock token. It should be displayed as an activelock on the resource but since we don't know if the scope of this token is an `{DAV:}exclusive` or `{DAV:}shared` (the only lock scopes currently supported by WebDAV), we will render this information as an empty XML element. >>> locktoken = tokens.EndableFreeze( ... resource, datetime.timedelta(hours = 1)) >>> locktoken = util.register(locktoken) >>> activelock = DAVActiveLock(None, locktoken, resource, request) >>> IActiveLock.providedBy(activelock) True >>> activelock.timeout u'Second-3600' >>> activelock.locktype [u'write'] Now the locktoken is None so no WebDAV client should be able to a resource or more likely they shouldn't be able to take out a new lock on this resource, since the `IF` conditional header shored fail. >>> activelock.locktoken is None True So far so good. But the EndableFreeze token doesn't correspond to any lock scope known by this WebDAV implementation so when we try and access we just return a empty list. This ensures the `{DAV:}lockscope` element gets rendered by its IDAVWidget but it doesn't contain any information. >>> activelock.lockscope [] >>> activelock.lockscope != z3c.dav.coreproperties.IActiveLock['lockscope'].missing_value True Rending this lock token we get the following. >>> lockdiscovery = DAVLockdiscovery(resource, request) >>> davwidget = z3c.dav.properties.getWidget( ... z3c.dav.coreproperties.lockdiscovery, ... lockdiscovery, request) >>> print etree.tostring(davwidget.render()) #doctest:+XMLDATA <lockdiscovery xmlns="DAV:"> <activelock> <lockscope></lockscope> <locktype><write /></locktype> <depth>0</depth> <timeout>Second-3600</timeout> <lockroot>/dummy/</lockroot> </activelock> </lockdiscovery> Unlock the resource. >>> locktoken.end() Now not all lock tokens have a duration associated with them. In this case the timeout is None, as it is not fully required by the WebDAV specification and all the other attributes will have the default values as tested previously. >>> locktoken = tokens.ExclusiveLock(resource, 'michael') >>> locktoken = util.register(locktoken) >>> activelock = DAVActiveLock(None, locktoken, resource, request) >>> verifyObject(IActiveLock, activelock) True >>> activelock.timeout is None True >>> lockdiscovery = DAVLockdiscovery(resource, request) >>> davwidget = z3c.dav.properties.getWidget( ... z3c.dav.coreproperties.lockdiscovery, ... lockdiscovery, request) >>> print etree.tostring(davwidget.render()) #doctest:+XMLDATA <lockdiscovery xmlns="DAV:"> <activelock> <lockscope><exclusive /></lockscope> <locktype><write /></locktype> <depth>0</depth> <lockroot>/dummy/</lockroot> </activelock> </lockdiscovery> Cleanup >>> zope.locking.utils.now = oldNow # undo time hack >>> component.getGlobalSiteManager().unregisterUtility( ... util, zope.locking.interfaces.ITokenUtility) True """ interface.implements(IActiveLock) def __init__(self, locktoken, token, context, request): self.context = self.__parent__ = context self._locktoken = locktoken self.token = token self.tokendata = token.annotations.get( WEBDAV_LOCK_KEY, {}).get(locktoken, {}) self.request = request @property def lockscope(self): if interfaces.IIndirectToken.providedBy(self.token): roottoken = self.token.roottoken else: roottoken = self.token if zope.locking.interfaces.IExclusiveLock.providedBy(roottoken): return [u"exclusive"] elif zope.locking.interfaces.ISharedLock.providedBy(roottoken): return [u"shared"] return [] @property def locktype(self): return [u"write"] @property def depth(self): return self.tokendata.get("depth", "0") @property def owner(self): return self.tokendata.get("owner", None) @property def timeout(self): remaining = self.token.remaining_duration if remaining is None: return None return u"Second-%d" % remaining.seconds @property def locktoken(self): return self._locktoken and [self._locktoken] @property def lockroot(self): if interfaces.IIndirectToken.providedBy(self.token): root = self.token.roottoken.context else: root = self.token.context return absoluteURL(root, self.request) @component.adapter( interface.Interface, zope.publisher.interfaces.http.IHTTPRequest) @interface.implementer(z3c.dav.coreproperties.IDAVLockdiscovery) def DAVLockdiscovery(context, request): """ This adapter is responsible for getting the data for the `{DAV:}lockdiscovery` property. >>> import datetime >>> from BTrees.OOBTree import OOBTree >>> from zope.interface.verify import verifyObject >>> from zope.locking import tokens >>> from zope.locking.utility import TokenUtility >>> from zope.locking.adapters import TokenBroker >>> from z3c.dav.publisher import WebDAVRequest >>> from cStringIO import StringIO >>> resource = Demo() >>> request = WebDAVRequest(StringIO(''), {}) >>> DAVLockdiscovery(resource, request) is None True >>> util = TokenUtility() >>> component.getGlobalSiteManager().registerUtility( ... util, zope.locking.interfaces.ITokenUtility) >>> component.getGlobalSiteManager().registerAdapter(DAVActiveLock, ... (interface.Interface, z3c.dav.interfaces.IWebDAVRequest), ... IActiveLock) >>> component.getGlobalSiteManager().registerAdapter( ... TokenBroker, (interface.Interface,), ... zope.locking.interfaces.ITokenBroker) The `{DAV:}lockdiscovery` is now defined for the resource but its value is None because the resource isn't locked yet. >>> lockdiscovery = DAVLockdiscovery(resource, request) >>> lockdiscovery is not None True >>> lockdiscovery.lockdiscovery is None True >>> token = tokens.ExclusiveLock( ... resource, 'michael', datetime.timedelta(hours = 1)) >>> token = util.register(token) >>> tokenannot = token.annotations[WEBDAV_LOCK_KEY] = OOBTree() >>> tokenannot['depth'] = 'testdepth' >>> lockdiscoveryview = DAVLockdiscovery(resource, request) >>> lockdiscovery = lockdiscoveryview.lockdiscovery >>> len(lockdiscovery) 1 >>> IActiveLock.providedBy(lockdiscovery[0]) True >>> isinstance(lockdiscovery[0], DAVActiveLock) True Cleanup >>> component.getGlobalSiteManager().unregisterUtility( ... util, zope.locking.interfaces.ITokenUtility) True >>> component.getGlobalSiteManager().unregisterAdapter(DAVActiveLock, ... (interface.Interface, z3c.dav.interfaces.IWebDAVRequest), ... IActiveLock) True >>> component.getGlobalSiteManager().unregisterAdapter( ... TokenBroker, (interface.Interface,), ... zope.locking.interfaces.ITokenBroker) True """ utility = component.queryUtility(zope.locking.interfaces.ITokenUtility) if utility is None: return None return DAVLockdiscoveryAdapter(context, request, utility) class DAVLockdiscoveryAdapter(object): interface.implements(z3c.dav.coreproperties.IDAVLockdiscovery) component.adapts(interface.Interface, z3c.dav.interfaces.IWebDAVRequest) def __init__(self, context, request, utility): self.context = context self.request = request self.utility = utility @property def lockdiscovery(self): token = self.utility.get(self.context) if token is None: return None activelocks = [] for locktoken in token.annotations.get(WEBDAV_LOCK_KEY, {}).keys(): if locktoken != "principal_ids": activelocks.append(DAVActiveLock(locktoken, token, self.context, self.request)) if activelocks: return activelocks # Probable a non-webdav client / application created this lock. # We probable need an other active lock implementation to handle # this case. return [DAVActiveLock(None, token, self.context, self.request)]
z3c.davapp.zopelocking
/z3c.davapp.zopelocking-1.0b.tar.gz/z3c.davapp.zopelocking-1.0b/src/z3c/davapp/zopelocking/properties.py
properties.py
Changelog of z3c.dependencychecker ================================== 2.12 (2023-08-02) ----------------- - Fix, hopefully finally, the Zope user mapping use case. [gforcada] - Add `Plone` as an umbrella distribution, alongside `Zope`. [gforcada] - Scan the `<implements` directive on `ZCML` files. [gforcada] - Handle new distributions that no longer have a `setup.py`. Consider `pyproject.toml` and `setup.cfg` alongside `setup.py`. [gforcada] 2.11 (2023-03-03) ----------------- - Ignore `node_modules` and `__pycache__` folders when scanning for files with dependencies. [gforcada] - Do not scan Plone FTI files for behaviors with dotted names. [gforcada] 2.10 (2023-01-30) ----------------- - Do not ignore `Zope` user mappings, fixes previous release. [gforcada] 2.9 (2023-01-23) ---------------- - Ignore `Zope` package, as otherwise it swallows all `zope.` namespace packages. [gforcada] 2.8 (2022-11-30) ---------------- - Drop python 2.7 support. [gforcada] - Replace travis for GitHub actions. [gforcada] - Test against python 3.7-3.11 and pypy3. [gforcada] - Updated developer documentation. [reinout] 2.7 (2018-08-08) ---------------- - Fixed the 'requirement should be test requirement' report. There were corner cases when using user mappings. [gforcada] 2.6 (2018-07-09) ---------------- - Use the user mappings on the remaining reports: - unneeded dependencies - unneeded test dependencies - dependencies that should be test dependencies [gforcada] - Always consider imports in python docstrings to be test dependencies. [gforcada] 2.5.1 (2018-07-06) ------------------ - Re-release 2.5 as it was a brown bag release. [gforcada] 2.5 (2018-07-06) ---------------- - Check in every top level folder if the .egg-info folder is in them. [gforcada] 2.4.4 (2018-07-04) ------------------ Note: this includes the 2.4.1 - 2.4.4 releases, we had to iterate a bit to get the formatting right :-) - Fix rendering of long description in pypi. [gforcada, reinout] - Documentation formatting fixes. [reinout] 2.4 (2018-06-30) ---------------- - Handle packages that have multiple top levels, i.e. packages like Zope2. [gforcada] 2.3 (2018-06-21) ---------------- - Add a new command line option ``--exit-zero``. It forces the program to always exit with a zero status code. Otherwise it will report ``1`` if the program does find anything to report. [gforcada] - Fix ZCML parser to discard empty strings. [gforcada] 2.2 (2018-06-19) ---------------- - Ignore relative imports (i.e. from . import foo). [gforcada] - Added ``ignore-packages`` config option to totally ignore one or more packages in the reports (whether unused imports or unneeded dependencies). Handy for soft dependencies. [gforcada] 2.1.1 (2018-03-10) ------------------ - Note: 2.1 had a technical release problem, hence 2.1.1. [reinout] - We're releasing it as a wheel, too, now. [reinout] - Small improvements to the debug logging (``-v/--verbose`` shows it). [reinout] - Remove unused parameter in DottedName. [gforcada] - All imports found by DocFiles imports extractor are marked as test ones. [gforcada] - Handle multiple dotted names found in a single ZCML parameter. [gforcada] - Use properties to make code more pythonic. [gforcada] - Allow users to define their own mappings on a `pyproject.toml` file. See README.rst. - Filter imports when adding them to the database, rather than on each report. [gforcada] 2.0 (2018-01-04) ---------------- - Complete rewrite: code does no longer use deprecated functionality, is more modular, more pythonic, easier to extend and hack, and above all, has a 100% test coverage to ensure that it works as expected. [gforcada] - Add support for Python 3. [gforcada] 1.16 (2017-06-21) ----------------- - Don't crash anymore on, for instance, django code that needs a django settings file to be available or that needs the django app config step to be finished. [reinout] - Improved Django settings extraction. [reinout] - Better detection of python built-in modules. ``logging/__init__.py`` style modules were previously missed. [reinout] 1.15 (2015-09-02) ----------------- - The name of a wrong package was sometimes found in case of a directory with multiple egg-info directories (like ``/usr/lib/python2.7/dist-packages/*.egg-info/``...). Now the ``top_level.txt`` file in the egg-info directories is checked if the top-level directory matches. [reinout] 1.14 (2015-09-01) ----------------- - The debug logging (``-v``) is now printed to stdout instead of stderr. This makes it easier to grep or search in the verbose output for debugging purposes. [reinout] 1.13 (2015-08-29) ----------------- - Import + semicolon + statement (like ``import transaction;transaction.commit()``) is now also detected correctly. [gforcada] - The starting directory for packages with a dotted name (like ``zest.releaser``) is now also found automatically. [reinout] - Internal code change: moved the code out of the ``src/`` directory. Everything moved one level up. [reinout] - Dependencychecker doesn't descend anymore into directories without an ``__init__.py``. This helps with website projects that sometimes have python files buried deep in directories that aren't actually part of the project's python code. [reinout] - Multiple imports from similarly-named libraries on separate lines are now handled correctly. An import of ``zope.interface`` on one line could sometimes "hide" a ``zope.component`` import one line down. [gforcada] 1.12 (2015-08-16) ----------------- - Improve ZCML imports coverage (look on ``for`` and ``class`` as well). [gforcada] - Internal project updates (buildout version, test adjustments, etc). [gforcada] - Add support for FTI dependencies (behaviors, schema and class). [gforcada] 1.11 (2013-04-16) ----------------- - Support python installations without global setuptools installed by searching the name in the setup.py as fallback. 1.10 (2013-02-24) ----------------- - Treat non-test extras_require like normal install_requires. 1.9 (2013-02-13) ---------------- - Improved detection for "Django-style" package names with a dash in them. Django doesn't deal well with namespace packages, so instead of ``zc.something``, you'll see packages like ``zc-something``. The import then uses an underscore, ``zc_something``. - Added support for Django settings files. Anything that matches ``*settings.py`` is searched for Django settings like ``INSTALLED_APPS = [...]`` or ``MIDDLEWARE_CLASSES = (...)``. 1.8 (2013-02-13) ---------------- - Detect ZCML "provides", as used for generic setup profile registration. 1.7.1 (2012-11-26) ------------------ - Added travis.ci configuration. We're tested there, too, now! 1.7 (2012-11-26) ---------------- - Lookup package name for ZCML modules too, as it is done for python modules. - Detect generic setup dependencies in ``metadata.xml`` files. 1.6 (2012-11-01) ---------------- - Fix AttributeError when "magic modules" like email.Header are imported. 1.5 (2012-07-03) ---------------- - Add support for zipped dists when looking up pkg name. 1.4 (2012-07-03) ---------------- - Lookup pkg name from egg-infos if possible (python >= 2.5). This helps for instance with the PIL problem (which can be ``Imaging`` instead when you import it). 1.3.2 (2012-06-29) ------------------ - Fixed broken 1.3.0 and 1.3.0 release: the ``MANIFEST.in`` was missing... 1.3.1 (2012-06-29) ------------------ - Documentation updates because we moved to github: https://github.com/reinout/z3c.dependencychecker . 1.3 (2012-06-29) ---------------- - Added fix for standard library detection on OSX when using the python buildout. (Patch by Jonas Baumann, as is the next item). - Supporting ``[tests]`` in addition to ``[test]`` for test requirements. 1.2 (2011-09-19) ---------------- - Looking for a package directory named after the package name in preference to the src/ directory. - Compensating for django-style 'django-something' package names with 'django_something' package directories. Dash versus underscore. 1.1 (2010-01-06) ---------------- - Zcml files are also searched for 'component=' patterns as that can be used by securitypolicy declarations. - Dependencychecker is now case insensitive as pypi is too. - Using optparse for parsing commandline now. Added --help and --version. 1.0 (2009-12-10) ---------------- - Documentation update. - Improved test coverage. The dependencychecker module self is at 100%, the original import checker module is at 91% coverage. 0.5 (2009-12-10) ---------------- - Searching in doctests (.py, .txt, .rst) for imports, too. Regex-based by necessity, but it seems to catch what I can test it with. 0.4 (2009-12-10) ---------------- - Supporting "from zope import interface"-style imports where you really want to be told you're missing an "zope.interface" dependency instead of just "zope" (which is just a namespace package). 0.3 (2009-12-08) ---------------- - Sorted "unneeded requirements" reports and filtered out duplicates. - Reporting separately on dependencies that should be moved from the regular to the test dependencies. 0.2 (2009-12-08) ---------------- - Added tests. Initial quick test puts coverage at 86%. - Fixed bug in test requirement detection. - Added documentation. - Moved source code to zope's svn repository. 0.1 (2009-12-02) ---------------- - Also reporting on unneeded imports. - Added note on re-running buildout after a setup.py change. - Added zcml lookup to detect even more missing imports. - Added reporting on missing regular and test imports. - Grabbing existing requirements from egginfo directory. - Copied over Martijn Faassen's zope importchecker script.
z3c.dependencychecker
/z3c.dependencychecker-2.12.tar.gz/z3c.dependencychecker-2.12/CHANGES.rst
CHANGES.rst
z3c.dependencychecker ===================== Checks which imports are done and compares them to what's in ``setup.py`` and warn when discovering missing or unneeded dependencies. .. image:: https://github.com/reinout/z3c.dependencychecker/actions/workflows/testing.yml/badge.svg?branch=master :target: https://github.com/reinout/z3c.dependencychecker/actions/workflows/testing.yml .. image:: https://coveralls.io/repos/github/reinout/z3c.dependencychecker/badge.svg?branch=master :target: https://coveralls.io/github/reinout/z3c.dependencychecker?branch=master .. contents:: What it does ------------ z3c.dependencychecker reports on: - **Missing (test) requirements**: imports without a corresponding requirement in the ``setup.py``. There might be false alarms, but at least you've got a (hopefully short) list of items to check. Watch out for packages that have a different name than how they're imported. For instance a requirement on ``pydns`` which is used as ``import DNS`` in your code: pydns and DNS lead to separate "missing requirements: DNS" and "unneeded requirements: pydns" warnings. - **Unneeded (test) requirements**: requirements in your setup.py that aren't imported anywhere in your code. You *might* need them because not everything needs to be imported. It at least gives you a much smaller list to check by hand. - **Requirements that should be test-only**: if something is only imported in a test file, it shouldn't be in the generic defaults. So you get a separate list of requirements that should be moved from the regular to the test requirements. It checks the following locations: - Python files for regular imports and their docstrings. - ZCML files, Plone's generic setup files as well as FTI XML files. - Python files, ``.txt`` and ``.rst`` files for imports in doctests. - django settings files. User mappings ------------- Some packages available on pypi have a different name than the import statement needed to use them, i.e. `python-dateutil` is imported as `import dateutil`. Others provide more than one package, i.e `Zope2` provides several packages like `Products.Five` or `Products.OFSP`. For those cases, z3c.dependencychecker has a solution: user mappings. Add a `pyproject.toml` file on the root of your project with the following content:: [tool.dependencychecker] python-dateutil = ['dateutil'] Zope2 = ['Products.Five', 'Products.OFSP' ] z3c.dependencychecker will read this information and use it on its reports. Ignore packages --------------- Sometimes you need to add a package in `setup.py` although you are not importing it directly, but maybe is an extra dependency of one of your dependencies, or your package has a soft dependency on a package, and as a soft dependency it is not mandatory to install it always. `z3c.dependencychecker` would complain in both cases. It would report that a dependency is not needed, or that a missing package is not listed on the package requirements. Fortunately, `z3c.dependencychecker` also has a solution for it. Add a `pyproject.toml` file on the root of your project with the following content:: [tool.dependencychecker] ignore-packages = ['one-package', 'another.package' ] `z3c.dependencychecker` will totally ignore those packages in its reports, whether they're requirements that appear to be unused, or requirements that appear to be missing. Credits ------- z3c.dependencychecker is a different application/packaging of zope's importchecker utility. It has been used in quite some projects, I grabbed a copy from `lovely.recipe's checkout <http://bazaar.launchpad.net/~vcs-imports/lovely.recipe/trunk/annotate/head%3A/src/lovely/recipe/importchecker/importchecker.py>`_. - Martijn Faassen wrote the original importchecker script. - `Reinout van Rees <http://reinout.vanrees.org>`_ added the dependency checker functionality and packaged it (mostly while working at `The Health Agency <http://www.thehealthagency.com>`_). - Quite some fixes from `Jonas Baumann <https://github.com/jone>`_. - Many updates (basically: rewriting the entire codebase to work with AST!) to work well with modern Plone versions by `Gil Forcada Codinachs <http://gil.badall.net/>`. Source code, forking and reporting bugs --------------------------------------- The source code can be found on github: https://github.com/reinout/z3c.dependencychecker You can fork and fix it from there. And you can add issues and feature requests in the github issue tracker. Every time you commit something, ``bin/code-analysis`` is automatically run. Pay attention to the output and fix the problems that are reported. Or fix the setup so that inappropriate reports are filtered out. Local development setup ----------------------- Create a virtualenv and install the requirements:: $ python3 -m venv . $ bin/pip install -r requirements.txt If you changed the actual requirements in ``setup.py`` or the development requirements in ``requirements.in``, re-generate ``requirements.txt``:: $ bin/pip-compile requirements.in To run the tests (there's some pytest configuration in ``setup.cfg``):: $ bin/pytest Some checks that are run by github actions:: $ bin/black $ bin/codespell setup.py z3c/ $ bin/flake8 setup.py z3c/
z3c.dependencychecker
/z3c.dependencychecker-2.12.tar.gz/z3c.dependencychecker-2.12/README.rst
README.rst
BSD 3-Clause License Copyright (c) 2018, Reinout van Rees All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
z3c.dependencychecker
/z3c.dependencychecker-2.12.tar.gz/z3c.dependencychecker-2.12/LICENSE.rst
LICENSE.rst
import hashlib from functools import total_ordering from cached_property import cached_property # An umbrella distribution is a Pypi distribution, like `Zope`, # of which the importable packages that it provides have different namespaces # than the umbrella distribution name. # Zope provides Products.OFSP, App, Shared, Testing and other namespaces, # but does not provide a Zope namespace. # # They should never match a dotted name when compared. UMBRELLA_DISTRIBUTIONS = {"zope", "plone"} @total_ordering class DottedName: def __init__( self, name, file_path=None, is_test=False, ): self.name = name self.safe_name = name.lower().replace("-", "_") self.file_path = file_path self.is_test = is_test @classmethod def from_requirement(cls, requirement, file_path=None): """A requirement in this method's context is a pkg_resources.Requirement """ return cls( requirement.project_name, file_path=file_path, ) @cached_property def namespaces(self): return self.safe_name.split(".") @cached_property def is_namespaced(self): return bool(len(self.namespaces) - 1) def __lt__(self, other): if not isinstance(other, DottedName): return NotImplemented return self.name < other.name def __eq__(self, other): if not isinstance(other, DottedName): return NotImplemented return self.safe_name == other.safe_name def __repr__(self): return f"<DottedName {self.name}>" def __hash__(self): digest = hashlib.sha256(self.safe_name.encode()).hexdigest() return int(digest, 16) % 10**8 def __contains__(self, item): """Check if self is in item or the other way around As we can never know which one is actually the requirement/pypi name and which one the import, check if one fits inside the other. So ``x in s`` and ``s in x`` should return the same in this implementation. """ if not isinstance(item, DottedName): return False if ( self.safe_name in UMBRELLA_DISTRIBUTIONS or item.safe_name in UMBRELLA_DISTRIBUTIONS ): return False if self.safe_name == item.safe_name: return True # note that zip makes two different sized iterables have the same size # i.e. [1,2,3] and [4,5,6,7,8] will only loop through [1,4] [2,5] # and [3,6]. The other elements (7 and 8) will be totally ignored. # That's a nice trick to ensure that all the namespace is shared. for part1, part2 in zip(self.namespaces, item.namespaces): if part1 != part2: return False return True
z3c.dependencychecker
/z3c.dependencychecker-2.12.tar.gz/z3c.dependencychecker-2.12/z3c/dependencychecker/dotted_name.py
dotted_name.py
import ast import fnmatch import logging import os import re from xml.etree import ElementTree from z3c.dependencychecker.dotted_name import DottedName TEST_REGEX = r""" {0} # Needs to start with the path separator \w* # There could be some characters (or none) test # has to contain test on it s? # ensure plurals are handled as well ( # Needs to end with either a path or a file extension: {0} # path separator | # OR \w* # some possible characters \. # a dot \w+ # extension ) """.format( os.sep ) TEST_IN_PATH_REGEX = re.compile(TEST_REGEX, re.VERBOSE) logger = logging.getLogger(__name__) FOLDERS_TO_IGNORE = ("node_modules", "__pycache__") class BaseModule: def __init__(self, package_path, full_path): self.path = full_path self._relative_path = self._get_relative_path(package_path, full_path) self.testing = self._is_test_module() @staticmethod def _get_relative_path(package_path, full_path): return full_path[len(package_path) :] def _is_test_module(self): return bool(re.search(TEST_IN_PATH_REGEX, self._relative_path)) @classmethod def create_from_files(cls, top_dir): raise NotImplementedError def scan(self): raise NotImplementedError class PythonModule(BaseModule): @classmethod def create_from_files(cls, top_dir): """Find all python files in the package For that it gets the path to where top_level.txt points to, which is not always a folder: - folder example: z3c.dependencychecker itself - file example: flake8-isort or any other single file distribution Return this very same class, which would allow to call the scan() method to get an iterator over all this file's imports. """ if top_dir.endswith(".py"): yield cls(top_dir, top_dir) return for path, folders, filenames in os.walk(top_dir): if "__init__.py" not in filenames: # Don't descend further into the tree. # Clear folders variable in-place. folders[:] = [] continue for filename in filenames: if filename.endswith(".py"): yield cls( top_dir, os.path.join(path, filename), ) def scan(self): for node in ast.walk(self._get_tree()): yield from self._process_ast_node(node) def _get_tree(self): with open(self.path) as module_file: source_text = module_file.read() tree = ast.parse(source_text) return tree def _process_ast_node(self, node): if isinstance(node, ast.Import): for name in node.names: dotted_name = name.name yield DottedName( dotted_name, file_path=self.path, is_test=self.testing, ) elif isinstance(node, ast.ImportFrom): if self._is_relative_import(node): return for name in node.names: if name.name == "*": dotted_name = node.module else: dotted_name = f"{node.module}.{name.name}" yield DottedName( dotted_name, file_path=self.path, is_test=self.testing, ) @staticmethod def _is_relative_import(import_node): return import_node.level > 0 class ZCMLFile(BaseModule): """Extract imports from .zcml files These files are in common use in Zope/Plone based projects to define its components and more. """ ELEMENTS = { "include": ("package",), "adapter": ("for", "factory", "provides"), "utility": ("provides", "component"), "browser:page": ("class", "for", "layer"), "subscriber": ("handler", "for"), "securityPolicy": ("component",), "genericsetup:registerProfile": ("provides",), "implements": ("interface",), } @classmethod def create_from_files(cls, top_dir): """Find all ZCML files in the package Return this very same class, which would allow to call the scan() method to get an iterator over all this file's imports. """ if top_dir.endswith(".py"): return for path, folders, filenames in os.walk(top_dir): folders[:] = [d for d in folders if d not in FOLDERS_TO_IGNORE] for filename in filenames: if filename.endswith(".zcml"): yield cls( top_dir, os.path.join(path, filename), ) def scan(self): tree = ElementTree.parse(self.path).getroot() for element in self.ELEMENTS: element_namespaced = self._build_namespaced_element(element) for node in tree.iter(element_namespaced): for attrib in self.ELEMENTS[element]: yield from self._extract_dotted_name(node, attrib) def _extract_dotted_name(self, node, attr): if attr in node.keys(): candidate_text = node.get(attr) for dotted_name in candidate_text.split(" "): if not dotted_name or dotted_name.startswith("."): continue if dotted_name == "*": continue yield DottedName( dotted_name, file_path=self.path, is_test=self.testing, ) @staticmethod def _build_namespaced_element(element): if ":" in element: namespace, name = element.split(":") return "{{http://namespaces.zope.org/{0}}}{1}".format( namespace, name, ) return f"{{http://namespaces.zope.org/zope}}{element}" class FTIFile(BaseModule): """Extract imports from Factory Type Information files These are xml files, usually located inside a types folder and used by Zope/Plone based projects to define its content types. """ TYPES_FOLDER = f"{os.sep}types" @classmethod def create_from_files(cls, top_dir): """Find all FTI files, which are xml, in the package Return this very same class, which would allow to call the scan() method to get an iterator over all this file's imports. """ if top_dir.endswith(".py"): return for path, folders, filenames in os.walk(top_dir): folders[:] = [d for d in folders if d not in FOLDERS_TO_IGNORE] for filename in filenames: if filename.endswith(".xml") and cls.TYPES_FOLDER in path: yield cls( top_dir, os.path.join(path, filename), ) def scan(self): tree = ElementTree.parse(self.path).getroot() for node in tree.iter("property"): if "name" in node.keys(): name = node.get("name") if name in ("klass", "schema"): if node.text: yield DottedName( node.text.strip(), file_path=self.path, is_test=self.testing, ) class GSMetadata(BaseModule): """Extract imports from Generic Setup metadata.xml files These files are in common use in Zope/Plone to define Generic Setup profile dependencies between projects. """ PROFILE_RE = re.compile(r"profile-(?P<dotted_name>[\w.]+):[\w\W]+") @classmethod def create_from_files(cls, top_dir): """Find all metadata.xml files in the package Return this very same class, which would allow to call the scan() method to get an iterator over all this file's imports. """ if top_dir.endswith(".py"): return for path, folders, filenames in os.walk(top_dir): folders[:] = [d for d in folders if d not in FOLDERS_TO_IGNORE] for filename in filenames: if filename == "metadata.xml": yield cls( top_dir, os.path.join(path, filename), ) def scan(self): tree = ElementTree.parse(self.path).getroot() for node in tree.iter("dependency"): if not node.text: continue result = self.PROFILE_RE.search(node.text.strip()) if result: yield DottedName( result.group("dotted_name"), file_path=self.path, is_test=self.testing, ) class PythonDocstrings(PythonModule): """Extract imports from docstrings found inside python modules There are some projects that rather than having separate files to keep the tests, they add the inline with the code as docstrings, either at class or method/function level. """ NODES_WITH_DOCSTRINGS = ( ast.Module, ast.ClassDef, ast.FunctionDef, ) def scan(self): for node in ast.walk(self._get_tree()): if isinstance(node, self.NODES_WITH_DOCSTRINGS): docstring = ast.get_docstring(node) yield from self._parse_docstring(docstring) def _parse_docstring(self, docstring): if not docstring: return for line in docstring.split("\n"): code = self._extract_code(line) if code: try: tree = ast.parse(code) except SyntaxError: logger.debug( 'Could not parse "%s" in %s', line, self.path, ) continue for node in ast.walk(tree): for dotted_name in self._process_ast_node(node): dotted_name.is_test = True yield dotted_name @staticmethod def _extract_code(line): if ">>>" in line: position = line.find(">>>") + 3 return line[position:].strip() class DocFiles(PythonDocstrings): """Extract imports from documentation-like documents One extended testing pattern (at least in Zope/Plone based projects) is to write documentation in txt/rst files that contain tests to assert that documentation. """ @classmethod def create_from_files(cls, top_dir): """Find all documentation files in the package For that it gets the path to where top_level.txt points to, which is not always a folder: - folder example: z3c.dependencychecker itself - file example: flake8-isort or any other single file distribution Return this very same class, which would allow to call the scan() method to get an iterator over all this file's imports. """ if top_dir.endswith(".py"): return for path, folders, filenames in os.walk(top_dir): folders[:] = [d for d in folders if d not in FOLDERS_TO_IGNORE] for filename in filenames: if filename.endswith(".txt") or filename.endswith(".rst"): yield cls( top_dir, os.path.join(path, filename), ) def scan(self): with open(self.path) as doc_file: for line in doc_file: code = self._extract_code(line) if code: try: tree = ast.parse(code) except SyntaxError: logger.debug( 'Could not parse "%s" in %s', line, self.path, ) continue for node in ast.walk(tree): for dotted_name in self._process_ast_node(node): dotted_name.is_test = True yield dotted_name class DjangoSettings(PythonModule): """Extract imports from Django settings.py These files are used to enable Django components. """ @classmethod def create_from_files(cls, top_dir): """Find all settings.py files in the package For that it gets the path to where top_level.txt points to, which is not always a folder: - folder example: z3c.dependencychecker itself - file example: flake8-isort or any other single file distribution Return this very same class, which would allow to call the scan() method to get an iterator over all this file's imports. """ if top_dir.endswith(".py"): return for path, folders, filenames in os.walk(top_dir): folders[:] = [d for d in folders if d not in FOLDERS_TO_IGNORE] for filename in filenames: if fnmatch.fnmatch(filename, "*settings.py"): yield cls( top_dir, os.path.join(path, filename), ) def scan(self): for node in ast.walk(self._get_tree()): if isinstance(node, ast.Assign): if self._is_installed_apps_assignment(node): if isinstance(node.value, (ast.Tuple, ast.List)): for element in node.value.elts: if isinstance(element, ast.Str): yield DottedName( element.s, file_path=self.path, is_test=self.testing, ) if self._is_test_runner_assignment(node): if isinstance(node.value, ast.Str): yield DottedName( node.value.s, file_path=self.path, is_test=True, ) @staticmethod def _is_installed_apps_assignment(node): if ( len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) and node.targets[0].id == "INSTALLED_APPS" ): return True return False @staticmethod def _is_test_runner_assignment(node): if ( len(node.targets) == 1 and isinstance(node.targets[0], ast.Name) and node.targets[0].id == "TEST_RUNNER" ): return True return False MODULES = ( PythonModule, ZCMLFile, FTIFile, GSMetadata, PythonDocstrings, DocFiles, DjangoSettings, )
z3c.dependencychecker
/z3c.dependencychecker-2.12.tar.gz/z3c.dependencychecker-2.12/z3c/dependencychecker/modules.py
modules.py
import glob import logging import os import sys import pkg_resources import toml from cached_property import cached_property from z3c.dependencychecker.db import ImportsDatabase from z3c.dependencychecker.dotted_name import DottedName from z3c.dependencychecker.modules import MODULES from z3c.dependencychecker.utils import change_dir METADATA_FILES = ( "setup.py", "setup.cfg", "pyproject.toml", ) logger = logging.getLogger(__name__) class PackageMetadata: """Information related to a python source distribution It relies heavily on setuptools and pkg_resources APIs. """ def __init__(self, path): logger.debug("Reading package metadata for %s...", path) self._path = path self._working_set = self._generate_working_set_with_ourselves() @cached_property def distribution_root(self): for metadata_file in METADATA_FILES: if metadata_file in os.listdir(self._path): break else: logger.error( "No pyproject.toml/setup.py/.cfg was found in %s. " "Without it dependencychecker can not work.", self._path, ) sys.exit(1) return self._path @cached_property def metadata_file_path(self): for metadata_file in METADATA_FILES: if metadata_file in os.listdir(self._path): return os.path.join( self.distribution_root, metadata_file, ) @cached_property def package_dir(self): """Check where the .egg-info is located""" try_paths = [self.distribution_root] top_level_elements = [ os.path.join(self.distribution_root, folder) for folder in os.listdir(self.distribution_root) ] try_paths += [folder for folder in top_level_elements if os.path.isdir(folder)] for path in try_paths: folder_found = self._find_egg_info_in_folder(path) if folder_found: logger.debug( ".egg-info folder found at %s folder", path, ) return path logger.error(".egg-info folder could not be found") sys.exit(1) @staticmethod def _find_egg_info_in_folder(path): with change_dir(path): results = glob.glob("*.egg-info") return results @cached_property def egg_info_dir(self): results = self._find_egg_info_in_folder(self.package_dir) return os.path.join( self.package_dir, results[0], ) @cached_property def name(self): path, filename = os.path.split(self.egg_info_dir) name = filename[: -len(".egg-info")] logger.debug( "Package name is %s", name, ) return name def _generate_working_set_with_ourselves(self): """Use pkg_resources API to enable the package being analyzed This, enabling the package in pkg_resources, allows to extract information from .egg-info folders, for example, its requirements. """ working_set = pkg_resources.WorkingSet() working_set.add_entry(self.package_dir) return working_set def _get_ourselves_from_working_set(self): """Use pkg_resources API to get a Requirement (in pkg_resources parlance) of the package being analyzed """ ourselves = pkg_resources.Requirement.parse(self.name) try: package = self._working_set.find(ourselves) return package except ValueError: logger.error( "Package %s could not be found.\n" "You might need to put it in development mode,\n" "i.e. python setup.py develop or python -m build", self.name, ) sys.exit(1) def get_required_dependencies(self): this_package = self._get_ourselves_from_working_set() requirements = this_package.requires() for requirement in requirements: yield DottedName.from_requirement( requirement, file_path=self.metadata_file_path, ) def get_extras_dependencies(self): """Get this packages' extras dependencies defined in its configuration""" this_package = self._get_ourselves_from_working_set() for extra_name in this_package.extras: extra_requirements = this_package.requires(extras=(extra_name,)) dotted_names = ( DottedName.from_requirement(req, file_path=self.metadata_file_path) for req in extra_requirements if req.project_name != "Zope" ) yield extra_name, dotted_names @cached_property def top_level(self): path = os.path.join( self.egg_info_dir, "top_level.txt", ) if not os.path.exists(path): logger.error( "top_level.txt could not be found on %s.\n" "It is needed for dependencychecker to work properly.", self.egg_info_dir, ) sys.exit(1) with open(path) as top_level_file: content = top_level_file.read().strip() top_levels = [] for candidate in content.split("\n"): possible_top_level = os.path.join( self.package_dir, candidate, ) if os.path.exists(possible_top_level): logger.debug("Found top level %s", possible_top_level) top_levels.append(possible_top_level) continue single_module = f"{possible_top_level}.py" if os.path.exists(single_module): logger.debug("Found top level %s", single_module) top_levels.append(single_module) continue logger.warning( "Top level %s not found but referenced by top_level.txt", possible_top_level, ) if top_levels: return top_levels logger.error( "There are paths found in %s%stop_level.txt that do not exist.\n" "Maybe you need to put the package in development again?", self.egg_info_dir, os.sep, ) sys.exit(1) class Package: """The python package that is being analyzed This class itself does not much per se, but connects the PackageMetadata with the ImportsDatabase, where the important bits are. """ def __init__(self, path): self.metadata = PackageMetadata(path) self.imports = ImportsDatabase() self.imports.own_dotted_name = DottedName(self.metadata.name) def inspect(self): self.set_declared_dependencies() self.set_declared_extras_dependencies() self.set_user_mappings() self.analyze_package() def set_declared_dependencies(self): """Add this packages' dependencies defined in its configuration to the database""" self.imports.add_requirements(self.metadata.get_required_dependencies()) def set_declared_extras_dependencies(self): """Add this packages' extras dependencies defined in its configuration to the database """ for extra, dotted_names in self.metadata.get_extras_dependencies(): self.imports.add_extra_requirements(extra, dotted_names) def set_user_mappings(self): """Add any user defined mapping They need to be on a pyproject.toml file within the table tool.dependencychecker. See tests/test_user_mappings.py for examples. """ config = self._load_user_config() for package, packages_provided in config.items(): if package == "ignore-packages": if isinstance(packages_provided, list): self.imports.add_ignored_packages(packages_provided) else: logger.warning( "ignore-packages key in pyproject.toml needs to " "be a list, even for a single package to be ignored." ) elif isinstance(packages_provided, list): self.imports.add_user_mapping(package, packages_provided) def analyze_package(self): for top_folder in self.metadata.top_level: logger.debug("Analyzing package top_level %s...", top_folder) for module_obj in MODULES: logger.debug( "Starting analyzing files using %s...", module_obj, ) for source_file in module_obj.create_from_files(top_folder): logger.debug( "Searching dependencies (with %s) in file %s...", module_obj.__name__, source_file.path, ) self.imports.add_imports(source_file.scan()) def _load_user_config(self): config_file_path = os.sep.join( [self.metadata.distribution_root, "pyproject.toml"] ) try: config = toml.load(config_file_path) return config["tool"]["dependencychecker"] except (OSError, KeyError): return {}
z3c.dependencychecker
/z3c.dependencychecker-2.12.tar.gz/z3c.dependencychecker-2.12/z3c/dependencychecker/package.py
package.py
import logging import optparse import os import sys import pkg_resources from z3c.dependencychecker.package import Package from z3c.dependencychecker.report import Report logger = logging.getLogger(__name__) def main(): options, args = parse_command_line() set_log_level(options.verbose) path = get_path(args) package_analyzed = Package(path) package_analyzed.inspect() report = Report(package_analyzed) report.print_report() if options.exit_status: exit(report.exit_status) exit(0) def parse_command_line(): usage = 'Usage: %prog [path]\n(path defaults to package name, fallback is "src/")' parser = optparse.OptionParser(usage=usage, version=_version()) parser.add_option( "-v", "--verbose", action="store_true", dest="verbose", default=False, help="Show debug output", ) parser.add_option( "--exit-zero", action="store_false", dest="exit_status", default=True, help='Exit with status code "0" even if there are errors.', ) options, args = parser.parse_args() return options, args def _version(): ourselves = pkg_resources.require("z3c.dependencychecker")[0] return ourselves.version def set_log_level(verbose): level = logging.INFO if verbose: level = logging.DEBUG logging.basicConfig( level=level, stream=sys.stdout, format="%(levelname)s: %(message)s" ) def get_path(args): """Get path to the python source distribution that will be checked for dependencies If no path is given on the command line arguments, the current working directory is used instead. """ path = os.getcwd() if len(args) < 1: logger.debug("path used: %s", path) return path path = os.path.abspath(args[0]) if os.path.isdir(path): logger.debug("path used: %s", path) return path logger.error("Given path is not a folder: %s", args[0]) sys.exit(1)
z3c.dependencychecker
/z3c.dependencychecker-2.12.tar.gz/z3c.dependencychecker-2.12/z3c/dependencychecker/main.py
main.py
import logging logger = logging.getLogger(__name__) class Report: def __init__(self, package): self._database = package.imports self.exit_status = 0 def print_report(self): logger.debug("Package requirements: %s", self._database._requirements) logger.debug("Package extras: %s", self._database._extras_requirements) logger.debug( "User defined mappings: %s", self._database.user_mappings, ) self.missing_requirements() self.missing_test_requirements() self.unneeded_requirements() self.requirements_that_should_be_test_requirements() self.unneeded_test_requirements() self.print_notice() def missing_requirements(self): self._print_metric( "Missing requirements", self._database.get_missing_imports, ) def missing_test_requirements(self): self._print_metric( "Missing test requirements", self._database.get_missing_test_imports, ) def unneeded_requirements(self): self._print_metric( "Unneeded requirements", self._database.get_unneeded_requirements, ) def requirements_that_should_be_test_requirements(self): self._print_metric( "Requirements that should be test requirements", self._database.requirements_that_should_be_test_requirements, ) def unneeded_test_requirements(self): self._print_metric( "Unneeded test requirements", self._database.get_unneeded_test_requirements, ) @staticmethod def print_notice(): print("") print("Note: requirements are taken from the egginfo dir, so you need") print("to re-generate it, via `python -m build`, setuptools, zc.buildout") print("or any other means.") print("") def _print_metric(self, title, method): missed = method() if len(missed) == 0: return self.exit_status = 1 self._print_header(title) for dotted_name in missed: print(f" {dotted_name.name}") @staticmethod def _print_header(message): if message: print("") print(message) print("=" * len(message))
z3c.dependencychecker
/z3c.dependencychecker-2.12.tar.gz/z3c.dependencychecker-2.12/z3c/dependencychecker/report.py
report.py
import logging import sys from z3c.dependencychecker.dotted_name import DottedName logger = logging.getLogger(__name__) # starting from python 3.10 the list of builtin methods are available directly PY_10_OR_HIGHER = sys.version_info[1] >= 10 class ImportsDatabase: """Store all imports and requirements of a package Use that information to extract useful data out of it, like requirements unused, etc. """ def __init__(self): self._requirements = set() self._extras_requirements = {} self.imports_used = [] self.user_mappings = {} self.reverse_user_mappings = {} self.ignored_packages = set() self.own_dotted_name = None def add_requirements(self, requirements): self._requirements = set(requirements) def add_extra_requirements(self, extra_name, dotted_names): # A bit of extra work needs to be done as pkg_resources API returns # all common requirements as well as the extras when asking for an # extra requirements. only_extra_dotted_names = self._filter_duplicates(dotted_names) if extra_name in self._extras_requirements.keys(): self._extras_requirements[extra_name].update( only_extra_dotted_names, ) logger.warning( 'extra requirement "%s" is declared twice', extra_name, ) else: self._extras_requirements[extra_name] = only_extra_dotted_names def _filter_duplicates(self, imports): """Return all items in imports that are not a requirement already""" all_imports = set(imports) filtered = all_imports - self._requirements return filtered def add_imports(self, imports): filters = ( self._filter_out_known_packages, self._filter_out_own_package, self._filter_out_python_standard_library, ) for single_import in imports: unknown_import = self._apply_filters([single_import], filters) if unknown_import: logger.debug(" Import found: %s", single_import.name) self.imports_used.append(single_import) else: logger.debug(" Import found & ignored: %s", single_import.name) def add_user_mapping(self, package_name, provided_names): package = DottedName(package_name) packages_provided = [DottedName(name) for name in provided_names] if package not in self._all_requirements(): logger.info( "Ignoring user mapping %s as is not a dependency of the " "package being analyzed", package, ) return logger.debug("Using user mapping %s", package) self.user_mappings[package] = set(packages_provided) for single_package in packages_provided: self.reverse_user_mappings[single_package] = package def add_ignored_packages(self, packages): self.ignored_packages = {DottedName(package) for package in packages} def _all_requirements(self): all_requirements = self._requirements.copy() for extra in self._extras_requirements: all_requirements.update(self._extras_requirements[extra]) return all_requirements def get_missing_imports(self): filters = ( self._filter_out_testing_imports, self._filter_out_requirements, self._filter_out_ignored_imports, ) missing = self._apply_filters(self.imports_used, filters) unique_imports = self._get_unique_imports(imports_list=missing) result = self._filter_user_mappings(unique_imports) return result def get_missing_test_imports(self): filters = ( self._filter_out_only_testing_imports, self._filter_out_requirements, self._filter_out_test_requirements, self._filter_out_ignored_imports, ) missing = self._apply_filters(self.imports_used, filters) unique_imports = self._get_unique_imports(imports_list=missing) result = self._filter_user_mappings(unique_imports) return result def get_unneeded_requirements(self): all_but_test_requirements = self._requirements.copy() for extra in self._extras_requirements: all_but_test_requirements.update(self._extras_requirements[extra]) test_requirements = self._get_test_extra() for dotted_name in test_requirements: all_but_test_requirements.remove(dotted_name) filters = ( self._filter_out_known_packages, self._filter_out_python_standard_library, self._filter_out_used_imports, self._filter_out_ignored_imports, self._filter_out_mappings, ) unneeded = self._apply_filters(all_but_test_requirements, filters) unique_imports = self._get_unique_imports(imports_list=unneeded) return unique_imports def requirements_that_should_be_test_requirements(self): non_testing_filters = (self._filter_out_testing_imports,) non_testing_imports = self._apply_filters( self.imports_used, non_testing_filters, ) complete_non_testing_imports = [] for non_test_import in non_testing_imports: if non_test_import in self.reverse_user_mappings: meta_package = self.reverse_user_mappings[non_test_import] complete_non_testing_imports.append(meta_package) continue complete_non_testing_imports.append(non_test_import) requirements_not_used = [ requirement for requirement in self._requirements if self._discard_if_found_obj_in_list( requirement, complete_non_testing_imports, ) ] testing_filters = ( self._filter_out_only_testing_imports, self._filter_out_own_package, ) testing_imports = self._apply_filters( self.imports_used, testing_filters, ) complete_test_imports = [] for test_import in testing_imports: if test_import in self.reverse_user_mappings: meta_package = self.reverse_user_mappings[test_import] complete_test_imports.append(meta_package) continue complete_test_imports.append(test_import) should_be_test_requirements = [ requirement for requirement in requirements_not_used if not self._discard_if_found_obj_in_list( requirement, complete_test_imports, ) ] filters = (self._filter_out_ignored_imports,) skip_ignored = self._apply_filters( should_be_test_requirements, filters, ) unique = self._get_unique_imports(imports_list=skip_ignored) return unique def get_unneeded_test_requirements(self): test_requirements = self._get_test_extra() if not test_requirements: return [] filters = ( self._filter_out_known_packages, self._filter_out_python_standard_library, self._filter_out_used_imports, self._filter_out_ignored_imports, self._filter_out_mappings_on_test, ) unneeded = self._apply_filters(test_requirements, filters) unique_imports = self._get_unique_imports(imports_list=unneeded) return unique_imports @staticmethod def _apply_filters(objects, filters): """Filter a list of given objects through a list of given filters This helps encapsulating the filtering logic here while keeping the methods free from this clutter. Callees of this method need to provide a list of objects (usually a list of DottedNames) that will be processed by the provided list of filters. A filter, in this context, is a function that takes a DottedName as a single argument and returns a boolean value. If a given DottedName returns True in all filters, it will make it to the final result an be returned back. """ result = [] for single_object in objects: for filter_func in filters: if not filter_func(single_object): break else: result.append(single_object) return result def _get_unique_imports(self, imports_list=None): if imports_list is None: imports_list = self.imports_used unique_dotted_names = list(set(imports_list)) sorted_unique_dotted_names = sorted(unique_dotted_names) return sorted_unique_dotted_names def _filter_out_used_imports(self, dotted_name): return self._discard_if_found_obj_in_list( dotted_name, self.imports_used, ) def _filter_out_mappings(self, meta_package): """Filter meta packages If it is not a meta package, let it continue the filtering. If it is a meta package, check if any of the packages it provides is used. If any of them it is, then filter it. """ if meta_package not in self.user_mappings.keys(): return True for dotted_name in self.user_mappings[meta_package]: if not self._discard_if_found_obj_in_list(dotted_name, self.imports_used): return False return True def _filter_out_mappings_on_test(self, meta_package): """Filter meta packages If it is not a meta package, let it continue the filtering. If it is a meta package, check if any of the packages it provides is used. If any of them it is, then filter it. """ if meta_package not in self.user_mappings.keys(): return True filters = (self._filter_out_only_testing_imports,) test_only_imports = self._apply_filters(self.imports_used, filters) for dotted_name in self.user_mappings[meta_package]: if not self._discard_if_found_obj_in_list(dotted_name, test_only_imports): return False return True def _filter_out_ignored_imports(self, dotted_name): return self._discard_if_found_obj_in_list( dotted_name, self.ignored_packages, ) def _filter_out_known_packages(self, dotted_name): to_ignore = ( DottedName("setuptools"), DottedName("pkg_resources"), DottedName("distribute"), ) return self._discard_if_found_obj_in_list(dotted_name, to_ignore) @staticmethod def _filter_out_testing_imports(dotted_name): return not dotted_name.is_test @staticmethod def _filter_out_only_testing_imports(dotted_name): return dotted_name.is_test def _filter_out_own_package(self, dotted_name): return dotted_name not in self.own_dotted_name def _filter_out_requirements(self, dotted_name): return self._discard_if_found_obj_in_list( dotted_name, self._requirements, ) def _filter_out_test_requirements(self, dotted_name): test_requirements = self._get_test_extra() if not test_requirements: return True return self._discard_if_found_obj_in_list( dotted_name, test_requirements, ) def _filter_out_python_standard_library(self, dotted_name): std_library = self._build_std_library() return self._discard_if_found_obj_in_list(dotted_name, std_library) @staticmethod def _discard_if_found_obj_in_list(obj, obj_list): """Check if obj is on obj_list and return the opposite We are interested in filtering out requirements, so if a given object is on a given list, that object can be discarded as it's already in the list. """ # this is a generator expression, nothing is computed until it is being # called some lines below iterable = (item for item in obj_list if obj in item) # `any` stops consuming the iterator as soon as an element of the # iterable is True if any(iterable): # if 'obj' is found, the pipeline needs to stop and discard the # requirement return False # 'obj' was not found on the list, means that is fulfilling the # pipeline filters so far return True @staticmethod def _build_std_library(): if PY_10_OR_HIGHER: # see https://github.com/jackmaney/python-stdlib-list/issues/55 libraries = list( set(list(sys.stdlib_module_names) + list(sys.builtin_module_names)) ) else: from stdlib_list import stdlib_list python_version = sys.version_info libraries = stdlib_list( "{}.{}".format( python_version[0], python_version[1], ) ) fake_std_libraries = [DottedName(x) for x in libraries] return fake_std_libraries def _get_test_extra(self): candidates = ("test", "tests") for candidate in candidates: if candidate in self._extras_requirements: return self._extras_requirements[candidate] return [] def _filter_user_mappings(self, dotted_names): """Remove dotted names that are in user mappings""" result = [] for single_import in dotted_names: for provided_package in self.reverse_user_mappings: if single_import in provided_package: logger.debug( "Skip %s as is part of user mapping %s", single_import, self.reverse_user_mappings[provided_package], ) break else: result.append(single_import) return result
z3c.dependencychecker
/z3c.dependencychecker-2.12.tar.gz/z3c.dependencychecker-2.12/z3c/dependencychecker/db.py
db.py
Usage of z3c.dependencychecker ============================== .. :doctest: Installation ------------ Either install z3c.dependencychecker globally (``easy_install z3c.dependencychecker``) or install it in your buildout. Usage ----- Run the ``dependencychecker`` or ``bin/dependencychecker`` script from your project's root folder and it will report on your dependencies. You must have installed your project, as z3c.dependencychecker needs the ``YOURPROJECT.egg-info`` directory that setuptools generates. It looks for that directory in the root folder and in the direct subdirectory (like ``src/`` or ``plone/``). We have a sample project in a temp directory:: >>> sample1_dir '/TESTTEMP/sample1' >>> ls(sample1_dir) setup.py src For our test, we call the main() method, just like the ``dependencychecker`` script would:: >>> import os >>> os.chdir(sample1_dir) >>> from z3c.dependencychecker import dependencychecker >>> dependencychecker.main() Unused imports ============== src/sample1/unusedimports.py:7: tempfile src/sample1/unusedimports.py:4: zest.releaser src/sample1/unusedimports.py:6: os <BLANKLINE> Missing requirements ==================== Products.GenericSetup.interfaces.EXTENSION missing.req other.generic.setup.dependency plone.app.content.interfaces.INameFromTitle plone.app.dexterity.behaviors.metadata.IBasic plone.random1.interfaces.IMySchema plone.random2.content.MyType some_django_app something.origname zope.exceptions zope.interface <BLANKLINE> Missing test requirements ========================= plone.dexterity.browser.views.ContentTypeView plone.dexterity.interfaces.IContentType reinout.hurray transaction zope.filerepresentation.interfaces.IRawReadFile <BLANKLINE> Unneeded requirements ===================== some.other.extension unneeded.req <BLANKLINE> Requirements that should be test requirements ============================================= Needed.By.Test <BLANKLINE> Unneeded test requirements ========================== zope.testing <BLANKLINE> Note: requirements are taken from the egginfo dir, so you need to re-run buildout (or setup.py or whatever) for changes in setup.py to have effect. <BLANKLINE>
z3c.dependencychecker
/z3c.dependencychecker-2.12.tar.gz/z3c.dependencychecker-2.12/z3c/dependencychecker/USAGE.rst
USAGE.rst
Overview -------- z3c.discriminator provides a formalism for marking adapter specifications as discriminators in the sense that they will be used only for adapter lookup, not instantiation. Using z3c.discriminator ----------------------- To mark one or more interfaces as discriminators in a ``provideAdapter`` call, simply wrap your interface with the ``discriminator`` method: >>> from z3c.discriminator import discriminator >>> provideAdapter(MyAdapter, (IFoo, discriminator(IBar))) To do the same in a Zope configuration file, prefix your dotted path with a dash like so: <adapter for="IFoo -IBar" factory="some.package.YourFactory" /> Note that any interface in the declaration can be made a discriminator; they need not come in any particular order. In your factory definition, simply require only the arguments that correspond to non-discriminator specifications, e.g. class GetsOnlyFoo(object): def __init__(self, foo): ... -or- def gets_only_bar(bar): ...
z3c.discriminator
/z3c.discriminator-0.2.tar.gz/z3c.discriminator-0.2/README.txt
README.txt
z3c.discriminator ================= This package provides a formalism for marking adapter specifications as discriminators in the sense that they will be used only for adapter lookup, not instantiation. First a set of interfaces and their implementations. >>> from zope import interface >>> class IFoo(interface.Interface): ... pass >>> class IBar(interface.Interface): ... pass >>> class Foo(object): ... interface.implements(IFoo) >>> class Bar(object): ... interface.implements(IBar) >>> foo = Foo() >>> bar = Bar() Let's say we want to register an adapter for IFoo that also discriminates on IBar. That is, the adapter itself takes only one argument (providing IFoo). >>> def give_me_foo(foo): ... return foo We can use the ``discriminator`` method the mark the interface as a discriminator. Let's look at its properties: >>> from z3c.discriminator import discriminator >>> discriminator(IFoo).providedBy(foo) True To register the adapter we use the standard ``provideAdapter`` method. >>> from zope import component >>> component.provideAdapter(give_me_foo, (IFoo, discriminator(IBar)), IFoo) Let's look up the adapter providing both ``foo`` and ``bar``: >>> from zope import component >>> component.getMultiAdapter((foo, bar), IFoo) <Foo object at ...> Adapter registration using ZCML ------------------------------- Directives that use ``zope.configuration.fields.GlobalObject`` as the value type for the global object parameters are automatically equipped to use discriminators. The convention is that if a dotted interface specification is prefaced by a dash, it's interpreted as a discriminator, e.g. for="-some.package.ISomeInterface" Let's try with the ``adapter`` directive. We'll register an adapter for IBar that also discriminates on IFoo. >>> def give_me_bar(bar): ... return bar To make our symbols available from the configuration machine we patch it onto the tests module. >>> import z3c.discriminator.tests >>> z3c.discriminator.tests.IBar = IBar >>> z3c.discriminator.tests.IFoo = IFoo >>> z3c.discriminator.tests.give_me_bar = give_me_bar We must first load the meta directives from ``zope.component``. >>> from cStringIO import StringIO >>> from zope.configuration import xmlconfig >>> xmlconfig.XMLConfig('meta.zcml', component)() Now we can Register the adapter. >>> xmlconfig.xmlconfig(StringIO(""" ... <configure xmlns="http://namespaces.zope.org/zope"> ... <adapter for="-z3c.discriminator.tests.IFoo ... z3c.discriminator.tests.IBar" ... provides="z3c.discriminator.tests.IBar" ... factory="z3c.discriminator.tests.give_me_bar" /> ... </configure> ... """)) Let's verify the adapter lookup: >>> component.getMultiAdapter((foo, bar), IBar) <Bar object at ...>
z3c.discriminator
/z3c.discriminator-0.2.tar.gz/z3c.discriminator-0.2/z3c/discriminator/README.txt
README.txt
Overview ======== Dobbin is an object database implemented on top of SQLAlchemy. It's designed to mimick the behavior of the Zope object database (ZODB) while providing greater flexibility and control of the storage. It supports strong typing with native SQL columns by utilizing the declarative field definitions from zope.schema. Weak typing is supported using the Python pickle protocol. Attributes are automatically persisted with the exception of those starting with the characters "_v_" (volatile attributes). Tables to support the strongly typed attributes are created on-the-fly with a 1:1 correspondence to interfaces with no inheritance (base interface). As such, objects are modelled as a join between the interfaces they implement plus a table that maintains object metadata and weakly typed instance attributes. Authors ------- This package was designed and implemented by Malthe Borch and Stefan Eletzhofer with parts contributed by Kapil Thangavelu and Laurence Rowe. It's licensed as ZPL.
z3c.dobbin
/z3c.dobbin-0.4.2.tar.gz/z3c.dobbin-0.4.2/README.txt
README.txt
from zope import interface from zope import schema from zope import component from zope.dottedname.resolve import resolve from zope.security.interfaces import IChecker from zope.security.checker import defineChecker, getCheckerForInstancesOf from zope.security.proxy import removeSecurityProxy from interfaces import IMapper from interfaces import IMapped import sqlalchemy as rdb from sqlalchemy import orm from sqlalchemy.orm.attributes import proxied_attribute_factory from z3c.saconfig import Session from uuid import uuid1 from random import randint from itertools import chain import bootstrap import session as tx import soup import zs2sa import types import utility def decode(name): return resolve(name.replace(':', '.')) def encode(iface): return iface.__identifier__.replace('.', ':') def expand(iface): yield iface for spec in iface.getBases(): for iface in expand(spec): yield iface @interface.implementer(IMapper) @component.adapter(interface.Interface) def getMapper(spec): """Return a mapper for the specification.""" if not callable(spec): raise TypeError("Create called for non-factory", spec) if IMapped.providedBy(spec): return spec.__mapper__ return createMapper(spec) def createMapper(spec): """Create a mapper for the specification.""" engine = Session().bind metadata = engine.metadata exclude = ['__name__'] # expand specification if interface.interfaces.IInterface.providedBy(spec): ifaces = set([spec.get(name).interface for name in spec.names(True)]) kls = object else: implemented = interface.implementedBy(spec) fields = chain(*[schema.getFields(iface) for iface in implemented]) ifaces = set([implemented.get(name).interface for name in fields]) kls = spec for name, value in spec.__dict__.items(): if isinstance(value, property): exclude.append(name) if not ifaces: spec.__mapper__ = bootstrap.Soup interface.alsoProvides(spec, IMapped) return spec.__mapper__ # create joined table properties = {} first_table = None for (t, p) in (getTable(iface, metadata, exclude) for iface in ifaces): if first_table is None: table = first_table = t else: table = table.join(t, onclause=(t.c.id==first_table.c.id)) properties.update(p) specification_path = '%s.%s' % (spec.__module__, spec.__name__) class Mapper(bootstrap.Soup, kls): interface.implements(*ifaces) __spec__ = specification_path def __init__(self, *args, **kwargs): super(Mapper, self).__init__(*args, **kwargs) # set soup metadata self.uuid = "{%s}" % uuid1() self.spec = self.__spec__ # if the specification is an interface class, try to look up a # security checker and define it on the mapper if interface.interfaces.IInterface.providedBy(spec): checker = component.queryAdapter(spec, IChecker) # if not, assign the checker from the specification to the mapper. else: checker = getCheckerForInstancesOf(spec) if checker is not None: defineChecker(Mapper, checker) # set class representation method if not defined if not isinstance(Mapper.__repr__, types.MethodType): def __repr__(self): return "<Mapper (%s.%s) at %s>" % \ (spec.__module__, spec.__name__, hex(id(self))) Mapper.__repr__ = __repr__ # set ``property``-derived properties directly on the mapper for name, prop in properties.items(): if isinstance(prop, property): del properties[name] setattr(Mapper, name, prop) soup_table = bootstrap.get_soup_table() polymorphic = ( [Mapper], table.join( soup_table, first_table.c.id==soup_table.c.id)) # XXX: currently SQLAlchemy expects all classes to be new-style; # we 'fix' these classes by patching on a ``__subclasses__`` # class-method. utility.fixup_class_hierarchy(Mapper) orm.mapper( Mapper, table, properties=properties, exclude_properties=exclude, with_polymorphic=polymorphic, inherits=bootstrap.Soup, inherit_condition=(first_table.c.id==soup_table.c.id)) spec.__mapper__ = Mapper interface.alsoProvides(spec, IMapped) return Mapper def removeMapper(spec): del spec.mapper interface.noLongerProvides(spec, IMapped) def getTable(iface, metadata, ignore=()): name = encode(iface) columns = [] properties = {} for field in map(lambda key: iface[key], iface.names()): property_factory = None if field.__name__ in ignore: continue try: factories = zs2sa.fieldmap[type(field)] except KeyError: # raise NotImplementedError("Field type unsupported (%s)." % field) continue try: column_factory, property_factory = factories except TypeError: column_factory = factories if column_factory is not None: column = column_factory(field, metadata) columns.append(column) else: column = None if property_factory is not None: props = property_factory(field, column, metadata) properties.update(props) if name in metadata.tables: return metadata.tables[name], properties kw = dict(useexisting=True) soup_table = bootstrap.get_soup_table() table = rdb.Table( name, metadata, rdb.Column('id', rdb.Integer, rdb.ForeignKey(soup_table.c.id), primary_key=True), *columns, **kw) table.create(checkfirst=True) return table, properties
z3c.dobbin
/z3c.dobbin-0.4.2.tar.gz/z3c.dobbin-0.4.2/src/z3c/dobbin/mapper.py
mapper.py
Walk-through of the framework ============================= This section demonstrates the functionality of the package. Introduction ------------ Dobbin uses SQLAlchemy's object relational mapper to transparently store objects in the database. Objects are persisted in two levels: Attributes may correspond directly to a table column in which case we say that the attribute is strongly typed. This is the most optimal way to store data. We may also store attributes that are not mapped directly to a column; in this case, the value of the attribute is stored as a Python pickle. This allows weak typing, but also persistence of amorphic data, e.g. data which does not fit naturally in a relational database. A universally unique id (UUID) is automatically assigned to all objects. We begin with a new database session. >>> import z3c.saconfig >>> session = z3c.saconfig.Session() Declarative configuration ------------------------- We can map attributes to table columns using zope.schema. Instead of using SQL column definitions, we rely on the declarative properties of schema fields. We start out with an interface decribing a recorded album. >>> class IAlbum(interface.Interface): ... artist = schema.TextLine( ... title=u"Artist", ... default=u"") ... ... title = schema.TextLine( ... title=u"Title", ... default=u"") We can now fabricate instances that implement this interface by using the ``create`` method. This is a shorthand for setting up a mapper and creating an instance by calling it. >>> from z3c.dobbin.factory import create >>> album = create(IAlbum) Set attributes. >>> album.artist = "The Beach Boys" >>> album.title = u"Pet Sounds" Interface inheritance is supported. For instance, a vinyl record is a particular type of album. >>> class IVinyl(IAlbum): ... rpm = schema.Int( ... title=u"RPM") >>> vinyl = create(IVinyl) >>> vinyl.artist = "Diana Ross and The Supremes" >>> vinyl.title = "Taking Care of Business" >>> vinyl.rpm = 45 The attributes are instrumented by SQLAlchemy and map directly to a column in a table. >>> IVinyl.__mapper__.artist <sqlalchemy.orm.attributes.InstrumentedAttribute object at ...> A compact disc is another kind of album. >>> class ICompactDisc(IAlbum): ... year = schema.Int(title=u"Year") Let's pick a more recent Diana Ross, to fit the format. >>> cd = create(ICompactDisc) >>> cd.artist = "Diana Ross" >>> cd.title = "The Great American Songbook" >>> cd.year = 2005 To verify that we've actually inserted objects to the database, we commit the transacation, thus flushing the current session. >>> session.save(album) >>> session.save(vinyl) >>> session.save(cd) We must actually query the database once before proceeding; this seems to be a bug in ``zope.sqlalchemy``. >>> results = session.query(album.__class__).all() Proceed with the transaction. >>> import transaction >>> transaction.commit() We get a reference to the database metadata object, to locate each underlying table. >>> engine = session.bind >>> metadata = engine.metadata Tables are given a name based on the dotted path of the interface they describe. A utility method is provided to create a proper table name for an interface. >>> from z3c.dobbin.mapper import encode Verify tables for ``IVinyl``, ``IAlbum`` and ``ICompactDisc``. >>> session.bind = metadata.bind >>> session.execute(metadata.tables[encode(IVinyl)].select()).fetchall() [(2, 45)] >>> session.execute(metadata.tables[encode(IAlbum)].select()).fetchall() [(1, u'Pet Sounds', u'The Beach Boys'), (2, u'Taking Care of Business', u'Diana Ross and The Supremes'), (3, u'The Great American Songbook', u'Diana Ross')] >>> session.execute(metadata.tables[encode(ICompactDisc)].select()).fetchall() [(3, 2005)] Mapping concrete classes ------------------------ Now we'll create a mapper based on a concrete class. We'll let the class implement the interface that describes the attributes we want to store, but also provides a custom method. >>> class Vinyl(object): ... interface.implements(IVinyl) ... ... def __repr__(self): ... return "<Vinyl %s: %s (@ %d RPM)>" % \ ... (self.artist, self.title, self.rpm) Although the symbols we define in this test report that they're available from the ``__builtin__`` module, they really aren't. We'll manually add these symbols. >>> import __builtin__ >>> __builtin__.IVinyl = IVinyl >>> __builtin__.IAlbum = IAlbum >>> __builtin__.Vinyl = Vinyl Create an instance using the ``create`` factory. >>> vinyl = create(Vinyl) Verify that we've instantiated and instance of our class. >>> isinstance(vinyl, Vinyl) True Copy the attributes from the Diana Ross vinyl record. >>> diana = session.query(IVinyl.__mapper__).filter_by( ... artist=u"Diana Ross and The Supremes")[0] >>> vinyl.artist = diana.artist >>> vinyl.title = diana.title >>> vinyl.rpm = diana.rpm Verify that the methods on our ``Vinyl``-class are available on the mapper. >>> repr(vinyl) '<Vinyl Diana Ross and The Supremes: Taking Care of Business (@ 45 RPM)>' When mapping a class we may run into properties that should take the place of a column (a read-only value). As an example, consider this experimental record class where rotation speed is a function of the title and artist. >>> class Experimental(Vinyl): ... @property ... def rpm(self): ... return len(self.title+self.artist) >>> experimental = create(Experimental) XXX: There's currently an issue with SQLAlchemy that hinders this behavior; it specifically won't work if a default value is set on the column that we're overriding. >>> # session.save(experimental) >>> experimental.artist = vinyl.artist >>> experimental.title = vinyl.title Let's see how fast this record should be played back. >>> experimental.rpm 50 Relations --------- Relations are columns that act as references to other objects. They're declared using the ``zope.schema.Object`` field. Note that we needn't declare the relation target type in advance, although it may be useful in general to specialize the ``schema`` keyword parameter. >>> class IFavorite(interface.Interface): ... item = schema.Object( ... title=u"Item", ... schema=interface.Interface) >>> __builtin__.IFavorite = IFavorite Let's make our Diana Ross record a favorite. >>> favorite = create(IFavorite) >>> favorite.item = vinyl >>> favorite.item <Vinyl Diana Ross and The Supremes: Taking Care of Business (@ 45 RPM)> >>> session.save(favorite) We'll commit the transaction and lookup the object by its unique id. >>> transaction.commit() >>> from z3c.dobbin.soup import lookup >>> favorite = lookup(favorite.uuid) When we retrieve the related items, it's automatically reconstructed to match the specification to which it was associated. >>> favorite.item <Vinyl Diana Ross and The Supremes: Taking Care of Business (@ 45 RPM)> We can create relations to objects that are not mapped. Let's model an accessory item. >>> class IAccessory(interface.Interface): ... name = schema.TextLine(title=u"Name of accessory") >>> class Accessory(object): ... interface.implements(IAccessory) ... ... def __repr__(self): ... return "<Accessory '%s'>" % self.name If we now instantiate an accessory and assign it as a favorite item, we'll implicitly create a mapper from the class specification and insert it into the database. >>> cleaner = Accessory() >>> cleaner.name = u"Record cleaner" Set up relation. >>> favorite.item = cleaner Let's try and get back our record cleaner item. >>> __builtin__.Accessory = Accessory >>> favorite.item <Accessory 'Record cleaner'> Within the same transaction, the relation will return the original object, maintaining integrity. >>> favorite.item is cleaner True The session keeps a copy of the pending object until the transaction is ended. >>> cleaner in session._d_pending.values() True However, once we commit the transaction, the relation is no longer attached to the relation source, and the correct data will be persisted in the database. >>> cleaner.name = u"CD cleaner" >>> session.flush() >>> session.update(favorite) >>> favorite.item.name u'CD cleaner' This behavior should work well in a request-response type environment, where the request will typically end with a commit. Collections ----------- We can instrument properties that behave like collections by using the sequence and mapping schema fields. Let's set up a record collection as an ordered list. >>> class ICollection(interface.Interface): ... records = schema.List( ... title=u"Records", ... value_type=schema.Object(schema=IAlbum) ... ) >>> __builtin__.ICollection = ICollection >>> collection = create(ICollection) >>> collection.records [] Add the Diana Ross record, and save the collection to the session. >>> collection.records.append(diana) >>> session.save(collection) We can get our collection back. >>> collection = lookup(collection.uuid) Let's verify that we've stored the Diana Ross record. >>> record = collection.records[0] >>> record.artist, record.title (u'Diana Ross and The Supremes', u'Taking Care of Business') >>> session.flush() When we create a new, transient object and append it to a list, it's automatically saved on the session. >>> collection = lookup(collection.uuid) >>> kool = create(IVinyl) >>> kool.artist = u"Kool & the Gang" >>> kool.title = u"Music Is the Message" >>> kool.rpm = 33 >>> collection.records.append(kool) >>> [record.artist for record in collection.records] [u'Diana Ross and The Supremes', u'Kool & the Gang'] >>> session.flush() >>> session.update(collection) We can remove items. >>> collection.records.remove(kool) >>> len(collection.records) == 1 True And extend. >>> collection.records.extend((kool,)) >>> len(collection.records) == 2 True Items can appear twice in the list. >>> collection.records.append(kool) >>> len(collection.records) == 3 True We can add concrete instances to collections. >>> marvin = Vinyl() >>> marvin.artist = u"Marvin Gaye" >>> marvin.title = u"Let's get it on" >>> marvin.rpm = 33 >>> collection.records.append(marvin) >>> len(collection.records) == 4 True And remove them, too. >>> collection.records.remove(marvin) >>> len(collection.records) == 3 True The standard list methods are available. >>> collection.records = [marvin, vinyl] >>> collection.records.sort(key=lambda record: record.artist) >>> collection.records [<Vinyl Diana Ross and The Supremes: Taking Care of Business (@ 45 RPM)>, <Vinyl Marvin Gaye: Let's get it on (@ 33 RPM)>] >>> collection.records.reverse() >>> collection.records [<Vinyl Marvin Gaye: Let's get it on (@ 33 RPM)>, <Vinyl Diana Ross and The Supremes: Taking Care of Business (@ 45 RPM)>] >>> collection.records.index(vinyl) 1 >>> collection.records.pop() <Vinyl Diana Ross and The Supremes: Taking Care of Business (@ 45 RPM)> >>> collection.records.insert(0, vinyl) >>> collection.records [<Vinyl Diana Ross and The Supremes: Taking Care of Business (@ 45 RPM)>, <Vinyl Marvin Gaye: Let's get it on (@ 33 RPM)>] >>> collection.records.count(vinyl) 1 >>> collection.records[1] = vinyl >>> collection.records.count(vinyl) 2 For good measure, let's create a new instance without adding any elements to its list. >>> empty_collection = create(ICollection) >>> session.save(empty_collection) To demonstrate the mapping implementation, let's set up a catalog for our record collection. We'll index the records by their ASIN string. >>> class ICatalog(interface.Interface): ... index = schema.Dict( ... title=u"Record index") >>> catalog = create(ICatalog) >>> session.save(catalog) Add a record to the index. >>> catalog.index[u"B00004WZ5Z"] = diana >>> catalog.index[u"B00004WZ5Z"] <Mapper (__builtin__.IVinyl) at ...> Verify state after commit. >>> transaction.commit() >>> catalog.index[u"B00004WZ5Z"] <Mapper (__builtin__.IVinyl) at ...> Let's check that the standard dict methods are supported. >>> catalog.index.values() [<Mapper (__builtin__.IVinyl) at ...>] >>> tuple(catalog.index.itervalues()) (<Mapper (__builtin__.IVinyl) at ...>,) >>> catalog.index.setdefault(u"B00004WZ5Z", None) <Mapper (__builtin__.IVinyl) at ...> >>> catalog.index.pop(u"B00004WZ5Z") <Mapper (__builtin__.IVinyl) at ...> >>> len(catalog.index) 0 Concrete instances are supported. >>> vinyl = Vinyl() >>> vinyl.artist = diana.artist >>> vinyl.title = diana.title >>> vinyl.rpm = diana.rpm >>> catalog.index[u"B00004WZ5Z"] = vinyl >>> len(catalog.index) 1 >>> catalog.index.popitem() (u'B00004WZ5Z', <Vinyl Diana Ross and The Supremes: Taking Care of Business (@ 45 RPM)>) >>> catalog.index = {u"B00004WZ5Z": vinyl} >>> len(catalog.index) 1 >>> catalog.index.clear() >>> len(catalog.index) 0 We may use a mapped object as index. >>> catalog.index[diana] = diana >>> catalog.index.keys()[0] == diana.uuid True >>> transaction.commit() >>> catalog.index[diana] <Mapper (__builtin__.IVinyl) at ...> >>> class IDiscography(ICatalog): ... records = schema.Dict( ... title=u"Discographies by artist", ... value_type=schema.List()) Amorphic objects ---------------- We can set and retrieve attributes that aren't declared in an interface. >>> record = create(interface.Interface) >>> record.publisher = u"Columbia records" >>> record.publisher u'Columbia records' >>> session.save(record) >>> session.query(record.__class__).filter_by( ... uuid=record.uuid)[0].publisher u'Columbia records' Using this kind of weak we can store (almost) any kind of structure. Values are kept as Python pickles. >>> favorite = create(interface.Interface) >>> session.save(favorite) A transaction hook makes sure that assigned values are transient during a session. >>> obj = object() >>> favorite.item = obj >>> favorite.item is obj True Integers, floats and unicode strings are straight-forward. >>> favorite.item = 42; transaction.commit() >>> favorite.item 42 >>> favorite.item = 42.01; transaction.commit() >>> 42 < favorite.item <= 42.01 True >>> favorite.item = u"My favorite number is 42."; transaction.commit() >>> favorite.item u'My favorite number is 42.' Normal strings need explicit coercing to ``str``. >>> favorite.item = "My favorite number is 42."; transaction.commit() >>> str(favorite.item) 'My favorite number is 42.' Or sequences of items. >>> favorite.item = (u"green", u"blue", u"red"); transaction.commit() >>> favorite.item (u'green', u'blue', u'red') Dictionaries. >>> favorite.item = {u"green": 0x00FF00, u"blue": 0x0000FF, u"red": 0xFF0000} >>> transaction.commit() >>> favorite.item {u'blue': 255, u'green': 65280, u'red': 16711680} >>> favorite.item[u"black"] = 0x000000 >>> sorted(favorite.item.items()) [(u'black', 0), (u'blue', 255), (u'green', 65280), (u'red', 16711680)] We do need explicitly set the dirty bit of this instance. >>> favorite.item = favorite.item >>> transaction.commit() >>> sorted(favorite.item.items()) [(u'black', 0), (u'blue', 255), (u'green', 65280), (u'red', 16711680)] When we create relations to mutable objects, a hook is made into the transaction machinery to keep track of the pending state. >>> some_list = [u"green", u"blue"] >>> favorite.item = some_list >>> some_list.append(u"red"); transaction.commit() >>> favorite.item [u'green', u'blue', u'red'] Amorphic structures. >>> favorite.item = ((1, u"green"), (2, u"blue"), (3, u"red")); transaction.commit() >>> favorite.item ((1, u'green'), (2, u'blue'), (3, u'red')) Structures involving relations to other instances. >>> favorite.item = vinyl; transaction.commit() >>> favorite.item <Vinyl Diana Ross and The Supremes: Taking Care of Business (@ 45 RPM)> Self-referencing works because polymorphic attributes are lazy. >>> favorite.item = favorite; transaction.commit() >>> favorite.item <z3c.dobbin.bootstrap.Soup object at ...> Security -------- The security model from Zope is applied to mappers. >>> from zope.security.checker import getCheckerForInstancesOf Our ``Vinyl`` class does not have a security checker defined. >>> from z3c.dobbin.mapper import getMapper >>> mapper = getMapper(Vinyl) >>> getCheckerForInstancesOf(mapper) is None True Let's set a checker and regenerate the mapper. >>> from zope.security.checker import defineChecker, CheckerPublic >>> defineChecker(Vinyl, CheckerPublic) >>> from z3c.dobbin.mapper import createMapper >>> mapper = createMapper(Vinyl) >>> getCheckerForInstancesOf(mapper) is CheckerPublic True Known limitations ----------------- Certain names are disallowed, and will be ignored when constructing the mapper. >>> class IKnownLimitations(interface.Interface): ... __name__ = schema.TextLine() >>> from z3c.dobbin.interfaces import IMapper >>> mapper = IMapper(IKnownLimitations) >>> mapper.__name__ 'Mapper' Cleanup ------- Commit session. >>> transaction.commit()
z3c.dobbin
/z3c.dobbin-0.4.2.tar.gz/z3c.dobbin-0.4.2/src/z3c/dobbin/README.txt
README.txt
from zope import interface from interfaces import IMapper from interfaces import IMapped from zope.dottedname.resolve import resolve from z3c.saconfig import Session import factory import bootstrap import interfaces import session as tx import types BASIC_TYPES = (int, float, str, unicode, tuple, list, set, dict) IMMUTABLE_TYPES = (int, float, str, unicode, tuple) def lookup(uuid, ignore_pending=False): session = Session() # check if object is in pending session objects if not ignore_pending: try: token = tx.COPY_CONCRETE_TO_INSTANCE(uuid) return session._d_pending[token] except (AttributeError, KeyError): pass try: item = session.query(bootstrap.Soup).filter_by(uuid=uuid)[0] except IndexError: raise LookupError("Unable to locate object with UUID = '%s'." % uuid) # build item return build(item.spec, item.uuid) def build(spec, uuid): kls = resolve(spec) mapper = IMapper(kls) session = Session() return session.query(mapper).filter_by(uuid=uuid)[0] def persist(item): instance = interfaces.IMapped(item) if interfaces.IBasicType.providedBy(instance): instance.value = item else: update(instance, item) # set soup identifier on instances if type(item) not in BASIC_TYPES: item._d_uuid = instance.uuid # register mutable objects with transaction manager if type(item) not in IMMUTABLE_TYPES: uuid = instance.uuid def copy_concrete_to_mapped(): # update attributes update(instance, item) # add transaction hook tx.addBeforeCommitHook( tx.COPY_CONCRETE_TO_INSTANCE(uuid), item, copy_concrete_to_mapped) return instance def update(instance, item): # set attributes for iface in interface.providedBy(item): for name in iface.names(): value = getattr(item, name) setattr(instance, name, value)
z3c.dobbin
/z3c.dobbin-0.4.2.tar.gz/z3c.dobbin-0.4.2/src/z3c/dobbin/soup.py
soup.py
from zope import interface from zope import schema import sqlalchemy as rdb from sqlalchemy import orm from z3c.saconfig import Session import session as tx import bootstrap import relations import collections class FieldTranslator(object): """Translate a zope schema field to a SQLAlchemy column.""" column_type = default = None def __init__(self, column_type=None, default=None): self.column_type = column_type or self.column_type self.default = default def extractInfo( self, field, info ): d = {} d['name'] = field.getName() if field.required: d['nullable'] = False if field.default is None: d['default'] = self.default else: d['default'] = field.default d['type'] = self.column_type return d def __call__(self, field, annotation): d = self.extractInfo( field, annotation ) name, type = d['name'], d['type'] del d['name'] del d['type'] return rdb.Column( name, type, **d) class StringTranslator(FieldTranslator): column_type = rdb.Text def __init__(self, column_type=None): self.column_type = column_type or self.column_type def extractInfo( self, field, info ): d = super( StringTranslator, self ).extractInfo( field, info ) if schema.interfaces.IMinMaxLen.providedBy( field ): d['type'].length = field.max_length if field.default is None and not d.get('default'): d['default'] = u"" return d class ObjectTranslator(object): def __call__(self, field, metadata): return rdb.Column( field.__name__+'_uuid', bootstrap.UUID, nullable=False) class ObjectProperty(object): """Object property. We're not checking type here, because we'll only be creating relations to items that are joined with the soup. """ def __call__(self, field, column, metadata): relation = relations.RelationProperty(field) return { field.__name__: relation, relation.name: orm.relation( bootstrap.Soup, primaryjoin=bootstrap.Soup.uuid==column, foreign_keys=[column], enable_typechecks=False, lazy=True) } class CollectionProperty(object): """A collection property.""" collection_class = None relation_class = None def __call__(self, field, column, metadata): return { field.__name__: orm.relation( self.relation_class, primaryjoin=self.getPrimaryJoinCondition(), collection_class=self.collection_class, enable_typechecks=False) } def getPrimaryJoinCondition(self): return NotImplementedError("Must be implemented by subclass.") class ListProperty(CollectionProperty): collection_class = collections.OrderedList relation_class = relations.OrderedRelation def getPrimaryJoinCondition(self): return bootstrap.Soup.uuid==relations.OrderedRelation.left class TupleProperty(ListProperty): collection_class = collections.Tuple class DictProperty(CollectionProperty): collection_class = collections.Dict relation_class = relations.KeyRelation def getPrimaryJoinCondition(self): return bootstrap.Soup.uuid==relations.KeyRelation.left fieldmap = { schema.ASCII: StringTranslator(), schema.ASCIILine: StringTranslator(), schema.Bool: FieldTranslator(rdb.BOOLEAN, default=False), schema.Bytes: FieldTranslator(rdb.BLOB), schema.BytesLine: FieldTranslator(rdb.CLOB), schema.Choice: StringTranslator(rdb.Unicode), schema.Date: FieldTranslator(rdb.DATE), schema.Dict: (None, DictProperty()), schema.DottedName: StringTranslator(), schema.Float: FieldTranslator(rdb.Float, default=0), schema.Id: StringTranslator(rdb.Unicode), schema.Int: FieldTranslator(rdb.Integer, default=0), schema.List: (None, ListProperty()), schema.Tuple: (None, TupleProperty()), schema.Object: (ObjectTranslator(), ObjectProperty()), schema.Password: StringTranslator(rdb.Unicode), schema.SourceText: StringTranslator(rdb.UnicodeText), schema.Text: StringTranslator(rdb.UnicodeText), schema.TextLine: StringTranslator(rdb.Unicode), schema.URI: StringTranslator(rdb.Unicode), interface.Attribute: None, interface.interface.Method: None, }
z3c.dobbin
/z3c.dobbin-0.4.2.tar.gz/z3c.dobbin-0.4.2/src/z3c/dobbin/zs2sa.py
zs2sa.py
from zope import interface from zope import component import sqlalchemy as rdb from sqlalchemy import orm from z3c.saconfig import Session import soup import utility import relations import interfaces import cPickle class UUID(rdb.types.TypeEngine): def get_col_spec(self): return "UUID" def get_soup_table(): return Soup._sa_class_manager.mapper.local_table def initialize(event=None): """Database initialization. This method sets up the tables that are necessary for the operation of the persistence and relational framework. """ session = Session() engine = session.bind engine.metadata = metadata = rdb.MetaData(engine) soup = rdb.Table( 'dobbin:soup', metadata, rdb.Column('id', rdb.Integer, primary_key=True, autoincrement=True), rdb.Column('uuid', UUID, unique=True, index=True), rdb.Column('spec', rdb.String, index=True), rdb.Column('dict', rdb.PickleType, default={}, index=False), ) soup_fk = rdb.ForeignKey(soup.c.uuid) int_relation = rdb.Table( 'dobbin:relation:int', metadata, rdb.Column('id', rdb.Integer, primary_key=True, autoincrement=True), rdb.Column('left', UUID, soup_fk, index=True), rdb.Column('right', UUID, soup_fk), rdb.Column('order', rdb.Integer, nullable=False)) str_relation = rdb.Table( 'dobbin:relation:str', metadata, rdb.Column('id', rdb.Integer, primary_key=True, autoincrement=True), rdb.Column('left', UUID, soup_fk, index=True), rdb.Column('right', UUID, soup_fk), rdb.Column('key', rdb.Unicode, nullable=False)) # set up mappers orm.mapper(Soup, soup) orm.mapper(relations.OrderedRelation, int_relation) orm.mapper(relations.KeyRelation, str_relation) # create all tables metadata.create_all() class Soup(object): interface.implements(interfaces.IMapped) """Soup class. This is the base object of all mappers. """ def __new__(cls, *args, **kwargs): inst = object.__new__(cls, *args, **kwargs) inst.__dict__ = utility.dictproxy(inst) return inst def __cmp__(self, other): if interfaces.IMapped.providedBy(other): return cmp(self.id, other.id) return -1 def __reduce__(self): return (soup.build, (self.__spec__, self.uuid,))
z3c.dobbin
/z3c.dobbin-0.4.2.tar.gz/z3c.dobbin-0.4.2/src/z3c/dobbin/bootstrap.py
bootstrap.py
from zope.security.checker import NamesChecker from sqlalchemy import orm import interfaces import relations import soup import types class Tuple(object): def __init__(self): self.data = [] @property def adapter(self): return orm.collections.collection_adapter(self) @orm.collections.collection.appender def _appender(self, item): self.data.append(item) @orm.collections.collection.iterator def _iterator(self): return iter(self.data) @orm.collections.collection.remover def _remover(self, item): self.data.remove(item) @orm.collections.collection.converter def convert(self, items): converted = [] for item in items: if not interfaces.IMapped.providedBy(item): item = soup.persist(item) # set up relation relation = relations.OrderedRelation() relation.target = item relation.order = len(converted) converted.append(relation) return converted def __iter__(self): return (self[i] for i in range(len(self.data))) def __getitem__(self, index): obj = self.data[index].target if interfaces.IBasicType.providedBy(obj): return obj.value else: return obj def __setitem__(self, index, value): return TypeError("Object does not support item assignment.") def __len__(self): return len(self.data) def __repr__(self): return repr(tuple(self)) class OrderedList(Tuple): __Security_checker__ = NamesChecker( ('append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort')) @orm.collections.collection.appender def _appender(self, item): self.data.append(item) @orm.collections.collection.iterator def _iterator(self): return iter(self.data) @orm.collections.collection.remover def _remover(self, item): self.data.remove(item) @orm.collections.collection.internally_instrumented def append(self, item, _sa_initiator=None): if not interfaces.IMapped.providedBy(item): item = soup.persist(item) # set up relation relation = relations.OrderedRelation() relation.target = item relation.order = len(self.data) self.adapter.fire_append_event(relation, _sa_initiator) # add relation to internal list self.data.append(relation) @orm.collections.collection.internally_instrumented def remove(self, item, _sa_initiator=None): if interfaces.IMapped.providedBy(item): uuid = item.uuid else: uuid = item._d_uuid for relation in self.data: if relation.right == uuid: self.adapter.fire_remove_event(relation, _sa_initiator) self.data.remove(relation) break else: raise ValueError("Not in list: %s" % item) def extend(self, items): map(self.append, items) def count(self, value): return list(self).count(value) def index(self, value, **kwargs): for index in range(len(self)): if self[index] == value: return index raise ValueError("%s not found in list." % value) @orm.collections.collection.internally_instrumented def insert(self, index, item): stack = self.data[index:] del self.data[index:] self.append(item) for relation in stack: relation.order += 1 self.data.append(relation) @orm.collections.collection.internally_instrumented def pop(self, index=-1, _sa_initiator=None): relation = self.data[index] obj = relation.target self.adapter.fire_remove_event(relation, _sa_initiator) del self.data[index] stack = self.data[index:] for relation in stack: relation.order -= 1 return obj def reverse(self): self.data.reverse() for index in range(len(self.data)): self.data[index].order = index def sort(self, **kwargs): data = list(self) data_relation_mapping = zip(data, self.data) mapping = {} for item, relation in data_relation_mapping: relations = mapping.setdefault(item, []) relations.append(relation) data.sort(**kwargs) del self.data[:] for item in data: relation = mapping[item].pop() relation.order = len(self.data) self.data.append(relation) def __repr__(self): return repr(list(self)) @orm.collections.collection.internally_instrumented def __setitem__(self, index, value, _sa_initiator=None): # remove previous relation = self.data[index] self.adapter.fire_remove_event(relation, _sa_initiator) # add new self.append(value) relation = self.data[-1] del self.data[-1] # replace previous relation.order = index self.data[index] = relation class Dict(dict): __Security_checker__ = NamesChecker( ('clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values')) @property def adapter(self): return orm.collections.collection_adapter(self) @orm.collections.collection.appender @orm.collections.collection.replaces(1) def _appender(self, item): dict.__setitem__(self, item.key, item) @orm.collections.collection.iterator def _iterator(self): return dict.itervalues(self) @orm.collections.collection.remover def _remover(self, item): dict.remove(item) @orm.collections.collection.internally_instrumented def __setitem__(self, key, item, _sa_initiator=None): if not interfaces.IMapped.providedBy(item): item = soup.persist(item) # mapped objects may be used as key; internally, we'll use # the UUID in this case, however. if interfaces.IMapped.providedBy(key): key = key.uuid assert isinstance(key, types.StringTypes), \ "Only strings or mapped objects may be used as keys." # set up relation relation = relations.KeyRelation() relation.target = item relation.key = key self.adapter.fire_append_event(relation, _sa_initiator) dict.__setitem__(self, key, relation) @orm.collections.collection.converter def convert(self, d): converted = [] for key, item in d.items(): if not interfaces.IMapped.providedBy(item): item = soup.persist(item) # set up relation relation = relations.KeyRelation() relation.target = item relation.key = key converted.append(relation) return converted def values(self): return [self[key] for key in self] def itervalues(self): return (self[key] for key in self) @orm.collections.collection.internally_instrumented def pop(self, key, _sa_initiator=None): relation = dict.pop(self, key) obj = relation.target self.adapter.fire_remove_event(relation, _sa_initiator) if interfaces.IBasicType.providedBy(obj): return obj.value else: return obj @orm.collections.collection.internally_instrumented def popitem(self, _sa_initiator=None): key, relation = dict.popitem(self) obj = relation.target self.adapter.fire_remove_event(relation, _sa_initiator) if interfaces.IBasicType.providedBy(obj): return key, obj.value else: return key, obj @orm.collections.collection.internally_instrumented def clear(self, _sa_initiator=None): for relation in dict.itervalues(self): self.adapter.fire_remove_event(relation, _sa_initiator) dict.clear(self) def __getitem__(self, key): # mapped objects may be used as key; internally, we'll use # the UUID in this case, however. if interfaces.IMapped.providedBy(key): key = key.uuid assert isinstance(key, types.StringTypes), \ "Only strings or mapped objects may be used as keys." obj = dict.__getitem__(self, key).target if interfaces.IBasicType.providedBy(obj): return obj.value else: return obj def __repr__(self): return repr(dict( (key, self[key]) for key in self))
z3c.dobbin
/z3c.dobbin-0.4.2.tar.gz/z3c.dobbin-0.4.2/src/z3c/dobbin/collections.py
collections.py
Extended testbrowser -------------------- This package provides some extensions to ``zope.testbrowser``. These are not included in the core because they have extra dependencies, such as ``lxml``. Requirements ~~~~~~~~~~~~ - lxml etree support ~~~~~~~~~~~~~ The extended test browser allows parsing of the result of a request into an etree using lxml (if the content type is text/html or text/xml). This is useful to perform more detailed analysis of web pages using e.g. XPath and related XML technologies. Example: >>> from z3c.etestbrowser.testing import ExtendedTestBrowser >>> browser = ExtendedTestBrowser() >>> browser.open("http://localhost/") >>> print(browser.contents) <!DOCTYPE ...> ... </html> >>> browser.etree <Element html at ...> >>> browser.etree.xpath('//body') [<Element body at ...>] Strict XML ++++++++++ It is possible to force the test browser to use the xml parser: >>> browser.xml_strict False >>> browser.xml_strict = True >>> browser.open("http://localhost/") >>> browser.etree <Element {http://www.w3.org/1999/xhtml}html at ...> >>> browser.etree.xpath( ... '//html:body', namespaces={'html': 'http://www.w3.org/1999/xhtml'}) [<Element {http://www.w3.org/1999/xhtml}body at ...>] LXML unicode support ++++++++++++++++++++ A couple of variations of libxml2 might interpret UTF-8 encoded strings incorrectly. We have a workaround for that. Let's have a look at a view that contains a German umlaut: >>> browser.xml_strict = False >>> browser.open('http://localhost/lxml.html') >>> browser.etree.xpath("//span")[0].text == u'K\xfcgelblitz.' True Invalid XML/HTML responses ++++++++++++++++++++++++++ Responses that contain a body with invalid XML/HTML will cause an error when accessing the etree or normalized_contents attribute, but will load fine for general TestBrowser use: >>> browser.open("http://localhost/empty.html") >>> browser.contents '' >>> browser.etree Traceback (most recent call last): ValueError: ... >>> browser.normalized_contents Traceback (most recent call last): ValueError: ... HTML/XML normalization ~~~~~~~~~~~~~~~~~~~~~~ The extended test browser allows normalized output of HTML and XML which makes testing examples with HTML or XML a bit easier when unimportant details like whitespace are changing: >>> browser.open('http://localhost/funny.html') >>> print(browser.contents) <html> <head> <title>Foo</title> </head> <body> <h1> Title </h1> </body> </html> <BLANKLINE> versus >>> print(browser.normalized_contents) <html> <head> <title>Foo</title> </head> <body> <h1> Title </h1> </body> </html>
z3c.etestbrowser
/z3c.etestbrowser-4.0-py3-none-any.whl/z3c/etestbrowser/README.rst
README.rst
"""Extensions for z3c.etestbrowser.""" import re import lxml.etree import lxml.html import zope.testbrowser.browser RE_CHARSET = re.compile('.*;charset=(.*)') def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " for e in elem: indent(e, level+1) if not e.tail or not e.tail.strip(): e.tail = i + " " if not e.tail or not e.tail.strip(): e.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i class ExtendedTestBrowser(zope.testbrowser.browser.Browser): """An extended testbrowser implementation. Features: - offers the content also as parsed etree """ xml_strict = False _etree = None _normalized_contents = None @property def etree(self): if self._etree is not None: return self._etree # I'm not using any internal knowledge about testbrowser # here, to avoid breakage. Memory usage won't be a problem. if self.xml_strict: self._etree = lxml.etree.fromstring( self.contents, parser=lxml.etree.XMLParser(resolve_entities=False)) else: # This is a workaround against the broken fallback for # encoding detection of libxml2. # We have a chance of knowing the encoding as Zope states this in # the content-type response header. self._etree = lxml.etree.HTML(self.contents) if self._etree is None: raise ValueError( 'ETree could not be constructed. Contents might be empty.') return self._etree @property def normalized_contents(self): if self._normalized_contents is None: indent(self.etree) self._normalized_contents = lxml.etree.tostring( self.etree, pretty_print=True, encoding=str) return self._normalized_contents def _changed(self): super()._changed() self._etree = None self._normalized_contents = None
z3c.etestbrowser
/z3c.etestbrowser-4.0-py3-none-any.whl/z3c/etestbrowser/browser.py
browser.py
Using testbrowser on the internet --------------------------------- The ``z3c.etestbrowser.browser`` module exposes an ``ExtendedTestBrowser`` class that simulates a web browser similar to Mozilla Firefox or IE. >>> from z3c.etestbrowser.browser import ExtendedTestBrowser >>> browser = ExtendedTestBrowser() It can send arbitrary headers; this is helpful for setting the language value, so that your tests format values the way you expect in your tests, if you rely on zope.i18n locale-based formatting or a similar approach. >>> browser.addHeader('Accept-Language', 'en-US') The browser can `open` web pages: >>> browser.open('https://www.w3.org') >>> print(browser.contents) <!DOCTYPE html ... ...The World Wide Web Consortium (W3C) is an international community...
z3c.etestbrowser
/z3c.etestbrowser-4.0-py3-none-any.whl/z3c/etestbrowser/over_the_wire.rst
over_the_wire.rst
========= z3c.etree ========= *z3c.etree* provides some mechanisms (a common interface) for integrating any ElementTree engine with the Zope component architecture. This allows applications to look up a engine against this interface. As such this package does not implement the ElementTree API. *z3c.etree* also provides a set of utilities that can be used to make testing XML output in doctests easier. This functionality can also be called from a python based unit test via the *assertXMLEqual* method. Developers ========== >>> import z3c.etree >>> import z3c.etree.testing >>> engine = z3c.etree.testing.etreeSetup() Here are some examples for how to use *z3c.etree* with your own code. To generate a Element object with the tag *DAV:getcontenttype* all we have to do is: >>> etree = z3c.etree.getEngine() >>> elem = etree.Element("{DAV:}getcontenttype") >>> elem #doctest:+ELLIPSIS <Element ...> >>> z3c.etree.testing.assertXMLEqual(etree.tostring(elem), """ ... <getcontenttype xmlns="DAV:"/>""") Now to add a value this element use just use the *elem* variable has the API suggests. >>> elem.text = "text/plain" >>> z3c.etree.testing.assertXMLEqual(etree.tostring(elem), """ ... <getcontenttype xmlns="DAV:">text/plain</getcontenttype>""") Tear-down ========= >>> z3c.etree.testing.etreeTearDown()
z3c.etree
/z3c.etree-0.9.2.tar.gz/z3c.etree-0.9.2/src/z3c/etree/README.txt
README.txt
__docformat__ = 'restructuredtext' import copy from zope.interface import implements from interfaces import IEtree class BaseEtree(object): def Comment(self, text = None): return self.etree.Comment(text) # XXX - not tested def dump(self, elem): return self.etree.dump(elem) def Element(self, tag, attrib = {}, **extra): return self.etree.Element(tag, attrib, **extra) def ElementTree(self, element = None, file = None): return self.etree.ElementTree(element, file = file) def XML(self, text): return self.etree.fromstring(text) fromstring = XML def iselement(self, element): return self.etree.iselement(element) # XXX - not tested def iterparse(self, source, events = None): return self.etree.iterparse(source, events) def parse(self, source, parser = None): return self.etree.parse(source, parser) def PI(self, target, text = None): raise NotImplementedError, "lxml doesn't implement PI" ProcessingInstruction = PI def QName(self, text_or_uri, tag = None): return self.etree.QName(text_or_uri, tag) def SubElement(self, parent, tag, attrib = {}, **extra): return self.etree.SubElement(parent, tag, attrib, **extra) def tostring(self, element, encoding = None): return self.etree.tostring(element, encoding = encoding) def TreeBuilder(self, element_factory = None): raise NotImplementedError, "lxml doesn't implement TreeBuilder" def XMLTreeBuilder(self, html = 0, target = None): raise NotImplementedError, "lxml doesn't implement XMLTreeBuilder" class EtreeEtree(BaseEtree): implements(IEtree) def __init__(self): from elementtree import ElementTree self.etree = ElementTree def XMLTreeBuilder(self, html = 0, target = None): return self.etree.XMLTreeBuilder(html, target) def PI(self, target, text = None): return self.etree.PI(target, text) ProcessingInstruction = PI class CEtree(EtreeEtree): implements(IEtree) def __init__(self): import cElementTree self.etree = cElementTree class EtreePy25(BaseEtree): implements(IEtree) def __init__(self): from xml.etree import ElementTree self.etree = ElementTree def XMLTreeBuilder(self, html = 0, target = None): return self.etree.XMLTreeBuilder(html, target) def PI(self, target, text = None): return self.etree.PI(target, text) ProcessingInstruction = PI class LxmlEtree(BaseEtree): implements(IEtree) def __init__(self): from lxml import etree self.etree = etree
z3c.etree
/z3c.etree-0.9.2.tar.gz/z3c.etree-0.9.2/src/z3c/etree/etree.py
etree.py
``z3c.evalexception`` provides two WSGI middlewares for debugging web applications running on the ``zope.publisher`` object publishing framework (e.g. Zope 3). Both middlewares will intercept an exception thrown by the application and provide means for debugging. Interactive AJAX debugger ========================= ``z3c.evalexception.ZopeEvalException`` lets you interactively debug exceptions from a browser. It is a small wrapper around the ``EvalException`` middleware from ``paste.evalexception``. You can easily refer to it in a PasteDeploy-style configuration file using the ``ajax`` entry-point:: [filter-app:main] use = egg:z3c.evalexception#ajax next = zope [app:zope] use = egg:YourApp [server:main] use = egg:Paste#http host = 127.0.0.1 port = 8080 Post-mortem pdb =============== ``z3c.evalexception.PostMortemDebug`` invokes pdb's post-mortem mode when the application has thrown an exception. You can refer to it in a PasteDeploy-style configuration file using the ``pdb`` entry-point:: [filter-app:main] use = egg:z3c.evalexception#pdb next = zope [app:zope] use = egg:YourApp [server:main] use = egg:Paste#http host = 127.0.0.1 port = 8080
z3c.evalexception
/z3c.evalexception-3.0.tar.gz/z3c.evalexception-3.0/README.rst
README.rst
=================== Filestorage Package =================== This package offers large file handling solutions for zope3. The first implementation is based on properties, the second on wsgi. The property implementation runs on plain zope 3. This is work in progress: see todo.txt Property ======== Installation ------------ Define an evnironment variable in your runzope like this:: os.environ['EXTFILE_STORAGEDIR'] = '/tmp/filestorage' Or define the storage directory in zope.conf like this (this overrides the environment variable):: <product-config z3c.extfile> storagedir /tmp/filestorage </product-config> This causes a IHashDir utilitiy to be registered upon zope startup. see hashdir.txt, property.txt WSGI (optional) =============== This package provides a wsgi filter that upon upload replaces the content of the upload with the sha digest of the content and stores the file on the filesystem. Upon download it looks if it has a digest and returns the according file directly from the filesystem. See also: hashdir.txt, processort.txt This package is currently only tested with zope3 twisted server. Requirements ============ Zope 3 with twisted server, this package does not work with zserver. :zope.paste: follow the instructions in http://svn.zope.org/zope.paste/trunk/README.txt Installation ============ Add the following to instance_home/etc/paste.ini. The directory parameter defines the storage directory for files. Example paste.ini:: [app:main] paste.app_factory = zope.paste.application:zope_publisher_app_factory filter-with = fs [filter:fs] paste.filter_factory = z3c.extfile.filter:filter_factory directory = /path/to/hashdir/storage Testing ======= If you use extfile in your testing the you ned to have a storagedir set for testing. You can do this by simply importing z3c.extfile.testing in your tests.py file. This will set up the environment vaiable to a temporary directory during the test.
z3c.extfile
/z3c.extfile-0.3.0b2.tar.gz/z3c.extfile-0.3.0b2/src/z3c/extfile/README.txt
README.txt
import os.path from z3c.extfile import processor, hashdir from cStringIO import StringIO import mimetypes import interfaces from zope.cachedescriptors.property import Lazy BLOCK_SIZE = 1024*128 class FSFilter(object): def __init__(self, app, directory=None): self.app = app if directory is not None: # use provided directory self.dir = os.path.abspath(directory) else: self.dir = None @Lazy def hd(self): if self.dir is None: #use environment variable if not os.environ.has_key('EXTFILE_STORAGEDIR'): raise RuntimeError, "EXTFILE_STORAGEDIR not defined" self.dir = os.environ.get('EXTFILE_STORAGEDIR') return hashdir.HashDir(self.dir) def __call__(self, env, start_response): method = env.get('REQUEST_METHOD') if env.get('HTTP_X_EXTFILE_HANDLE'): if method=='POST' and \ env.get('CONTENT_TYPE','').startswith('multipart/form-data;'): fp = env['wsgi.input'] out = StringIO() proc = processor.Processor( self.hd, contentInfo=env.has_key('HTTP_X_EXTFILE_INFO'), allowedTypes=env.get('HTTP_X_EXTFILE_TYPES'), ) cl = env.get('CONTENT_LENGTH') if not cl: raise RuntimeError, "No content-length header found" cl = int(cl) try: proc.pushInput(fp, out, cl) except interfaces.TypeNotAllowed: start_response("400 Bad Request", [ ('Content-Type', 'text/plain')]) return [] env['CONTENT_LENGTH'] = out.tell() out.seek(0) env['wsgi.input'] = out elif method == 'GET': resp = FileResponse(self.app, self.hd) return resp(env, start_response) return self.app(env, start_response) def getInfo(s): """takes a z3c.extfile info string and returns a (digest, contentType, contentLength) tuple. If the parsing fails digest is None""" parts = s.split(':') contentType = contentLength = None if len(parts)==2: digest = parts[1] elif len(parts)==4: digest, contentType, contentLength = parts[1:] else: digest = None if digest and len(digest)!=40: digest = None if contentLength is not None: try: contentLength=int(contentLength) except ValueError: contentLength = None return (digest, contentType, contentLength) class FileResponse(object): def __init__(self, app, hd): self.hd = hd self.app = app def start_response(self, status, headers_out, exc_info=None): """Intercept the response start from the filtered app.""" self.doHandle = False if '200' in status: for n,v in headers_out: # the length is digest(40) + len(z3c.extfile.digest) # we do not now how long the info is getting but it should # be under 100 if n.lower()=='content-length' and len(v)<3: self.doHandle = True break self.status = status self.headers_out = headers_out self.exc_info = exc_info def __call__(self, env, start_response): """Facilitate WSGI API by providing a callable hook.""" self.env = env self.real_start = start_response self.response = self.app(self.env, self.start_response) if self.doHandle is False: return self._orgStart() body = "".join(self.response) self.response = [body] if not body.startswith('z3c.extfile.digest:'): return self._orgStart() digest, contentType, contentLength = getInfo(body) if digest is None: return self._orgStart() try: f = self.hd.open(digest) except KeyError: # no such digest return self._orgStart() headers_out = dict( [(k.lower(),v) for k,v in self.headers_out] ) if contentType: headers_out['content-type'] = contentType if contentLength: headers_out['content-length'] = str(contentLength) else: headers_out['content-length'] = str(len(f)) headers_out = headers_out.items() self.real_start(self.status, headers_out, self.exc_info) return f.__iter__() def _orgStart(self): self.real_start(self.status, self.headers_out, self.exc_info) return self.response def filter_factory(global_conf, **local_conf): if local_conf.has_key('directory'): local_conf['directory'] = os.path.join( global_conf.get('here'), local_conf.get('directory')) def filter(app): return FSFilter(app, **local_conf) return filter
z3c.extfile
/z3c.extfile-0.3.0b2.tar.gz/z3c.extfile-0.3.0b2/src/z3c/extfile/filter.py
filter.py
from zope import component import os import hashdir import interfaces from zope.app.appsetup.product import getProductConfiguration import logging log = logging.getLogger('z3c.extfile') def getPath(): """returns the path of the storage directory If not path is defined None is returned >>> del os.environ['EXTFILE_STORAGEDIR'] >>> getPath() is None True If we have a evnironment variable it is returned. If the path does not exist a ValueError is raised. >>> os.environ['EXTFILE_STORAGEDIR'] = '/this/path/does/not/exist' >>> getPath() Traceback (most recent call last): ... ValueError: Extfile storage path does not exist: '/this/path/does/not/exist' >>> os.environ['EXTFILE_STORAGEDIR'] = os.path.dirname(__file__) >>> getPath() '.../z3c/extfile' If we have a product configuration this is used. >>> class Config(object): ... mapping = {} ... def getSectionName(self): ... return 'z3c.extfile' >>> config = Config() >>> path = os.path.join(os.path.dirname(__file__), 'browser') >>> config.mapping['storagedir'] = path >>> from zope.app.appsetup.product import setProductConfigurations >>> setProductConfigurations([config]) >>> getPath() is path True """ path = None config = getProductConfiguration('z3c.extfile') if config is not None: path = config.get('storagedir') path = path or os.environ.get('EXTFILE_STORAGEDIR') if path is None: return if not os.path.exists(path): raise ValueError, "Extfile storage path does not exist: %r" % path return path def bootStrapSubscriber(event): """create an IHashDir util if the EXTFILE_STORAGEDIR environment variable is present """ path = getPath() if path is not None: # look first if we have utility already hd = component.queryUtility(interfaces.IHashDir) if hd is not None: log.warn('Ignoring hashdir path %r using already' ' registered IHashDir Utility at %r' % ( path,hd.path)) return hd = hashdir.HashDir(path) component.provideUtility(hd, provides=interfaces.IHashDir) log.info('Registered IHashDir utility with storagedir: %r' % path)
z3c.extfile
/z3c.extfile-0.3.0b2.tar.gz/z3c.extfile-0.3.0b2/src/z3c/extfile/utility.py
utility.py
import sha import os import stat import tempfile import shutil from types import StringTypes, UnicodeType import interfaces from zope import interface from persistent import Persistent from zope.cachedescriptors.property import Lazy class HashDir(Persistent): """a directory holding files named after their sha1 hash""" interface.implements(interfaces.IHashDir) _path = None def __init__(self, path=None, fallbacks=()): self.path = path self.fallbacks = map(os.path.abspath, fallbacks) def _setPath(self, path): if path is None: return self._path = os.path.abspath(path) self.tmp = os.path.join(self.path, 'tmp') self.var = os.path.join(self.path, 'var') self._initPaths() def _getPath(self): return self._path path = property(_getPath,_setPath) def _initPaths(self): for path in [self.path,self.var,self.tmp]: if not os.path.exists(path): os.mkdir(path) def new(self): """returns a new filehandle""" handle, path = tempfile.mkstemp(prefix='dirty.', dir=self.tmp) return WriteFile(self, handle, path) def commit(self, f): """commit a file, this is called by the file""" digest = f.sha.hexdigest() target = os.path.join(self.var, digest) if os.path.exists(target): # we have that content so just delete the tmp file os.remove(f.path) else: shutil.move(f.path, target) os.chmod(target, 0440) return digest def digests(self): """returns all digests stored""" return os.listdir(self.var) def getPath(self, digest): if type(digest) not in StringTypes or len(digest) != 40: raise ValueError, repr(digest) if type(self.var) is UnicodeType: digest = unicode(digest) for base in [self.var] + self.fallbacks: path = os.path.join(base, digest) if os.path.isfile(path): return path raise KeyError, digest def getSize(self, digest): return os.path.getsize(self.getPath(digest)) def open(self, digest): return ReadFile(self.getPath(digest)) class ReadFile(object): """A lazy read file implementation""" interface.implements(interfaces.IReadFile) def __init__(self, name, bufsize=-1): self.name = name self.digest = str(os.path.split(self.name)[1]) self.bufsize=bufsize self._v_len = None self._v_file = None @property def _file(self): if not self.closed: return self._v_file self._v_file = file(self.name, 'rb', self.bufsize) return self._v_file @Lazy def ctime(self): return int(os.stat(self.name)[stat.ST_CTIME]) @Lazy def atime(self): return int(os.stat(self.name)[stat.ST_ATIME]) def __len__(self): if self._v_len is None: self._v_len = int(os.stat(self.name)[stat.ST_SIZE]) return self._v_len def __repr__(self): return "<ReadFile named %s>" % repr(self.digest) @property def closed(self): """like file closed, but lazy""" return self._v_file is None or self._v_file.closed def seek(self, offset, whence=0): """see file.seek""" # we optimize when we have 0, 0 then we do not need to open # the file if it is closed, because on the next read we are at # 0 if offset==0 and whence==0 and self.closed: return return self._file.seek(offset, whence) def tell(self): """see file.tell""" if self.closed: return 0 return self._file.tell() def read(self, size=-1): """see file.read""" return self._file.read(size) def close(self): """see file.close""" if not self.closed: self._v_file.close() self._v_file = None def fileno(self): return self._file.fileno() def __iter__(self): return self._file.__iter__() class WriteFile(object): interface.implements(interfaces.IWriteFile) def __init__(self, hd, handle, path): self.hd = hd self.handle = handle self.path = path self.sha = sha.new() self._pos = 0 def write(self, s): self.sha.update(s) os.write(self.handle, s) self._pos += len(s) def commit(self): """returns the sha digest and saves the file""" os.close(self.handle) return self.hd.commit(self) def tell(self): """see file.tell""" return self._pos def abort(self): """abort the write and delete file""" os.close(self.handle) os.unlink(self.path)
z3c.extfile
/z3c.extfile-0.3.0b2.tar.gz/z3c.extfile-0.3.0b2/src/z3c/extfile/hashdir.py
hashdir.py
import time import os import stat from z3c.filetype import api from z3c.filetype.interfaces import filetypes from zope import interface from cStringIO import StringIO import interfaces import re BLOCK_SIZE = 1024*128 def parse_header(s): l = [e.strip() for e in s.split(';')] result_value = l.pop(0).lower() result_d = {} for e in l: try: key, value = e.split('=', 1) except ValueError: continue key = key.strip().lower() value = value.strip() if len(value) >= 2 and value.startswith('"') and value.endswith('"'): value = value[1:-1] result_d[key] = value return result_value, result_d class Processor: def __init__(self, hd, contentInfo=False, allowedTypes=None): self.hd = hd self._incoming = [] self.contentInfo = contentInfo self.allowedTypes = allowedTypes and re.compile(allowedTypes) self._ct = None self._len = None # we use a state pattern where the handle method gets # replaced by the current handle method for this state. self.handle = self.handle_first_boundary def pushInput(self, fp, out, length=None): if length is None and isinstance(fp, file): length = int(os.stat(fp.name)[stat.ST_SIZE]) pos = 0 bufsize = getattr(fp, 'bufsize', BLOCK_SIZE) while pos<length: chunk = min(length-pos, bufsize) pos += chunk s = fp.read(chunk) for line in s.splitlines(True): self.pushInputLine(line,out) def pushInputLine(self, data, out): # collect data self._incoming.append(data) # if we're not at the end of the line, input was broken # somewhere. We return to collect more first. if data[-1] != '\n': return # now use the line in whatever handle method is current if len(self._incoming) == 1: line = data else: line = ''.join(self._incoming) self._incoming = [] self.handle(line, out) def handle_first_boundary(self, line, out): self._boundary = line self._last_boundary = self._boundary.rstrip() + '--\r\n' self.init_headers() self.handle = self.handle_headers out.write(line) def init_headers(self): self._disposition = None self._disposition_options = {} self._content_type = 'text/plain' self._content_type_options = {} def handle_headers(self, line, out): if line in ['\n', '\r\n']: out.write(line) self.init_data(out) return key, value = line.split(':', 1) key = key.lower() if key == "content-disposition": self._disposition, self._disposition_options = parse_header( value) elif key == "content-type": self._content_type, self._content_type_options = parse_header( value) line = line.replace(self._content_type, 'application/x-z3c.extfile-info') out.write(line) def init_data(self, out): self._dt_start = time.time() filename = self._disposition_options.get('filename') # if filename is empty, assume no file is submitted and submit # empty file -- don't handle it if filename is None or not filename: self.handle = self.handle_data return self._f = self.hd.new() self._previous_line = None self.handle = self.handle_file_data def handle_data(self, line, out): out.write(line) if line == self._boundary: self.init_headers() self.handle = self.handle_headers elif line == self._last_boundary: # we should be done self.handle = None # shouldn't be called again def handle_file_data(self, line, out): def _end(): # write last line, but without \r\n self._f.write(self._previous_line[:-2]) size = self._f.tell() digest = self._f.commit() out.write('z3c.extfile.digest:%s' % digest) if self.contentInfo: out.write(':%s:%s' % (self._ct, size)) out.write('\r\n') out.write(line) self._f = None self._dt_start = time.time() if line == self._boundary: _end() self.handle = self.handle_headers elif line == self._last_boundary: _end() self._f = None self._ct = None self.handle = None # shouldn't be called again else: if self._previous_line is not None: self._f.write(self._previous_line) elif self.contentInfo: ct = self._sniffType(line) if self.allowedTypes is not None: if self.allowedTypes.match(ct) is None: self._f.abort() raise interfaces.TypeNotAllowed, repr(ct) self._ct = ct self._previous_line = line def _sniffType(self, sample): f = StringIO(sample) ifaces = api.getInterfacesFor(f) decl = interface.Declaration(ifaces) for iface in decl.flattened(): mt = iface.queryTaggedValue(filetypes.MT) if mt is not None: return mt def _getInfo(self, digest): f = self.hd.open(digest) ifaces = api.getInterfacesFor(f) decl = interface.Declaration(ifaces) for iface in decl.flattened(): mt = iface.queryTaggedValue(filetypes.MT) if mt is not None: break return (mt, int(len(f)))
z3c.extfile
/z3c.extfile-0.3.0b2.tar.gz/z3c.extfile-0.3.0b2/src/z3c/extfile/processor.py
processor.py
from lxml import etree import types import pkg_resources from zc.buildout import easy_install from zope.interface import directlyProvides from z3c.builder.core import project, base from z3c.feature.core import interfaces target_dir = pkg_resources.working_set.find( pkg_resources.Requirement.parse('zc.buildout')).location class FeatureDocBuilder(base.FileBuilder): """A builder to document all applied features of a project.""" def render(self): result = open( base.getTemplatePath('zboiler-doc-header.txt'), 'r').read() for feature in self.getProject().appliedFeatures: title = feature.featureTitle result += "\n\n" + title + "\n" result += "-"*len(title) + "\n" docs = feature.featureDocumentation.strip() result += "\n" + docs + "\n\n" return result def getNode(nodeOrFileOrStr): if isinstance(nodeOrFileOrStr, types.StringTypes): return etree.fromstring(nodeOrFileOrStr) elif hasattr(nodeOrFileOrStr, 'read'): data = nodeOrFileOrStr.read() nodeOrFileOrStr.seek(0) return etree.fromstring(data) elif isinstance(nodeOrFileOrStr, etree._Element): return nodeOrFileOrStr else: raise TypeError("Could not get a lxml.etree.Element " "object from %s" % nodeOrFileOrStr) def getFeatureFactory(featureNode): featureType = featureNode.get('type') egg, entryPoint = featureType.split(':') if egg not in pkg_resources.working_set.by_key: ws = easy_install.install([egg], target_dir, newest=True) distro = ws.find(pkg_resources.Requirement.parse(eggs)) pkg_resources.working_set.add(distro) else: distro = pkg_resources.get_distribution(egg) try: featureFactory = distro.load_entry_point( interfaces.FEATURE_GROUP, entryPoint) except ImportError, e: raise ValueError("Unable to load feature factory for %s:%s because: %s" % (interfaces.FEATURE_GROUP, entryPoint, e)) return featureFactory def getFeaturesDict(node): node = getNode(node) features = {} for featureNode in node.xpath('//feature'): featureFactory = getFeatureFactory(featureNode).fromXMLNode(featureNode) feature = featureFactory.fromXMLNode(featureNode) features[featureNode.get('type')] = feature return features def getFeatures(node): return getFeaturesDict(node).values() def xmlToProject(node): node = getNode(node) name = node.get("name") builder = project.BuildoutProjectBuilder(unicode(name)) from z3c.feature.core import base base.applyFeatures(getFeatures(node), builder) builder.add(FeatureDocBuilder(u'ZBOILER.txt')) return builder def extractData(node, iface, convert=True): node = getNode(node) data = {} for fieldName in iface: matches = node.xpath('./%s'%fieldName.replace('_','-')) match = matches[0] if matches else None if match is not None: if convert: # ignore templated values when converting to actual fields. if match.text == "?": continue # see if this is a composite element representing a list of # items. items = match.xpath('./item') if items: data[fieldName] = [unicode(item.text) for item in items] # otherwise, see if we can parse a value from unicode elif hasattr(iface[fieldName], 'fromUnicode'): data[fieldName] = iface[fieldName].fromUnicode( unicode(match.text)) # oh well, we'll just send back the unicode and hope that's ok elif match.text: data[fieldName] = unicode(match.text) else: data[fieldName] = unicode(match.text) return data
z3c.feature.core
/z3c.feature.core-0.1.1.tar.gz/z3c.feature.core-0.1.1/src/z3c/feature/core/xml.py
xml.py
import datetime import os import zope.interface from zope.interface.interfaces import IInterface import zope.schema from z3c.builder.core.interfaces import troveClassiferVocabulary FEATURE_GROUP = 'z3c.feature' class IFeatureType(IInterface): """An interface that describes a particular type of feature.""" class DuplicateFeatureConflictError(ValueError): def __init__(self, type): self.type = type ValueError.__init__(self, type) class CyclicDependencyError(ValueError): def __init__(self, cycle): self.cycle = cycle ValueError.__init__(self, cycle) class MissingFeatureDependencyError(KeyError): def __init__(self, feature, dependencyName): self.feature = feature self.dependencyName = dependencyName KeyError.__init__(self, dependencyName) def __str__(self): return ('Feature "%s" depends on "%s" but no "%s" ' 'feature was specified') % (self.feature.featureTitle, self.dependencyName, self.dependencyName) class IFeatureSchema(IInterface): """A schema describing the configuration parameters of a feature.""" class IBaseFeatureSchema(zope.interface.Interface): """A trivial feature schema.""" zope.interface.directlyProvides(IBaseFeatureSchema, IFeatureSchema) class IFeature(zope.interface.Interface): """An object representing a possible feature.""" featureTitle = zope.schema.TextLine( title=u"Feature Title", description=u"A user readable title for this feature.") featureDocumentation = zope.schema.Text( title=u"Feature Documentation", description=u"""ReSTructured text documentation on the feature. This should explain what files were modified/created by the feature and what each piece does, with tips on modifying them later. Documentation for all the features are combined into a single README.txt in the project Root. """) featureSingleton = zope.schema.Bool( title=u"Feature Sigelton", description=(u"When set, only one instance of this feature can " u"be applied to the context."), default=True) featureDependencies = zope.schema.Tuple( title=u"Feature Dependencies", description=(u"A list of names of features that this feature " u"depends on."), value_type=zope.schema.ASCIILine()) def update(features=()): """Update the feature. Optionally, all other features that are applied are passed into the method as an argument. """ def applyTo(context): """Apply the given feature to the context.""" def findEntryPoint(): """Returns the egg name and entry point name. If no entry point is found, `(None, None)` is returned. """ def toXML(asString=False, prettyPrint=False): """Returns an etree node object representing the feature in xml. Optional keyword arguments include asString and prettyPrint which if set to true will return an xml string that is pretty printed. """ class IHaveAppliedFeatures(zope.interface.Interface): """A component that keeps track of the features applied to it.""" appliedFeatures = zope.schema.List( title=u'Applied Features', description=u'A list of features that were applied on the builder.') class IProjectTemplateProvider(zope.interface.Interface): """Object that provides a projecte template.""" title = zope.schema.TextLine( title=u"Title", description=u"A title that can be provided to the user.") description = zope.schema.TextLine( title=u"Description", description=u"A description that can be provided to the user.") def getFeatures(): """Returns a dictionary of entrypoint name to features that are part of this template.""" class IFileBasedTemplateProvider(IProjectTemplateProvider): filename = zope.schema.TextLine( title=u"Filename") class IMetaDataFeature(zope.interface.Interface): license = zope.schema.TextLine( title=u'License', default=u'GNU General Public License (GPL)', required=False) version = zope.schema.TextLine( title=u'Version', description=u'An initial version number for the project', default=u'0.1.0', required=False) description = zope.schema.TextLine( title=u'Project Description', description=u'Short Description of the project', required=False) author = zope.schema.TextLine( title=u'Author(s)', description=u'Name of the project author(s)', required=False) author_email = zope.schema.TextLine( title=u'Author Email', description=u'Email address for the project author(s)', required=False) keywords = zope.schema.List( title=u'Keywords', description=u'A list of keywords related to the project, one per line.', value_type=zope.schema.TextLine(), required=False) url = zope.schema.TextLine( title=u'URL', description=(u'The url for the project. Defaults to ' u'http://pypi.python.org/pypi/[project-name]'), required=False) classifiers = zope.schema.Set( title=u"Trove Classifiers", value_type=zope.schema.Choice( vocabulary=troveClassiferVocabulary), required=False) commentHeader = zope.schema.Text( title=u'Comment Header', description=(u'A comment header that should appear at the top of every ' u'python file (like a license header).'), required=False) namespace_packages = zope.schema.List( title=u'Namespace Packages', description=(u'A list of namespace packages that should be created, one ' u'per line (i.e. zope or zc or z3c or collective)'), value_type=zope.schema.TextLine(), required=False) install_requires = zope.schema.List( title=u"Install Requires", description=(u"A list of additional dependencies, one per line " u"(i.e. lxml)"), value_type=zope.schema.TextLine(), required=False) extras_require = zope.schema.Dict( title=u"Extras Require", key_type=zope.schema.TextLine(), value_type=zope.schema.List(value_type=zope.schema.TextLine())) zope.interface.directlyProvides(IMetaDataFeature, IFeatureSchema) class ICommentHeaderZPLFeature(zope.interface.Interface): author = zope.schema.TextLine( title=u'Author(s)', description=u'Name of the project author(s)', required=False) year = zope.schema.Int( title=u"Year", description=u'The copyright year', default=datetime.date.today().year) zope.interface.directlyProvides(ICommentHeaderZPLFeature, IFeatureSchema) class IProprietaryHeaderFeature(zope.interface.Interface): year = zope.schema.Int( title=u"Year", description=u'The copyright year', default=datetime.date.today().year) company = zope.schema.TextLine( title=u'Company', description=u'The name of your company, (i.e. Foo Inc.)') location = zope.schema.TextLine( title=u'Location', description=u'Location of your company (i.e. San Francisco, USA)') zope.interface.directlyProvides(IProprietaryHeaderFeature, IFeatureSchema) class IPythonInterpreterFeature(zope.interface.Interface): executableName = zope.schema.ASCIILine( title=u'Executable', description=(u'The path to the python executable. ' u'(i.e. /opt/python2.6/bin/python or just python)'), default='python') zope.interface.directlyProvides(IPythonInterpreterFeature, IFeatureSchema) class ITestingFeature(zope.interface.Interface): coverageDirectory = zope.schema.TextLine( title=u"Coverage Directory", description=u"Directory where test coverage data should be placed.", default=u"${buildout:directory}/coverage") coverageReportDirectory = zope.schema.TextLine( title=u'Coverage Report Directory', description=u'Directory where coverage reports should be generated', default=u'${buildout:directory}/coverage/report') zope.interface.directlyProvides(ITestingFeature, IFeatureSchema) class IScriptFeature(zope.interface.Interface): scriptName = zope.schema.TextLine( title=u'Script Name', description=(u'The name of the script that will ' u'be made available on the command line. ' u'Defaults to the name of the project.'), required=False) scriptFile = zope.schema.TextLine( title=u'Script File', description=u'The file where the script will be located', default=u"script.py") scriptFunction = zope.schema.TextLine( title=u'Script Function', description=u'The function in the script file that runs the script', default=u"main") zope.interface.directlyProvides(IScriptFeature, IFeatureSchema) class IDocumentationFeature(zope.interface.Interface): layoutTemplatePath = zope.schema.URI( title=u'Layout Template', description=u"URL for a layout template. Leave blank for default", required=False) cssPath = zope.schema.URI( title=u'CSS url', description=(u'URL for a css file that should be used. Leave blank ' u'for default.'), required=False) additionalEggs = zope.schema.List( title=u'Additional Packages', description=(u'Additional packages for which documentation should ' u'be built'), value_type=zope.schema.TextLine(), required=False) zope.interface.directlyProvides(IDocumentationFeature, IFeatureSchema)
z3c.feature.core
/z3c.feature.core-0.1.1.tar.gz/z3c.feature.core-0.1.1/src/z3c/feature/core/interfaces.py
interfaces.py
import zope.interface from zope.schema.fieldproperty import FieldProperty from z3c.builder.core import project, buildout from z3c.builder.core.python import ModuleBuilder, FunctionBuilder from z3c.feature.core import base, interfaces, xml PYTHON_INTERPRETER_DOCUMENTATION = """ The Python Interpreter feature creates an alias to whatever python interpreter you want inside your project's bin/ directory. Furthermore, it adds your project and all its egg dependencies to the python path. After running buildout from your project directory you can start up the interpreter as normal:: $ ./bin/python >>> from myproject import mymodule >>> form a.dependency import something """ SCRIPT_FEATURE_DOCUMENTATION = """ The Command Line Script Feature exposes a python function in your project as a command line script. There are several pieces to this: #. **The script file.** There is a script file located at %(scriptFile)s with a function in it called %(scriptFunction)s. This is what you should modify to make your script actually do something. #. **Setuptools entry point.** When someone installs your project using setuptools, for example with the command:: $ easy_install yourproject any entry points in the console_script group will turn into executable scripts that the end user can just run. This make your project into an application and not just a set of python libraries. The entry point is created by modifying the ``setup.py`` file. Look for the keyword parameter called entry_points. #. ``scripts`` **buildout part.** Finally there is also a part added to buildout.cfg that makes the script defined in the entry point available in the projects bin/ directory. This is only for development purposes. """ class PythonInterpreterFeature(base.BaseFeature): zope.interface.implements(interfaces.IPythonInterpreterFeature) executableName = FieldProperty( interfaces.IPythonInterpreterFeature['executableName']) featureTitle = u'Python Interpreter' featureDocumentation = PYTHON_INTERPRETER_DOCUMENTATION def _applyTo(self, context): pythonPartBuilder = buildout.PartBuilder(u'python') pythonPartBuilder.addValue('recipe', 'zc.recipe.egg') pythonPartBuilder.addValue('interpreter', self.executableName) pythonPartBuilder.addValue('eggs', context.name) context.buildout.add(pythonPartBuilder) class ScriptFeature(base.BaseFeature): zope.interface.implements(interfaces.IScriptFeature) scriptName = FieldProperty(interfaces.IScriptFeature['scriptName']) scriptFile = FieldProperty(interfaces.IScriptFeature['scriptFile']) scriptFunction = FieldProperty(interfaces.IScriptFeature['scriptFunction']) featureTitle = u'Command Line Script' @property def featureDocumentation(self): return SCRIPT_FEATURE_DOCUMENTATION % dict( scriptFunction=self.scriptFunction, scriptFile=self.scriptFile) def _applyTo(self, context): scriptName = self.scriptName or context.name moduleBuilder = ModuleBuilder(self.scriptFile) moduleBuilder.add(FunctionBuilder( self.scriptFunction, kwargs={'args':None}, docstring=('Runs the %s script ' 'from the %s project') % (scriptName, context.name), code='print "Successfully ran the %s script"' % scriptName )) context.package.add(moduleBuilder) context.setup.addEntryPoints( 'console_scripts', ['%s = %s.%s:%s' % (scriptName, context.name, self.scriptFile[:-3], self.scriptFunction)]) scriptsPart = buildout.PartBuilder(u'scripts') scriptsPart.addValue('recipe','zc.recipe.egg:scripts') scriptsPart.addValue('eggs', context.name) scriptsPart.addValue('script', scriptName) context.buildout.add(scriptsPart)
z3c.feature.core
/z3c.feature.core-0.1.1.tar.gz/z3c.feature.core-0.1.1/src/z3c/feature/core/python.py
python.py
import lxml.etree import pkg_resources import zope.interface import zope.schema from zope.schema.fieldproperty import FieldProperty from z3c.feature.core import interfaces, xml MISSING_DOCUMENTATION = """ Sorry, but the authors of the \"%s\" feature are big meanies who don't like to make software accessible.""" class BaseFeature(object): zope.interface.implements( interfaces.IFeature, interfaces.IBaseFeatureSchema) featureSingleton = FieldProperty(interfaces.IFeature['featureSingleton']) featureDependencies = () @property def featureTitle(self): """See ``z3c.feature.core.interfaces.IFeature``""" return self.__class__.__name__ @property def featureDocumentation(self): """See ``z3c.feature.core.interfaces.IFeature``""" return MISSING_DOCUMENTATION % self.featureTitle @classmethod def fromXMLNode(cls, node, omit=()): feature = cls() schema = getFeatureSchema(feature) data = xml.extractData(node, schema) for fieldName in schema: if fieldName in omit: continue value = data.get(fieldName) if value: setattr(feature, fieldName, value) return feature @classmethod def fromXML(cls, xml): tree = lxml.etree.fromstring(xml) return cls.fromXMLNode(tree) def findEntryPoint(self): set = pkg_resources.working_set for entryPoint in set.iter_entry_points(interfaces.FEATURE_GROUP): if entryPoint.load() == self.__class__: return entryPoint.dist.project_name, entryPoint.name return None, None def toXML(self, asString=False, prettyPrint=False): feature = lxml.etree.Element('feature') egg, name = self.findEntryPoint() feature.set('type', egg + ':' + name if egg and name else 'unknown') schema = getFeatureSchema(self) for fieldName in zope.schema.getFields(schema): if fieldName in interfaces.IFeature: continue value = getattr(self, fieldName) if value != schema[fieldName].default: featureOption = lxml.etree.SubElement(feature, fieldName) if isinstance(value, (list, tuple, set)): for item in value: itemElem = lxml.etree.SubElement(featureOption, 'item') itemElem.text = str(item) else: featureOption.text = str(value) if asString: return lxml.etree.tostring(feature, pretty_print=prettyPrint) return feature def update(self, features=None): """See ``z3c.feature.core.interfaces.IFeature``""" def _applyTo(self, context): pass def applyTo(self, context): """See ``z3c.feature.core.interfaces.IFeature``""" if interfaces.IHaveAppliedFeatures.providedBy(context): context.appliedFeatures.append(self) self._applyTo(context) def __repr__(self): return "<%s %r>" % (self.__class__.__name__, self.featureTitle) def getFeatureSchema(feature): if isinstance(feature, type): ifaces = zope.interface.implementedBy(feature).flattened() else: ifaces = zope.interface.providedBy(feature).flattened() for iface in ifaces: if interfaces.IFeatureSchema.providedBy(iface): return iface return None def getFeatureTypes(feature): return [iface for iface in zope.interface.providedBy(feature).flattened() if interfaces.IFeatureType.providedBy(iface)] def resolveDependencies(features, resolution=None, seen=None, types=None, all=None): # List of all features. if all is None: all = features # List of all feature types that have been found on singletons. if types is None: types = [] # List of features that have been resolved in the correct order. if resolution is None: resolution = [] # A list of seen features for a particular dependency sub-path. if seen is None: seen = [] # Loop through all features and resolve them. for name, feature in features.items(): # If the feature is a singleton record its types. if feature.featureSingleton: for type in getFeatureTypes(feature): if type in types: raise interfaces.DuplicateFeatureConflictError(type) types.append(type) # If a feature is already resolved, skip the feature. if feature in resolution: continue # If we have seen the feature already, we have a cycle. if feature in seen: raise interfaces.CyclicDependencyError(seen[seen.index(feature):]) # If we do not have a cycle, add the feature to the list of seen ones seen.append(feature) # Resolve the dependencies of all children. if feature.featureDependencies: try: deps = dict( [(name, all[name]) for name in feature.featureDependencies]) except KeyError: raise interfaces.MissingFeatureDependencyError(feature, name) resolveDependencies(deps, resolution, seen, types, all) # Add the feature to the resolution. if feature not in resolution: resolution.append(feature) # Remove the feature from the current dependency path. seen.pop() return resolution def applyFeatures(features, project): """Apply a list of features to the project.""" # Make sure the project collects all applied features zope.interface.directlyProvides(project, interfaces.IHaveAppliedFeatures) project.appliedFeatures = [] # Apply features one by one. featureDict = dict( [(feature.findEntryPoint()[1] or 'unknwon-%i' %idx, feature) for idx, feature in enumerate(features)]) for feature in resolveDependencies(featureDict): feature.update(featureDict) feature.applyTo(project) class FileBasedTemplateBase(object): _filename = None def getFeatures(self): if self._filename is None: raise ValueError("Missing filename attribute.") return xml.getFeatures(open(self._filename)) def FileBasedTemplate(filename, title, description): FileBasedTemplate = type( '<FileBasedTemplate for %s' % filename, (FileBasedTemplateBase,), dict(title=title, description=description, _filename=filename)) zope.interface.classImplements( FileBasedTemplate, interfaces.IProjectTemplateProvider) return FileBasedTemplate
z3c.feature.core
/z3c.feature.core-0.1.1.tar.gz/z3c.feature.core-0.1.1/src/z3c/feature/core/base.py
base.py
=============== Boiler Features =============== This package provides high-level components to build a project. The intend is that a user can select a set of features that make up a project and the system figures out how to create a coherent project from that set of features. - `base.txt` This document provides a tutorial about how to write features based on the base feature provided by this package. - `metadata.txt` This file explains the metadata feature, which is used to create the package's setup information. - `python.txt` This file documents the basic Python features provided by the module. - `unittest.txt` This document provides detailed documentation obout the testing feature. - `xml.txt` This document describes how XML is converted into features and then applied to a project. - `example.txt` A quick example of producing a project from XML feature descriptions.
z3c.feature.core
/z3c.feature.core-0.1.1.tar.gz/z3c.feature.core-0.1.1/src/z3c/feature/core/README.txt
README.txt
import os import types import zope.interface from zope.schema.fieldproperty import FieldProperty from z3c.builder.core import project, buildout from z3c.builder.core.base import getTemplatePath, FileBuilder from z3c.builder.core.interfaces import IFileBuilder from z3c.feature.core import base, interfaces, xml METADATA_FEATURE_DOCUMENTATION = """ The Metadata feature sets up the setup.py file which is what setuptools uses to generate distributable python eggs. """ COMMENT_HEADER_ZPL_DOCUMENTATION = """ The Zope Public License file header looks something like this:: %(header)s """ PROPRIETARY_HEADER_DOCUMENTATION = """ The proprietary header looks something like this:: %(header)s """ DOCUMENTATION_FEATURE_DOCUMENTATION = """ The ReSTructured Text Documentation feature hooks up scripts for generating html (or latex for that matter) documentation from ReSTructured text files using Sphinx. There are a few pieces involved in this hookup: #. ``buildout.cfg`` **part section** This looks something like:: [docs] recipe = z3c.recipe.sphinxdoc eggs = yourproject [docs] z3c.recipe.sphinxdoc default.css = layout.html = This buildout part section will generate a script in the bin directory called ``docs`` which you can run liket his:: $ ./bin/docs Documentation will be put into the ``parts/docs/`` directory, with one directory for each package specified in the eggs parameter of the docs section. See the documentation for z3c.recipe.sphinxdoc for more information. It can be found at http://pypi.python.org/pypi/z3c.recipe.sphinxdoc #. ``setup.py extras_require`` **section** For the docs to build correctly, there must be a ``docs`` section in ``extras_require`` that pulls in the Sphinx dependencies. #. ``index.txt`` **file in project src** An ``index.txt`` file will be added to the src directory. This serves as the root document used by Sphinx to generate all the documentation. See the Sphinx documentation for what sort of things you can put in here at http://sphinx.pocoo.org/ """ class MetaDataFeature(base.BaseFeature): zope.interface.implements(interfaces.IMetaDataFeature) version = FieldProperty(interfaces.IMetaDataFeature['version']) license = FieldProperty(interfaces.IMetaDataFeature['license']) url = FieldProperty(interfaces.IMetaDataFeature['url']) classifiers = FieldProperty(interfaces.IMetaDataFeature['classifiers']) keywords = FieldProperty(interfaces.IMetaDataFeature['keywords']) author = FieldProperty(interfaces.IMetaDataFeature['author']) author_email = FieldProperty(interfaces.IMetaDataFeature['author_email']) description = FieldProperty(interfaces.IMetaDataFeature['description']) commentHeader = FieldProperty(interfaces.IMetaDataFeature['commentHeader']) namespace_packages = FieldProperty( interfaces.IMetaDataFeature['namespace_packages']) install_requires = FieldProperty( interfaces.IMetaDataFeature['install_requires']) extras_require = FieldProperty(interfaces.IMetaDataFeature['extras_require']) featureTitle = u'Metadata' featureDocumentation = METADATA_FEATURE_DOCUMENTATION @classmethod def fromXMLNode(cls, node, omit=()): feature = super(MetaDataFeature, cls).fromXMLNode( node, omit=('classifiers', 'extras_require')) schema = base.getFeatureSchema(feature) data = xml.extractData(node, schema) classifiers = data.get('classifiers') feature.classifiers = set() if classifiers: feature.classifiers = [c.strip() for c in classifiers.split('\n')] return feature def _applyTo(self, context): """See ``z3c.feature.core.interfaces.IFeature``""" # Assign all meta data to setup. for name in ('version', 'license', 'url', 'keywords', 'author', 'author_email', 'description', 'namespace_packages', 'install_requires','extras_require'): value = getattr(self, name) if value is not None: setattr(context.setup, name, value) # Set the comment header. if self.commentHeader is not None: context.commentHeader = self.commentHeader class CommentHeaderZPLFeature(base.BaseFeature): zope.interface.implements(interfaces.ICommentHeaderZPLFeature) _template = unicode(open(getTemplatePath('zpl-header.py')).read()) year = FieldProperty(interfaces.ICommentHeaderZPLFeature['year']) author = FieldProperty(interfaces.ICommentHeaderZPLFeature['author']) featureTitle = u'ZPL Header' @property def featureDocumentation(self): """See ``z3c.feature.core.interfaces.IFeature``""" header = ' ' + self.renderCommentHeader().replace('\n', '\n ') return COMMENT_HEADER_ZPL_DOCUMENTATION % {'header':header} def renderCommentHeader(self): return self._template % dict(year=self.year, author=self.author) def _applyTo(self, context): """See ``z3c.feature.core.interfaces.IFeature``""" context.commentHeader = self.renderCommentHeader() class ProprietaryHeaderFeature(base.BaseFeature): zope.interface.implements(interfaces.IProprietaryHeaderFeature) _template = unicode(open(getTemplatePath('proprietary-header.py')).read()) year = FieldProperty(interfaces.IProprietaryHeaderFeature['year']) company = FieldProperty(interfaces.IProprietaryHeaderFeature['company']) location = FieldProperty(interfaces.IProprietaryHeaderFeature['location']) featureTitle = u'Proprietary Header' @property def featureDocumentation(self): """See ``z3c.feature.core.interfaces.IFeature``""" header = ' ' + self.renderCommentHeader().replace('\n', '\n ') return PROPRIETARY_HEADER_DOCUMENTATION % {'header':header} def renderCommentHeader(self): return self._template % dict(year=self.year, company=self.company, location=self.location) def _applyTo(self, context): """See ``z3c.feature.core.interfaces.IFeature``""" context.commentHeader = self.renderCommentHeader() class DocumentationFileBuilder(FileBuilder): template = os.path.join( os.path.dirname(__file__), 'file-templates', 'index-template.txt') def update(self): project = self.getProject() self.title = project.name + ' Documentation' self.TOC = [] for builder in self.__parent__.values(): if (IFileBuilder.providedBy(builder) and builder.filename.endswith('.txt') and builder is not self): self.TOC.append(builder.filename[:-4]) def render(self): heading = '%(border)s\n%(title)s\n%(border)s' % dict( border='='*len(self.title), title=self.title) TOC = '\n '.join(self.TOC) return open(self.template).read() % dict(heading=heading, TOC=TOC) class DocumentationFeature(base.BaseFeature): zope.interface.implements(interfaces.IDocumentationFeature) layoutTemplatePath = FieldProperty( interfaces.IDocumentationFeature['layoutTemplatePath']) cssPath = FieldProperty( interfaces.IDocumentationFeature['cssPath']) additionalEggs = FieldProperty( interfaces.IDocumentationFeature['additionalEggs']) featureTitle = u'Restructured Text Documentation' featureDocumentation = DOCUMENTATION_FEATURE_DOCUMENTATION def _applyTo(self, context): """See ``z3c.feature.core.interfaces.IFeature``""" docsPart = buildout.PartBuilder(u'docs') docsPart.addValue('recipe', 'z3c.recipe.sphinxdoc') eggs = [context.name+' [docs]'] + (self.additionalEggs or []) eggsString = 'z3c.recipe.sphinxdoc' for egg in eggs: eggsString += '\n '+egg docsPart.addValue('eggs', eggsString) docsPart.addValue('layout.html', self.layoutTemplatePath or '') docsPart.addValue('default.css', self.cssPath or '') context.buildout.add(docsPart) context.setup.addExtrasRequires('docs', ['Sphinx']) indexBuilder = DocumentationFileBuilder(u'index.txt') context.package.add(indexBuilder)
z3c.feature.core
/z3c.feature.core-0.1.1.tar.gz/z3c.feature.core-0.1.1/src/z3c/feature/core/metadata.py
metadata.py
import zope.schema from zope.schema.vocabulary import SimpleVocabulary from zope.schema.vocabulary import SimpleTerm from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile from z3c.form.form import EditForm from z3c.form.field import Fields from z3c.form.browser.textlines import TextLinesFieldWidget from z3c.feature.core.metadata import MetaDataFeature from z3c.feature.core.metadata import CommentHeaderZPLFeature from z3c.feature.core.metadata import ProprietaryHeaderFeature from z3c.feature.core.metadata import DocumentationFeature from z3c.feature.core.python import PythonInterpreterFeature from z3c.feature.core import interfaces licenseVocabulary = SimpleVocabulary([ SimpleTerm('Aladdin Free Public License (AFPL)'), SimpleTerm('DFSG approved'), SimpleTerm('Eiffel Forum License (EFL)'), SimpleTerm('Free For Educational Use'), SimpleTerm('Free For Home Use'), SimpleTerm('Free for non-commercial use'), SimpleTerm('Freely Distributable'), SimpleTerm('Free To Use But Restricted'), SimpleTerm('Freeware'), SimpleTerm('Netscape Public License (NPL)'), SimpleTerm('Nokia Open Source License (NOKOS)'), SimpleTerm('Academic Free License (AFL)'), SimpleTerm('Apache Software License'), SimpleTerm('Apple Public Source License'), SimpleTerm('Artistic License'), SimpleTerm('Attribution Assurance License'), SimpleTerm('BSD License'), SimpleTerm('Common Public License'), SimpleTerm('Eiffel Forum License'), SimpleTerm('GNU Affero General Public License v3'), SimpleTerm('GNU Free Documentation License (FDL)'), SimpleTerm('GNU General Public License (GPL)'), SimpleTerm('GNU Library or Lesser General Public License (LGPL)'), SimpleTerm('IBM Public License'), SimpleTerm('Intel Open Source License'), SimpleTerm('Jabber Open Source License'), SimpleTerm('MIT License'), SimpleTerm('MITRE Collaborative Virtual Workspace License (CVW)'), SimpleTerm('Motosoto License'), SimpleTerm('Mozilla Public License 1.0 (MPL)'), SimpleTerm('Mozilla Public License 1.1 (MPL 1.1)'), SimpleTerm('Nethack General Public License'), SimpleTerm('Nokia Open Source License'), SimpleTerm('Open Group Test Suite License'), SimpleTerm('Python License (CNRI Python License)'), SimpleTerm('Python Software Foundation License'), SimpleTerm('Qt Public License (QPL)'), SimpleTerm('Ricoh Source Code Public License'), SimpleTerm('Sleepycat License'), SimpleTerm('Sun Industry Standards Source License (SISSL)'), SimpleTerm('Sun Public License'), SimpleTerm('University of Illinois/NCSA Open Source License'), SimpleTerm('Vovida Software License 1.0'), SimpleTerm('W3C License'), SimpleTerm('X.Net License'), SimpleTerm('zlib/libpng License'), SimpleTerm('Zope Public License'), SimpleTerm('Other/Proprietary License'), SimpleTerm('Public Domain'), ]) class MetaDataWebView(EditForm): label = u'Project Metadata' template = ViewPageTemplateFile('templates/metadata.pt') javascript = ViewPageTemplateFile('templates/metadata.js') fields = Fields(zope.schema.Choice( __name__='commonLicense', title=u'License', default=u'GNU General Public License (GPL)', vocabulary=licenseVocabulary, required=False)) fields += Fields(interfaces.IMetaDataFeature).select( 'license','version','description','author', 'author_email','url','classifiers','keywords', 'namespace_packages','install_requires', 'commentHeader') fields = fields.select( 'license','commonLicense','version','description','author', 'author_email','url','classifiers','keywords', 'namespace_packages','install_requires', 'commentHeader') fields['keywords'].widgetFactory = TextLinesFieldWidget fields['namespace_packages'].widgetFactory = TextLinesFieldWidget fields['install_requires'].widgetFactory = TextLinesFieldWidget def applyChanges(self, data): commonLicense = data.pop('commonLicense') data['license'] = data.get('license', commonLicense) return super(MetaDataWebView, self).applyChanges(data) class MetaDataWebFeature(object): viewFactory = MetaDataWebView contentFactory = MetaDataFeature title = u"Metadata" description = (u"Let's you modify project metadata used by setuptools " u"such as version number, license information, author " u"information, project description, and more.") class CommentHeaderZPLWebView(EditForm): label = u'Comment Header for the Zope Public License' fields = Fields(interfaces.ICommentHeaderZPLFeature).select('year') class CommentHeaderZPLWebFeature(object): viewFactory = CommentHeaderZPLWebView contentFactory = CommentHeaderZPLFeature title = u"ZPL Header" description = u"Adds a ZPL Header to all generated files." class ProprietaryHeaderWebView(EditForm): template = ViewPageTemplateFile("templates/proprietary-header.pt") fields = Fields(interfaces.IProprietaryHeaderFeature).select( 'year','company','location') def update(self): super(ProprietaryHeaderWebView, self).update() self.commentHeader = self.context.renderCommentHeader() class ProprietaryHeaderWebFeature(object): viewFactory = ProprietaryHeaderWebView contentFactory = ProprietaryHeaderFeature title = u"Proprietary Header" description = u"Adds a Proprietary Software Header to all generated files." class DocumentationWebView(EditForm): label = u'Documentation' fields = Fields(interfaces.IDocumentationFeature) class DocumentationWebFeature(object): viewFactory = DocumentationWebView contentFactory = DocumentationFeature title = u"Documentation" description = (u"Adds a script for generating project documentation from " u"ReSTructured Text files using Sphinx (just like the python " u"documetation). Great in combination with the " u"Automated Tests Feature")
z3c.feature.core
/z3c.feature.core-0.1.1.tar.gz/z3c.feature.core-0.1.1/src/z3c/feature/core/web/metadata.py
metadata.py
import os import zope.interface from zope.schema.fieldproperty import FieldProperty from z3c.builder.core import project, zcml, python, form from z3c.feature.core import base, xml from z3c.feature.zope import interfaces CONTENT_DOCUMENTATION = """ The Zope Content Feature lets you define a basic content type that can be stored in a database and that has a simple page for creating, reading, updating, and deleting the content item. """ class ZopeContentFeature(base.BaseFeature): zope.interface.implements(interfaces.IZopeContentFeature) featureDocumentation = CONTENT_DOCUMENTATION featureSingleton = False featureDependencies = ('zope-project','zope-skin') className = FieldProperty(interfaces.IZopeContentFeature['className']) classFile = FieldProperty(interfaces.IZopeContentFeature['classFile']) fields = FieldProperty(interfaces.IZopeContentFeature['fields']) @property def featureTitle(self): return u'Zope Content Type (%s)' % self.className def __init__(self): self.fields = {} def addField(self, name, schemaType): constraint = interfaces.IZopeContentFeature['fields'] constraint.key_type.validate(name) constraint.value_type.validate(schemaType) self.fields[name] = schemaType def update(self, features=()): if not self.classFile: self.classFile = self.className.lower()+'.py' @classmethod def fromXMLNode(cls, node, omit=()): feature = cls() schema = base.getFeatureSchema(feature) for fieldName in ('className','classFile'): matches = node.xpath('./%s'%fieldName) match = matches[0] if matches else None if match is not None: setattr(feature, fieldName, unicode(match.text)) for field in node.xpath('./fields/field'): feature.addField(unicode(field.get('name')), unicode(field.get('type'))) return feature def _applyTo(self, project): # Step 1: build the interface ifaces = project.package['interfaces.py'] iface = python.InterfaceBuilder(u'I%s' % self.className) iface.docstring = str("The ``%s`` Content Type" % self.className) ifaces.add(iface) for fieldName, fieldType in self.fields.items(): iface.add(python.FieldBuilder( name=fieldName, type=str(fieldType), title=fieldName.capitalize())) # Step 2: build the implementation if self.classFile not in project.package.keys(): project.package.add(python.ModuleBuilder(self.classFile)) module = project.package[self.classFile] classDefinition = python.ClassFromInterfaceBuilder( name=self.className, interface=iface, bases = ('persistent.Persistent', 'zope.container.contained.Contained')) module.add(classDefinition) # Step 3: build the configuration if 'configure' not in project.package.keys(): project.package.add(zcml.ZCMLFileBuilder(u'configure.zcml')) configure = project.package['configure'] classDirective = zcml.ZCMLDirectiveBuilder( namespace=zcml.ZOPE_NS, name='class', attributes={'class':classDefinition.getPythonPath()}) configure.add(classDirective) classDirective.add(zcml.ZCMLDirectiveBuilder( namespace=None, name='allow', attributes={'interface':iface.getPythonPath()})) classDirective.add(zcml.ZCMLDirectiveBuilder( namespace=None, name='require', attributes={'permission':'zope.Public', 'set_schema':iface.getPythonPath()})) browser = project.package['browser'] # Step 4: make sure the browser package has configuration in it. if 'configure' not in browser.keys(): browser.add(zcml.ZCMLFileBuilder(u'configure.zcml')) configure.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'include', attributes={'package':browser.getPythonPath()})) browserConfig = browser['configure'] # Step 5: create the form module. if 'z3c.form' not in project.setup.install_requires: project.setup.install_requires.append('z3c.form') project.package['appConfig'].add( zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'include', attributes={'package':'z3c.form','file':'meta.zcml'}) ) project.package['appConfig'].add( zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'include', attributes={'package':'z3c.form'}) ) layerIface = project.package['interfaces.py']['ILayer'] skinIface = project.package['interfaces.py']['ISkin'] if 'z3c.form.interfaces.IFormLayer' not in skinIface.bases: skinIface.bases.append('z3c.form.interfaces.IFormLayer') formModule = python.ModuleBuilder(self.classFile) browser.add(formModule) # Step 5.1: create the add form and register it addForm = form.AddFormBuilder( name=u'%sAddForm' % self.className, #TODO: make add form builder accept an interface builder. interface=str(iface.getPythonPath()), fields=iface.keys(), factory=str(classDefinition.getPythonPath()), next='index.html') formModule.add(addForm) browserConfig.add(zcml.ZCMLDirectiveBuilder( namespace=zcml.BROWSER_NS, name=u'page', attributes = { 'name': 'index.html', 'for': 'zope.app.folder.interfaces.IFolder', #TODO: make add forms support a getPythonPath method... 'class': '%s.%s'%(formModule.getPythonPath(), addForm.name), 'permission': 'zope.Public', 'layer':layerIface.getPythonPath()})) # Step 5.2 create the edit form and register it. editForm = form.EditFormBuilder( name=u'%sEditForm' % self.className, interface=str(iface.getPythonPath()), fields=iface.keys()) formModule.add(editForm) browserConfig.add(zcml.ZCMLDirectiveBuilder( namespace=zcml.BROWSER_NS, name=u'page', attributes = { 'name': 'edit.html', 'for': str(iface.getPythonPath()), #TODO: make add forms support a getPythonPath method... 'class': '%s.%s'%(formModule.getPythonPath(), editForm.name), 'permission': 'zope.Public', 'layer':layerIface.getPythonPath()})) # Step 5.3 create the display form and register it. displayForm = form.SimpleDisplayFormBuilder( name=u'%sDisplayForm' % self.className, interface=str(iface.getPythonPath()), fields=iface.keys()) formModule.add(displayForm) browserConfig.add(zcml.ZCMLDirectiveBuilder( namespace=zcml.BROWSER_NS, name=u'page', attributes = { 'name': 'index.html', 'for': str(iface.getPythonPath()), #TODO: make add forms support a getPythonPath method... 'class': '%s.%s'%(formModule.getPythonPath(), displayForm.name), 'permission': 'zope.Public', 'layer':layerIface.getPythonPath()}))
z3c.feature.zope
/z3c.feature.zope-0.1.0.tar.gz/z3c.feature.zope-0.1.0/src/z3c/feature/zope/content.py
content.py
import zope.interface import zope.schema from zope.schema.vocabulary import SimpleVocabulary from zope.schema.vocabulary import SimpleTerm from z3c.feature.core.interfaces import IFeatureSchema FieldsVocabulary = SimpleVocabulary( [SimpleTerm('zope.schema.TextLine', u'Text Line', u'Text Line'), SimpleTerm('zope.schema.Text', u'Text', u'Text'), SimpleTerm('zope.schema.Int', u'Integer', u'Integer'), SimpleTerm('zope.schema.Float', u'Float', u'Float'), ]) class IZopeProjectFeature(zope.interface.Interface): """A feature converting a project to a Zope project.""" zope.interface.directlyProvides(IZopeProjectFeature, IFeatureSchema) class IZopePageFeature(zope.interface.Interface): """A feature to produce a simple page.""" name = zope.schema.TextLine( title=u'Name', description=(u'The name by which the page can be accessed in a url ' u'i.e. index.html'), default=u'index.html') templateName = zope.schema.TextLine( title=u'Template Name', description=(u'The name of the template for the page. ' u'Defaults to the name of the page.'), required=False) zope.interface.directlyProvides(IZopePageFeature, IFeatureSchema) class IZopeContentFeature(zope.interface.Interface): """A feature to produce a Content Object with CRUD pages.""" className = zope.schema.TextLine( title=u'Class Name', description=u'The name of the class to create. i.e. MyContent', default=u'MyContent') classFile = zope.schema.TextLine( title=u'Class File', description=(u'The file in which to put the class. i.e. mycontent.py. ' u'Defaults to the lowercased version of the class name'), required=False) fields = zope.schema.Dict( title=u'Fields', description=u'The fields for this object', key_type=zope.schema.TextLine( title=u'Name', description=u'The name of the field'), value_type=zope.schema.Choice( title=u'Type', description=u"The field's type.", vocabulary=FieldsVocabulary) ) zope.interface.directlyProvides(IZopeContentFeature, IFeatureSchema) class IZopeSkinFeature(zope.interface.Interface): """A feature to produce a Skin with a layer.""" zope.interface.directlyProvides(IZopeSkinFeature, IFeatureSchema)
z3c.feature.zope
/z3c.feature.zope-0.1.0.tar.gz/z3c.feature.zope-0.1.0/src/z3c/feature/zope/interfaces.py
interfaces.py
========================= Zope-Related Web Features ========================= This page contains features that are specific to Zope projects. Zope Project Feature -------------------- The Zope project feature converts a project from a simple Buildout project to a full Zope server installation. >>> from z3c.feature.zope import project >>> zprj = project.ZopeProjectFeature() >>> zprj <ZopeProjectFeature u'Zope Project'> Clearly, the Zope Project Feature implements its own interface: >>> from zope.interface.verify import verifyObject >>> from z3c.feature.zope import interfaces >>> verifyObject(interfaces.IZopeProjectFeature, zprj) True Each feature must provide a title and some documentation: >>> print zprj.featureTitle Zope Project >>> print zprj.featureDocumentation This feature extends a buildout project to a Zope project. Let's now create a project to which we can apply the feature. >>> from z3c.builder.core.project import BuildoutProjectBuilder >>> demo = BuildoutProjectBuilder(u'demo') >>> zprj.applyTo(demo) The easiest way to see what the feature added is by rendering the project itself. >>> demo.update() >>> demo.write(buildPath) >>> ls(buildPath) demo/ bootstrap.py buildout.cfg setup.py src/ demo/ __init__.py application.zcml configure.zcml browser/ __init__.py configure.zcml You immediately notice that there are several files: - `browser/` - This is a placeholder sub-package for all browser-related code. It contains a placeholder configuration file. >>> more(buildPath, 'demo', 'src', 'demo', 'browser', 'configure.zcml') <configure i18n_domain="demo" /> - `application.zcml` - This file contains all the necessary includes to make the Zope 3 application run. >>> more(buildPath, 'demo', 'src', 'demo', 'application.zcml') <configure xmlns:zope="http://namespaces.zope.org/zope" xmlns:browser="http://namespaces.zope.org/browser" i18n_domain="demo" > <zope:include package="zope.app.component" file="meta.zcml" /> ... <browser:menu title="Views" id="zmi_views" /> <browser:menu title="Actions" id="zmi_actions" /> <zope:include package="zope.app.appsetup" /> ... <browser:defaultView name="index.html" /> <zope:securityPolicy component="zope.securitypolicy.zopepolicy.ZopeSecurityPolicy" /> <zope:role title="Everybody" id="zope.Anonymous" /> <zope:grantAll role="zope.Anonymous" /> </configure> - `configure.zcml` - This is a simple placeholder configuration file for future use. >>> more(buildPath, 'demo', 'src', 'demo', 'configure.zcml') <configure xmlns:zope="http://namespaces.zope.org/zope" i18n_domain="demo" > <zope:include package=".browser" /> </configure> Clearly with so many references to other packages, the setup file must also list dependencies. >>> more(buildPath, 'demo', 'setup.py') ############################################################################## # # This file is part of demo... # ############################################################################## """Setup""" from setuptools import setup, find_packages <BLANKLINE> setup ( name = 'demo', version = '0.1.0', author = u"", author_email = u"", description = u"", license = "GPLv3", keywords = u"", url = "http://pypi.python.org/pypi/demo", classifiers = [], packages = find_packages('src'), include_package_data = True, package_dir = {'':'src'}, namespace_packages = [], extras_require = {}, install_requires = [ 'setuptools', 'zdaemon', ... ], zip_safe = False, entry_points = {}, ) Also, the buildout configuration file contain multiple new sections that setup the application server >>> more(buildPath, 'demo', 'buildout.cfg') [buildout] extends = http://download.zope.org/zope3.4/3.4.0/versions.cfg develop = . parts = demo-app demo versions = versions <BLANKLINE> [zope3] location = . <BLANKLINE> [demo-app] recipe = zc.zope3recipes:app site.zcml = <include package="demo" file="application.zcml" /> eggs = demo <BLANKLINE> [demo] recipe = zc.zope3recipes:instance application = demo-app zope.conf = ${database:zconfig} eggs = demo <BLANKLINE> [database] recipe = zc.recipe.filestorage Zope Browser Layer Feature -------------------------- Not yet done. Zope Page Feature ----------------- This feature installs a simple page. It provides a few options that alter the outcome of the generation. >>> from z3c.feature.zope import browser >>> page = browser.ZopePageFeature() >>> page <ZopePageFeature u'Zope Page (index.html)'> Clearly, the feature implements its own interface: >>> verifyObject(interfaces.IZopePageFeature, page) True Each feature must provide a title and some documentation: >>> print page.featureTitle Zope Page (index.html) >>> print page.featureDocumentation The Zope Page Feature creates a simple Zope 3 style page. This particular feature has some additional fields that can be customized. >>> print page.name index.html >>> print page.templateName None If we change the page name, the feature title changes as well. >>> page.name = u"page.html" >>> print page.featureTitle Zope Page (page.html) Now that we have the page setup, let's apply it to the project and render the project again. >>> page.update() >>> page.applyTo(demo) >>> demo.update() >>> demo.write(buildPath, True) >>> ls(buildPath) demo/ bootstrap.py buildout.cfg setup.py src/ demo/ __init__.py application.zcml configure.zcml browser/ __init__.py configure.zcml page.pt The page template is the simplest HTML page possible: >>> more(buildPath, 'demo', 'src', 'demo', 'browser', 'page.pt') <html> <head> <title>Simple Page</title> </head> <body> <h1>Simple Page</h1> </body> </html> The configuration file also registers the page: >>> more(buildPath, 'demo', 'src', 'demo', 'browser', 'configure.zcml') <configure xmlns:browser="http://namespaces.zope.org/browser" i18n_domain="demo" > <browser:page template="page.pt" for="*" name="page.html" permission="zope.Public" /> </configure> Pretty simple. Bulding the Project ------------------- Before we can build the project, we need to install the Python interpreter feature and re-render the project. >>> from z3c.feature.core import python >>> interpreter = python.PythonInterpreterFeature() >>> interpreter.applyTo(demo) >>> demo.update() >>> demo.write(buildPath, True) Let's now build the project to see whether it all works. >>> import sys >>> projectDir = buildPath + '/demo' >>> print cmd((sys.executable, 'bootstrap.py'), projectDir) Exit Status: 0... Downloading http://pypi.python.org/packages/2.5/s/setuptools/setuptools-... Creating directory '.../demo/bin'. Creating directory '.../demo/parts'. Creating directory '.../demo/develop-eggs'. Generated script '.../demo/bin/buildout'. >>> print cmd(('./bin/buildout', '-N'), projectDir) Exit Status: 0 Develop: '.../demo/.' Installing demo-app. Generated script '.../demo/parts/demo-app/runzope'. Generated script '.../demo/parts/demo-app/debugzope'. Installing database. Installing demo. Generated script '.../demo/bin/demo'. Installing python. Generated interpreter '.../demo/bin/python'. Let's now load the configuration to check that we have a fully functioning package. >>> testCode = ''' ... import zope.app.twisted.main ... from zc.zope3recipes import debugzope ... options = debugzope.load_options( ... ('-C', '%(dir)s/parts/demo/zope.conf',), ... zope.app.twisted.main) ... folder = debugzope.zglobals(options.configroot)['root'] ... ... import zope.component ... from zope.publisher.browser import TestRequest ... page = zope.component.getMultiAdapter( ... (folder, TestRequest()), name='page.html') ... print page() ... ''' % {'dir': projectDir} >>> print cmd(('./bin/python', '-c', testCode), projectDir) Exit Status: 0 <html> <head> <title>Simple Page</title> </head> <body> <h1>Simple Page</h1> </body> </html>
z3c.feature.zope
/z3c.feature.zope-0.1.0.tar.gz/z3c.feature.zope-0.1.0/src/z3c/feature/zope/README.txt
README.txt
import zope.interface from z3c.builder.core import buildout, python, zcml from z3c.feature.core import base from z3c.feature.zope import interfaces PROJECT_DOCUMENTATION = u''' This feature extends a buildout project to a Zope project. ''' class ZopeProjectFeature(base.BaseFeature): zope.interface.implements(interfaces.IZopeProjectFeature) featureTitle = u'Zope Project' featureDocumentation = PROJECT_DOCUMENTATION def _applyTo(self, project): # Create application ZCML. appConfig = zcml.ZCMLFileBuilder(u'application.zcml') project.package['appConfig'] = appConfig for name in ('zope.app.component', 'zope.app.component.browser', 'zope.app.pagetemplate', 'zope.app.publication', 'zope.app.publisher', 'zope.app.security', 'zope.app.securitypolicy', 'zc.configuration', 'z3c.form', 'z3c.template', 'z3c.pagelet', 'z3c.macro', 'zope.viewlet', ): id = appConfig.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'include', attributes = { 'package': name, 'file': 'meta.zcml'} )) for package, filename in ( ('zope.app.securitypolicy.browser', 'configure.zcml'), ('zope.app.session', 'browser.zcml'), ('zope.app.folder.browser', 'configure.zcml'), ): id = appConfig.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'exclude', attributes = {'package': package, 'file': filename} )) appConfig.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.BROWSER_NS, name = 'menu', attributes = { 'id': 'zmi_views', 'title': 'Views'} )) appConfig.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.BROWSER_NS, name = 'menu', attributes = { 'id': 'zmi_actions', 'title': 'Actions'} )) for name in ('zope.app.appsetup', 'zope.app.component', 'zope.app.container', 'zope.app.error', 'zope.app.i18n', 'zope.app.publication', 'zope.app.security', 'zope.app.securitypolicy', 'zope.app.session', 'zope.app.twisted', 'zope.app.wsgi', 'zope.annotation', 'zope.component', 'zope.container', 'zope.location', 'zope.publisher', 'zope.traversing', 'zope.traversing.browser', 'zope.app.folder', 'z3c.macro', 'z3c.form', 'z3c.formui', 'z3c.pagelet', 'z3c.layer.pagelet', ): id = appConfig.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'include', attributes = {'package': name} )) appConfig.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'include', attributes = {'package': project.name} )) appConfig.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.BROWSER_NS, name = 'defaultView', attributes = { 'name': 'index.html'} )) appConfig.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'securityPolicy', attributes = { 'component': 'zope.securitypolicy.zopepolicy.ZopeSecurityPolicy'} )) appConfig.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'role', attributes = { 'id': 'zope.Anonymous', 'title': 'Everybody'} )) appConfig.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'grantAll', attributes = { 'role': 'zope.Anonymous'} )) # Create `browser` package. project.package.add(python.PackageBuilder(u'browser')) project.package['browser'].add(zcml.ZCMLFileBuilder(u'configure.zcml')) # Create package configuration file. config = zcml.ZCMLFileBuilder(u'configure.zcml') config.add(zcml.ZCMLDirectiveBuilder( namespace = zcml.ZOPE_NS, name = 'include', attributes = { 'package': '.browser'} )) project.package.add(config) if 'versions' not in project.buildout.keys(): project.buildout.add(buildout.PartBuilder( u'versions', autoBuild=False )) for version in (('zc.configuration','1.0'), ('z3c.layer.pagelet','1.0.1')): project.buildout['versions'].addValue(*version) # Create buildout parts. project.buildout.add(buildout.PartBuilder( u'zope3', [('location', '.')], autoBuild=False )) project.buildout.add(buildout.PartBuilder( u'%s-app' %project.name, [('recipe', 'zc.zope3recipes:app'), ('site.zcml', '<include package="%s" file="application.zcml" />' %project.name), ('eggs', project.name)] )) project.buildout.add(buildout.PartBuilder( project.name, [('recipe', 'zc.zope3recipes:instance'), ('application', '%s-app' %project.name), ('zope.conf', '${database:zconfig}'), ('eggs', project.name)] )) project.buildout.add(buildout.PartBuilder( u'database', [('recipe', 'zc.recipe.filestorage')], autoBuild=False )) # Add dependencies. project.setup.install_requires += [ 'zdaemon', 'zc.configuration', 'zc.zope3recipes', 'zope.app.securitypolicy', 'zope.app.container', 'zope.app.session', 'zope.app.twisted', 'zope.container', 'z3c.formui', 'z3c.pagelet', 'z3c.layer.pagelet', ]
z3c.feature.zope
/z3c.feature.zope-0.1.0.tar.gz/z3c.feature.zope-0.1.0/src/z3c/feature/zope/project.py
project.py
import os import zope.interface from zope.schema.fieldproperty import FieldProperty from z3c.builder.core import project, zcml, python, form from z3c.feature.core import base, xml from z3c.feature.zope import interfaces SKIN_DOCUMENTATION = """ The Zope Skin Feature lets you define a basic skin along with a layer that can inherit from other layers. """ class ZopeSkinFeature(base.BaseFeature): zope.interface.implements(interfaces.IZopeSkinFeature) featureDocumentation = SKIN_DOCUMENTATION featureSingleton = True featureDependencies = ('zope-project',) @property def featureTitle(self): return u'Zope Skin' def _applyTo(self, project): if 'interfaces.py' not in project.package.keys(): project.package.add(python.ModuleBuilder(u'interfaces.py')) ifaces = project.package['interfaces.py'] # Step 1: define a layer layerIface = python.InterfaceBuilder(u'ILayer') layerIface.docstring = str("Browser Layer for %s" % project.name) layerIface.bases = ['zope.publisher.interfaces.browser.IBrowserRequest'] ifaces.add(layerIface) # Step 2: define a skin skinIface = python.InterfaceBuilder(u'ISkin') skinIface.docstring = str("Browser Skin for %s" % project.name) skinIface.bases = ['z3c.form.interfaces.IFormLayer', 'z3c.formui.interfaces.IDivFormLayer', 'z3c.layer.pagelet.IPageletBrowserLayer', layerIface.getPythonPath()] ifaces.add(skinIface) configure = project.package['configure'] # Step 3: register the skin skinDirective = zcml.ZCMLDirectiveBuilder( namespace=zcml.ZOPE_NS, name='interface', attributes={'interface':skinIface.getPythonPath(), 'type':'zope.publisher.interfaces.browser.IBrowserSkinType', 'name':project.name}) configure.add(skinDirective) # Step 4: make it the default skin appConfig = project.package['appConfig'] appConfig.add(zcml.ZCMLDirectiveBuilder( namespace=zcml.BROWSER_NS, name='defaultSkin', attributes={'name':project.name}))
z3c.feature.zope
/z3c.feature.zope-0.1.0.tar.gz/z3c.feature.zope-0.1.0/src/z3c/feature/zope/skin.py
skin.py
import zope.i18nmessageid from zope.size.interfaces import ISized from zope.size import byteDisplay from interfaces import filetypes from zope import component, interface import os import stat import struct _ = zope.i18nmessageid.MessageFactory("zope") class ImageFileSized(object): interface.implements(ISized) def __init__(self, image): self._image = image @property def bytes(self): try: return len(self._image.data) except TypeError: data = self._image.data return int(os.fstat(data.fileno())[stat.ST_SIZE]) raise NotImplementedError def sizeForSorting(self): '''See `ISized`''' return ('byte', self.bytes) def getImageSize(self): raise NotImplementedError def sizeForDisplay(self): '''See `ISized`''' w, h = self.getImageSize() if w < 0: w = '?' if h < 0: h = '?' byte_size = byteDisplay(self.bytes) mapping = byte_size.mapping if mapping is None: mapping = {} mapping.update({'width': str(w), 'height': str(h)}) #TODO the way this message id is defined, it won't be picked up by # i18nextract and never show up in message catalogs return _(byte_size + ' ${width}x${height}', mapping=mapping) class GIFFileSized(ImageFileSized): interface.implements(ISized) component.adapts(filetypes.IGIFFile) def getImageSize(self): data = self._image.data data.seek(0) data = data.read(24) size = len(data) width = -1 height = -1 if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'): # Check to see if content_type is correct w, h = struct.unpack("<HH", data[6:10]) width = int(w) height = int(h) return width, height class PNGFileSized(ImageFileSized): interface.implements(ISized) component.adapts(filetypes.IPNGFile) def getImageSize(self): data = self._image.data data.seek(0) data = data.read(24) size = len(data) height = -1 width = -1 # See PNG 2. Edition spec (http://www.w3.org/TR/PNG/) # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR' # and finally the 4-byte width, height if ((size >= 24) and data.startswith('\211PNG\r\n\032\n') and (data[12:16] == 'IHDR')): w, h = struct.unpack(">LL", data[16:24]) width = int(w) height = int(h) # Maybe this is for an older PNG version. elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'): w, h = struct.unpack(">LL", data[8:16]) width = int(w) height = int(h) return width, height class JPGFileSized(ImageFileSized): interface.implements(ISized) component.adapts(filetypes.IJPGFile) def getImageSize(self): data = self._image.data data.seek(2) size = self.bytes height = -1 width = -1 b = data.read(1) try: w = -1 h = -1 while (b and ord(b) != 0xDA): while (ord(b) != 0xFF): b = data.read(1) while (ord(b) == 0xFF): b = data.read(1) if (ord(b) >= 0xC0 and ord(b) <= 0xC3): data.read(3) h, w = struct.unpack(">HH", data.read(4)) break else: data.read(int(struct.unpack(">H", data.read(2))[0])-2) b = data.read(1) width = int(w) height = int(h) except struct.error: pass except ValueError: pass return width, height
z3c.filetype
/z3c.filetype-1.2.1.tar.gz/z3c.filetype-1.2.1/src/z3c/filetype/size.py
size.py
================ Filetype Package ================ :ATTENTION: This package is not ready yet! see TODO.txt This package provides a way to get interfaces that are provided based on their content, filename or mime-type. >>> from z3c.filetype import api We take some files for demonstration from the testdata directory. >>> import os >>> testData = os.path.join(os.path.dirname(api.__file__),'testdata') >>> fileNames = sorted(os.listdir(testData)) >>> for name in fileNames: ... if name==".svn": continue ... path = os.path.join(testData, name) ... i = api.getInterfacesFor(file(path, 'rb'), filename=name) ... print name ... print sorted(i) DS_Store [<InterfaceClass z3c.filetype.interfaces.filetypes.IBinaryFile>] IMG_0504.JPG [<InterfaceClass z3c.filetype.interfaces.filetypes.IJPGFile>] excel.xls [<InterfaceClass z3c.filetype.interfaces.filetypes.IMSWordFile>] faces_gray.avi [<InterfaceClass z3c.filetype.interfaces.filetypes.IAVIFile>] ftyp.mov [<InterfaceClass z3c.filetype.interfaces.filetypes.IQuickTimeFile>] ipod.mp4 [<InterfaceClass z3c.filetype.interfaces.filetypes.IMP4File>] jumps.mov [<InterfaceClass z3c.filetype.interfaces.filetypes.IQuickTimeFile>] logo.gif [<InterfaceClass z3c.filetype.interfaces.filetypes.IGIFFile>] logo.gif.bz2 [<InterfaceClass z3c.filetype.interfaces.filetypes.IBZIP2File>] mpeglayer3.mp3 [<InterfaceClass z3c.filetype.interfaces.filetypes.IAudioMPEGFile>] noface.bmp [<InterfaceClass z3c.filetype.interfaces.filetypes.IBMPFile>] portable.pdf [<InterfaceClass z3c.filetype.interfaces.filetypes.IPDFFile>] powerpoingt.ppt [<InterfaceClass z3c.filetype.interfaces.filetypes.IMSWordFile>] test.flv [<InterfaceClass z3c.filetype.interfaces.filetypes.IFLVFile>] test.gnutar [<InterfaceClass z3c.filetype.interfaces.filetypes.ITARFile>] test.html [<InterfaceClass z3c.filetype.interfaces.filetypes.IHTMLFile>] test.png [<InterfaceClass z3c.filetype.interfaces.filetypes.IPNGFile>] test.tar [<InterfaceClass z3c.filetype.interfaces.filetypes.ITARFile>] test.tgz [<InterfaceClass z3c.filetype.interfaces.filetypes.IGZIPFile>] test.txt.gz [<InterfaceClass z3c.filetype.interfaces.filetypes.IGZIPFile>] test2.html [<InterfaceClass z3c.filetype.interfaces.filetypes.IHTMLFile>] test2.thml [<InterfaceClass z3c.filetype.interfaces.filetypes.IHTMLFile>] thumbnailImage_small.jpeg [<InterfaceClass z3c.filetype.interfaces.filetypes.IJPGFile>] word.doc [<InterfaceClass z3c.filetype.interfaces.filetypes.IMSWordFile>] It is not possible to reliably detect Microsoft Office files from file data. The only way right now is to use the filename. >>> for name in fileNames: ... if name==".svn": continue ... i = api.getInterfacesFor(filename=name) ... print name ... print sorted(i) DS_Store [<InterfaceClass z3c.filetype.interfaces.filetypes.IBinaryFile>] ... excel.xls [<InterfaceClass z3c.filetype.interfaces.filetypes.IMSExcelFile>] ... powerpoingt.ppt [<InterfaceClass z3c.filetype.interfaces.filetypes.IMSPowerpointFile>] ... word.doc [<InterfaceClass z3c.filetype.interfaces.filetypes.IMSWordFile>] WMA files are alway detected as video/x-ms-asf. The only way is to use the file extension. To be able to detect WMA file this package adds its own mime.types file to the python mimetypes module. >>> import mimetypes >>> mimetypes.knownfiles [... '.../z3c.filetype/src/z3c/filetype/mime.types'... >>> sorted(api.getInterfacesFor(filename='test.wma')) [<InterfaceClass z3c.filetype.interfaces.filetypes.IWMAFile>] The filename is only used if no interface is found, because we should not trust the filename in most cases. >>> f = open(os.path.join(testData, 'test.tar')) >>> sorted(api.getInterfacesFor(f)) [<InterfaceClass z3c.filetype.interfaces.filetypes.ITARFile>] >>> sorted(api.getInterfacesFor(filename="x.png")) [<InterfaceClass z3c.filetype.interfaces.filetypes.IPNGFile>] >>> sorted(api.getInterfacesFor(f, filename="x.png")) [<InterfaceClass z3c.filetype.interfaces.filetypes.ITARFile>] If a mimeType is given then the interfaces derived from it is added to the result, regardless if the content of the file tells something different. >>> sorted(api.getInterfacesFor(f, mimeType="text/plain")) [<InterfaceClass z3c.filetype.interfaces.filetypes.ITARFile>, <InterfaceClass z3c.filetype.interfaces.filetypes.ITextFile>] You can also provide a path instead of a stream. >>> f.name '...test.tar' >>> sorted(api.getInterfacesFor(f.name)) [<InterfaceClass z3c.filetype.interfaces.filetypes.ITARFile>] Applying filetype interfaces to objects via events ================================================== There are event handlers which apply filetype interfaces to an object. This object needs to implement ITypeableFile. So let us setup the event handling. >>> from zope.component import eventtesting >>> eventtesting.setUp() >>> from z3c.filetype import interfaces >>> from zope import interface >>> class Foo(object): ... interface.implements(interfaces.ITypeableFile) ... def __init__(self, f): ... self.data = f >>> foo = Foo(f) There is also an event handler registered for IObjectCreatedEvent and IObjectModified on ITypeableFile. We register them here in the test. >>> from zope import component >>> component.provideHandler(api.handleCreated) >>> component.provideHandler(api.handleModified) So we need to fire an IObjectCreatedEvent. Which is normally done by a factory. >>> from zope.lifecycleevent import ObjectCreatedEvent >>> from zope.lifecycleevent import ObjectModifiedEvent >>> from zope.event import notify >>> eventtesting.clearEvents() >>> notify(ObjectCreatedEvent(foo)) >>> sorted(eventtesting.getEvents()) [<z3c.filetype.event.FileTypeModifiedEvent object at ...>, <zope.app.event.objectevent.ObjectCreatedEvent object at ...>] The object now implements the according interface. This is achieved by the evennthandler which calls applyInterfaces. >>> sorted((interface.directlyProvidedBy(foo))) [<InterfaceClass z3c.filetype.interfaces.filetypes.ITARFile>] A second applyInteraces does nothing. >>> eventtesting.clearEvents() >>> api.applyInterfaces(foo) False >>> eventtesting.getEvents() [] If we change the object the interface changes too. We need to fire an IObjectModifiedevent. Which is normally done by the implementation. >>> foo.data = file(os.path.join(testData,'test.flv'), 'rb') >>> eventtesting.clearEvents() >>> >>> notify(ObjectModifiedEvent(foo)) Now we have two events, one we fired and one from our handler. >>> eventtesting.getEvents() [<zope.app.event.objectevent.ObjectModifiedEvent object at ...>, <z3c.filetype.event.FileTypeModifiedEvent object at ...>] Now the file should implement another filetype. >>> sorted((interface.directlyProvidedBy(foo))) [<InterfaceClass z3c.filetype.interfaces.filetypes.IFLVFile>] IFileType adapters ================== There is also an adapter from ITypedFile to IFileType, which can be used to get the default content type for the interface. >>> from z3c.filetype import adapters >>> component.provideAdapter(adapters.TypedFileType) >>> for name in fileNames: ... if name==".svn": continue ... path = os.path.join(testData, name) ... i = Foo(file(path, 'rb')) ... notify(ObjectModifiedEvent(i)) ... print name + " --> " + interfaces.IFileType(i).contentType DS_Store --> application/octet-stream IMG_0504.JPG --> image/jpeg excel.xls --> application/msword faces_gray.avi --> video/x-msvideo ftyp.mov --> video/quicktime ipod.mp4 --> video/mp4 jumps.mov --> video/quicktime logo.gif --> image/gif logo.gif.bz2 --> application/x-bzip2 mpeglayer3.mp3 --> audio/mpeg noface.bmp --> image/bmp portable.pdf --> application/pdf powerpoingt.ppt --> application/msword test.flv --> video/x-flv test.gnutar --> application/x-tar test.html --> text/html test.png --> image/png test.tar --> application/x-tar test.tgz --> application/x-gzip test.txt.gz --> application/x-gzip test2.html --> text/html test2.thml --> text/html thumbnailImage_small.jpeg --> image/jpeg word.doc --> application/msword Size adapters ============= There are adapters registered for ISized for IPNGFile, IJPEGFile and IGIFFile. >>> from z3c.filetype import size >>> from zope.size.interfaces import ISized >>> component.provideAdapter(size.GIFFileSized) >>> component.provideAdapter(size.PNGFileSized) >>> component.provideAdapter(size.JPGFileSized) >>> foo.data = file(os.path.join(testData,'thumbnailImage_small.jpeg'), 'rb') >>> notify(ObjectModifiedEvent(foo)) >>> ISized(foo).sizeForDisplay().mapping {'width': '120', 'height': '90', 'size': '3'} >>> foo.data = file(os.path.join(testData,'test.png'), 'rb') >>> notify(ObjectModifiedEvent(foo)) >>> ISized(foo).sizeForDisplay().mapping {'width': '279', 'height': '19', 'size': '4'} >>> foo.data = file(os.path.join(testData,'logo.gif'), 'rb') >>> notify(ObjectModifiedEvent(foo)) >>> ISized(foo).sizeForDisplay().mapping {'width': '201', 'height': '54', 'size': '2'} >>> foo.data = file(os.path.join(testData,'IMG_0504.JPG'), 'rb') >>> notify(ObjectModifiedEvent(foo)) >>> ISized(foo).sizeForDisplay().mapping {'width': '1600', 'height': '1200', 'size': '499'}
z3c.filetype
/z3c.filetype-1.2.1.tar.gz/z3c.filetype-1.2.1/src/z3c/filetype/README.txt
README.txt
import os.path from z3c.filetype import magic import interfaces from interfaces import filetypes from zope.contenttype import guess_content_type, add_files from zope import interface, component from zope.lifecycleevent.interfaces import IObjectModifiedEvent from zope.lifecycleevent.interfaces import IObjectCreatedEvent from zope.event import notify from event import FileTypeModifiedEvent magicFile = magic.MagicFile() def byMimeType(t): """returns interfaces implemented by mimeType""" ifaces = [iface for name, iface in vars(filetypes).items() \ if name.startswith("I")] res = InterfaceSet() for iface in ifaces: mtm = iface.queryTaggedValue(filetypes.MTM) if mtm is not None: if mtm.match(t): res.add(iface) return res def getInterfacesFor(file=None, filename=None, mimeType=None): """returns a sequence of interfaces that are provided by file like objects (file argument) with an optional filename as name or mimeType as mime-type """ ifaces = set() if file is not None: types = magicFile.detect(file) for t in types: ifaces.update(byMimeType(t)) if mimeType is not None: ifaces.update(byMimeType(mimeType)) if filename is not None and not ifaces: t = guess_content_type(filename)[0] # dont trust this here because zope does not recognize some # binary files. if t and not t == 'text/x-unknown-content-type': ifaces.update(byMimeType(t)) if not ifaces: ifaces.add(interfaces.filetypes.IBinaryFile) return InterfaceSet(*ifaces) def applyInterfaces(obj): assert(interfaces.ITypeableFile.providedBy(obj)) ifaces = InterfaceSet(*getInterfacesFor(obj.data)) provided = set(interface.directlyProvidedBy(obj)) for iface in provided: if not issubclass(iface, interfaces.filetypes.ITypedFile): ifaces.add(iface) if set(ifaces)!=provided: from zope.proxy import removeAllProxies obj = removeAllProxies(obj) for iface in ifaces: interface.directlyProvides(obj, iface) notify(FileTypeModifiedEvent(obj)) return True return False class InterfaceSet(object): """a set that only holds most specific interfaces >>> s = InterfaceSet(filetypes.IBinaryFile, filetypes.IImageFile) >>> sorted(s) [<InterfaceClass z3c.filetype.interfaces.filetypes.IBinaryFile>, <InterfaceClass z3c.filetype.interfaces.filetypes.IImageFile>] Now we add a jpeg file which is a subclass of all ifaces in the set >>> s.add(filetypes.IJPGFile) >>> sorted(s) [<InterfaceClass z3c.filetype.interfaces.filetypes.IJPGFile>] If we add a new which is not a subclass it is contained >>> s.add(filetypes.ITextFile) >>> sorted(s) [<InterfaceClass z3c.filetype.interfaces.filetypes.IJPGFile>, <InterfaceClass z3c.filetype.interfaces.filetypes.ITextFile>] """ def __init__(self, *ifaces): self._data = set() for iface in ifaces: self.add(iface) def add(self, iface): assert(issubclass(iface, interface.Interface)) toDelete = set() for i in self._data: if issubclass(i,iface): return if issubclass(iface, i): toDelete.add(i) self._data.add(iface) self._data.difference_update(toDelete) def __iter__(self): return iter(self._data) @component.adapter(interfaces.ITypeableFile,IObjectModifiedEvent) def handleModified(typeableFile, event): """handles modification of data""" if interfaces.IFileTypeModifiedEvent.providedBy(event): # do nothing if this is already a filetype modification event return applyInterfaces(typeableFile) @component.adapter(interfaces.ITypeableFile,IObjectCreatedEvent) def handleCreated(typeableFile, event): """handles modification of data""" applyInterfaces(typeableFile) # add our mimetypes definitions to pythons mimetypes module here = os.path.dirname(os.path.abspath(__file__)) add_files([os.path.join(here, "mime.types")])
z3c.filetype
/z3c.filetype-1.2.1.tar.gz/z3c.filetype-1.2.1/src/z3c/filetype/api.py
api.py
import sys, struct, time, re, exceptions, pprint, stat, os _mew = 0 _magic = os.path.join(os.path.dirname(__file__),'magic.mime') mime = 1 _ldate_adjust = lambda x: time.mktime( time.gmtime(x) ) BUFFER_SIZE = 1024 * 128 # 128K should be enough... class MagicError(exceptions.Exception): pass def _handle(fmt='@x',adj=None): return fmt, struct.calcsize(fmt), adj KnownTypes = { 'byte':_handle('@b'), 'byte':_handle('@B'), 'ubyte':_handle('@B'), 'string':('s',0,None), 'pstring':_handle('p'), 'short':_handle('@h'), 'beshort':_handle('>h'), 'leshort':_handle('<h'), 'short':_handle('@H'), 'beshort':_handle('>H'), 'leshort':_handle('<H'), 'ushort':_handle('@H'), 'ubeshort':_handle('>H'), 'uleshort':_handle('<H'), 'long':_handle('@l'), 'belong':_handle('>l'), 'lelong':_handle('<l'), 'ulong':_handle('@L'), 'ubelong':_handle('>L'), 'ulelong':_handle('<L'), 'date':_handle('=l'), 'bedate':_handle('>l'), 'ledate':_handle('<l'), 'ldate':_handle('=l',_ldate_adjust), 'beldate':_handle('>l',_ldate_adjust), 'leldate':_handle('<l',_ldate_adjust), } _mew_cnt = 0 def mew(x): global _mew_cnt if _mew : if x=='.' : _mew_cnt += 1 if _mew_cnt % 64 == 0 : sys.stderr.write( '\n' ) sys.stderr.write( '.' ) else: sys.stderr.write( '\b'+x ) def has_format(s): n = 0 l = None for c in s : if c == '%' : if l == '%' : n -= 1 else : n += 1 l = c return n def read_asciiz(file,size=None,pos=None): s = [] if pos : mew('s') file.seek( pos, 0 ) mew('z') if size is not None : s = [file.read( size ).split('\0')[0]] else: while 1 : c = file.read(1) if (not c) or (ord(c)==0) or (c=='\n') : break s.append (c) mew('Z') return ''.join(s) def a2i(v,base=0): if v[-1:] in 'lL' : v = v[:-1] return int( v, base ) _cmap = { '\\' : '\\', '0' : '\0', } for c in range(ord('a'),ord('z')+1) : try : e = eval('"\\%c"' % chr(c)) except ValueError : pass else : _cmap[chr(c)] = e else: del c del e def make_string(s): # hack, is this the right way? s = s.replace('\\<','<') s = s.replace('\\ ',' ') return eval( '"'+s.replace('"','\\"')+'"') class MagicTestError(MagicError): pass class MagicTest: def __init__(self,offset,mtype,test,message,line=None,level=None): self.line, self.level = line, level self.mtype = mtype self.mtest = test self.subtests = [] self.mask = None self.smod = None self.nmod = None self.offset, self.type, self.test, self.message = \ offset,mtype,test,message if self.mtype == 'true' : return # XXX hack to enable level skips if test[-1:]=='\\' and test[-2:]!='\\\\' : self.test += 'n' # looks like someone wanted EOL to match? if mtype[:6]=='string' : if '/' in mtype : # for strings self.type, self.smod = \ mtype[:mtype.find('/')], mtype[mtype.find('/')+1:] else: for nm in '&+-' : if nm in mtype : # for integer-based self.nmod, self.type, self.mask = ( nm, mtype[:mtype.find(nm)], # convert mask to int, autodetect base int( mtype[mtype.find(nm)+1:], 0 ) ) break self.struct, self.size, self.cast = KnownTypes[ self.type ] def __str__(self): return '%s %s %s %s' % ( self.offset, self.mtype, self.mtest, self.message ) def __repr__(self): return 'MagicTest(%s,%s,%s,%s,line=%s,level=%s,subtests=\n%s%s)' % ( `self.offset`, `self.mtype`, `self.mtest`, `self.message`, `self.line`, `self.level`, '\t'*self.level, pprint.pformat(self.subtests) ) def run(self,file): result = '' do_close = 0 try: if type(file) == type('x') : file = open( file, 'r', BUFFER_SIZE ) do_close = 1 # else: # saved_pos = file.tell() if self.mtype != 'true' : data = self.read(file) try: last = file.tell() except Exception, e: # TODO: check what's happen here, I run into this on # windows guessing a content type for flv files. ri pass else: data = last = None if self.check( data ) : result = self.message+' ' if has_format( result ) : result %= data for test in self.subtests : m = test.run(file) if m is not None : result += m return make_string( result ) finally: if do_close : file.close() # else: # file.seek( saved_pos, 0 ) def get_mod_and_value(self): if self.type[-6:] == 'string' : # if 'ustar' in self.test: # import pdb;pdb.set_trace() # "something like\tthis\n" if self.test[0] in '=<>' : mod, value = self.test[0], make_string( self.test[1:] ) else: mod, value = '=', make_string( self.test ) else: if self.test[0] in '=<>&^' : mod, value = self.test[0], a2i(self.test[1:]) elif self.test[0] == 'x': mod = self.test[0] value = 0 else: mod, value = '=', a2i(self.test) return mod, value def read(self,file): mew( 's' ) file.seek( self.offset(file), 0 ) # SEEK_SET mew( 'r' ) try: data = rdata = None # XXX self.size might be 0 here... if self.size == 0 : # this is an ASCIIZ string... size = None if self.test != '>\\0' : # magic's hack for string read... value = self.get_mod_and_value()[1] size = (value=='\0') and None or len(value) rdata = data = read_asciiz( file, size=size ) else: rdata = file.read( self.size ) if not rdata or (len(rdata)!=self.size) : return None data = struct.unpack( self.struct, rdata )[0] # XXX hack?? except: print >>sys.stderr, self print >>sys.stderr, '@%s struct=%s size=%d rdata=%s' % ( self.offset, `self.struct`, self.size,`rdata`) raise mew( 'R' ) if self.cast : data = self.cast( data ) if self.mask : try: if self.nmod == '&' : data &= self.mask elif self.nmod == '+' : data += self.mask elif self.nmod == '-' : data -= self.mask else: raise MagicTestError(self.nmod) except: print >>sys.stderr,'data=%s nmod=%s mask=%s' % ( `data`, `self.nmod`, `self.mask` ) raise return data def check(self,data): mew('.') if self.mtype == 'true' : return '' # not None ! mod, value = self.get_mod_and_value() if self.type[-6:] == 'string' : # "something like\tthis\n" if self.smod: #import pdb;pdb.set_trace() xdata = data if 'b' in self.smod : # all blanks are optional xdata = ''.join( data.split() ) value = ''.join( value.split() ) if 'c' in self.smod : # all blanks are optional xdata = xdata.upper() value = value.upper() if 'B' in self.smod : # compact blanks data = ' '.join( data.split() ) if ' ' not in data : return None else: xdata = data try: if mod == '=' : result = data == value elif mod == '<' : result = data < value elif mod == '>' : result = data > value elif mod == '&' : result = data & value elif mod == '^' : result = (data & (~value)) == 0 elif mod == 'x' : result = 1 else : raise MagicTestError(self.test) if result : zdata, zval = `data`, `value` if self.mtype[-6:]!='string' : try: zdata, zval = hex(data), hex(value) except: zdata, zval = `data`, `value` if 0 : print >>sys.stderr, '%s @%s %s:%s %s %s => %s (%s)' % ( '>'*self.level, self.offset, zdata, self.mtype, `mod`, zval, `result`, self.message ) return result except: print >>sys.stderr,'mtype=%s data=%s mod=%s value=%s' % ( `self.mtype`, `data`, `mod`, `value` ) raise def add(self,mt): if not isinstance(mt,MagicTest) : raise MagicTestError((mt,'incorrect subtest type %s'%(type(mt),))) if mt.level == self.level+1 : self.subtests.append( mt ) elif self.subtests : self.subtests[-1].add( mt ) elif mt.level > self.level+1 : # it's possible to get level 3 just after level 1 !!! :-( level = self.level + 1 while level < mt.level : xmt = MagicTest(None,'true','x','',line=self.line,level=level) self.add( xmt ) level += 1 else: self.add( mt ) # retry... else: raise MagicTestError((mt,'incorrect subtest level %s'%(`mt.level`,))) def last_test(self): return self.subtests[-1] #end class MagicTest class OffsetError(MagicError): pass class Offset: pos_format = {'b':'<B','B':'>B','s':'<H','S':'>H','l':'<I','L':'>I',} pattern0 = re.compile(r''' # mere offset ^ &? # possible ampersand ( 0 # just zero | [1-9]{1,1}[0-9]* # decimal | 0[0-7]+ # octal | 0x[0-9a-f]+ # hex ) $ ''', re.X|re.I ) pattern1 = re.compile(r''' # indirect offset ^\( (?P<base>&?0 # just zero |&?[1-9]{1,1}[0-9]* # decimal |&?0[0-7]* # octal |&?0x[0-9A-F]+ # hex ) (?P<type> \. # this dot might be alone [BSL]? # one of this chars in either case )? (?P<sign> [-+]{0,1} )? (?P<off>0 # just zero |[1-9]{1,1}[0-9]* # decimal |0[0-7]* # octal |0x[0-9a-f]+ # hex )? \)$''', re.X|re.I ) def __init__(self,s): self.source = s self.value = None self.relative = 0 self.base = self.type = self.sign = self.offs = None m = Offset.pattern0.match( s ) if m : # just a number if s[0] == '&' : self.relative, self.value = 1, int( s[1:], 0 ) else: self.value = int( s, 0 ) return m = Offset.pattern1.match( s ) if m : # real indirect offset try: self.base = m.group('base') if self.base[0] == '&' : self.relative, self.base = 1, int( self.base[1:], 0 ) else: self.base = int( self.base, 0 ) if m.group('type') : self.type = m.group('type')[1:] self.sign = m.group('sign') if m.group('off') : self.offs = int( m.group('off'), 0 ) if self.sign == '-' : self.offs = 0 - self.offs except: print >>sys.stderr, '$$', m.groupdict() raise return raise OffsetError(`s`) def __call__(self,file=None): if self.value is not None : return self.value pos = file.tell() try: if not self.relative : file.seek( self.offset, 0 ) frmt = Offset.pos_format.get( self.type, 'I' ) size = struct.calcsize( frmt ) data = struct.unpack( frmt, file.read( size ) ) if self.offs : data += self.offs return data finally: file.seek( pos, 0 ) def __str__(self): return self.source def __repr__(self): return 'Offset(%s)' % `self.source` #end class Offset class MagicFileError(MagicError): pass class MagicFile: def __init__(self,filename=_magic): self.file = None self.tests = [] self.total_tests = 0 self.load( filename ) self.ack_tests = None self.nak_tests = None def __del__(self): self.close() def load(self,filename=None): self.open( filename ) self.parse() self.close() def open(self,filename=None): self.close() if filename is not None : self.filename = filename self.file = open( self.filename, 'r', BUFFER_SIZE ) def close(self): if self.file : self.file.close() self.file = None def parse(self): line_no = 0 for line in self.file.xreadlines() : line_no += 1 if not line or line[0]=='#' : continue line = line.lstrip().rstrip('\r\n') if not line or line[0]=='#' : continue try: x = self.parse_line( line ) if x is None : print >>sys.stderr, '#[%04d]#'%line_no, line continue except: print >>sys.stderr, '###[%04d]###'%line_no, line raise self.total_tests += 1 level, offset, mtype, test, message = x new_test = MagicTest(offset,mtype,test,message, line=line_no,level=level) try: if level == 0 : self.tests.append( new_test ) else: self.tests[-1].add( new_test ) except: if 1 : print >>sys.stderr, 'total tests=%s' % ( `self.total_tests`, ) print >>sys.stderr, 'level=%s' % ( `level`, ) print >>sys.stderr, 'tests=%s' % ( pprint.pformat(self.tests), ) raise else: while self.tests[-1].level > 0 : self.tests.pop() def parse_line(self,line): # print >>sys.stderr, 'line=[%s]' % line if (not line) or line[0]=='#' : return None level = 0 offset = mtype = test = message = '' mask = None # get optional level (count leading '>') while line and line[0]=='>' : line, level = line[1:], level+1 # get offset while line and not line[0].isspace() : offset, line = offset+line[0], line[1:] try: offset = Offset(offset) except: print >>sys.stderr, 'line=[%s]' % line raise # skip spaces line = line.lstrip() # get type c = None while line : last_c, c, line = c, line[0], line[1:] if last_c!='\\' and c.isspace() : break # unescaped space - end of field else: mtype += c if last_c == '\\' : c = None # don't fuck my brain with sequential backslashes # skip spaces line = line.lstrip() # get test c = None while line : last_c, c, line = c, line[0], line[1:] if last_c!='\\' and c.isspace() : break # unescaped space - end of field else: test += c if last_c == '\\' : c = None # don't fuck my brain with sequential backslashes # skip spaces line = line.lstrip() # get message message = line if mime and line.find("\t") != -1: message=line[0:line.find("\t")] # # print '>>', level, offset, mtype, test, message return level, offset, mtype, test, message def detect(self,file): self.ack_tests = 0 self.nak_tests = 0 answers = set() for test in self.tests : message = test.run( file ) if message and message.strip(): self.ack_tests += 1 answers.add( message.strip().split()[0] ) else: self.nak_tests += 1 return answers #end class MagicFile def username(uid): try: import pwd return pwd.getpwuid( uid )[0] except: return '#%s'%uid def groupname(gid): try: import grp return grp.getgrgid( gid )[0] except: return '#%s'%gid def get_file_type(fname,follow): t = None if not follow : try: st = os.lstat( fname ) # stat that entry, don't follow links! except os.error, why : pass else: if stat.S_ISLNK(st[stat.ST_MODE]) : t = 'symbolic link' try: lnk = os.readlink( fname ) except: t += ' (unreadable)' else: t += ' to '+lnk if t is None : try: st = os.stat( fname ) except os.error, why : return "can't stat `%s' (%s)." % (why.filename,why.strerror) dmaj, dmin = (st.st_rdev>>8)&0x0FF, st.st_rdev&0x0FF if 0 : pass elif stat.S_ISSOCK(st.st_mode) : t = 'socket' elif stat.S_ISLNK (st.st_mode) : t = follow and 'symbolic link' or t elif stat.S_ISREG (st.st_mode) : t = 'file' elif stat.S_ISBLK (st.st_mode) : t = 'block special (%d/%d)'%(dmaj,dmin) elif stat.S_ISDIR (st.st_mode) : t = 'directory' elif stat.S_ISCHR (st.st_mode) : t = 'character special (%d/%d)'%(dmaj,dmin) elif stat.S_ISFIFO(st.st_mode) : t = 'pipe' else: t = '<unknown>' if st.st_mode & stat.S_ISUID : t = 'setuid(%d=%s) %s'%(st.st_uid,username(st.st_uid),t) if st.st_mode & stat.S_ISGID : t = 'setgid(%d=%s) %s'%(st.st_gid,groupname(st.st_gid),t) if st.st_mode & stat.S_ISVTX : t = 'sticky '+t return t HELP = '''%s [options] [files...] Options: -?, --help -- this help -m, --magic=<file> -- use this magic <file> instead of %s -f, --files=<namefile> -- read filenames for <namefile> * -C, --compile -- write "compiled" magic file -b, --brief -- don't prepend filenames to output lines + -c, --check -- check the magic file -i, --mime -- output MIME types * -k, --keep-going -- don't stop st the first match -n, --flush -- flush stdout after each line -v, --verson -- print version and exit * -z, --compressed -- try to look inside compressed files -L, --follow -- follow symlinks -s, --special -- don't skip special files * -- not implemented so far ;-) + -- implemented, but in another way... ''' def main(): import getopt global _magic try: brief = 0 flush = 0 follow= 0 mime = 0 check = 0 special=0 try: opts, args = getopt.getopt( sys.argv[1:], '?m:f:CbciknvzLs', ( 'help', 'magic=', 'names=', 'compile', 'brief', 'check', 'mime', 'keep-going', 'flush', 'version', 'compressed', 'follow', 'special', ) ) except getopt.error, why: print >>sys.stderr, sys.argv[0], why return 1 else: files = None for o,v in opts : if o in ('-?','--help'): print HELP % ( sys.argv[0], _magic, ) return 0 elif o in ('-f','--files='): files = v elif o in ('-m','--magic='): _magic = v[:] elif o in ('-C','--compile'): pass elif o in ('-b','--brief'): brief = 1 elif o in ('-c','--check'): check = 1 elif o in ('-i','--mime'): mime = 1 if os.path.exists( _magic+'.mime' ) : _magic += '.mime' print >>sys.stderr,sys.argv[0]+':',\ "Using regular magic file `%s'" % _magic elif o in ('-k','--keep-going'): pass elif o in ('-n','--flush'): flush = 1 elif o in ('-v','--version'): print 'VERSION' return 0 elif o in ('-z','--compressed'): pass elif o in ('-L','--follow'): follow = 1 elif o in ('-s','--special'): special = 1 else: if files : files = map(lambda x: x.strip(), v.split(',')) if '-' in files and '-' in args : error( 1, 'cannot use STDIN simultaneously for file list and data' ) for file in files : for name in ( (file=='-') and sys.stdin or open(file,'r',BUFFER_SIZE) ).xreadlines(): name = name.strip() if name not in args : args.append( name ) try: if check : print >>sys.stderr, 'Loading magic database...' t0 = time.time() m = MagicFile(_magic) t1 = time.time() if check : print >>sys.stderr, \ m.total_tests, 'tests loaded', \ 'for', '%.2f' % (t1-t0), 'seconds' print >>sys.stderr, len(m.tests), 'tests at top level' return 0 # XXX "shortened" form ;-) mlen = max( map(len, args) )+1 for arg in args : if not brief : print (arg + ':').ljust(mlen), ftype = get_file_type( arg, follow ) if (special and ftype.find('special')>=0) \ or ftype[-4:] == 'file' : t0 = time.time() try: t = m.detect( arg ) except (IOError,os.error), why: t = "can't read `%s' (%s)" % (why.filename,why.strerror) if ftype[-4:] == 'file' : t = ftype[:-4] + t t1 = time.time() print t and t or 'data' if 0 : print \ '#\t%d tests ok, %d tests failed for %.2f seconds'%\ (m.ack_tests, m.nak_tests, t1-t0) else: print mime and 'application/x-not-regular-file' or ftype if flush : sys.stdout.flush() # print >>sys.stderr, 'DONE' except: if check : return 1 raise else: return 0 finally: pass if __name__ == '__main__' : sys.exit( main() ) # vim:ai # EOF #
z3c.filetype
/z3c.filetype-1.2.1.tar.gz/z3c.filetype-1.2.1/src/z3c/filetype/magic.py
magic.py
from zope import interface import re # mimeTypeMatch holds regular expression for matching mime-types MTM = 'mimeTypesMatch' # mimeType holds the preferred mime type to be returned for this # interface MT = "mimeType" class ITypedFile(interface.Interface): """A Type of a file""" class IBinaryFile(ITypedFile): """Binary file""" IBinaryFile.setTaggedValue(MTM,re.compile('application/octet-stream')) IBinaryFile.setTaggedValue(MT,'application/octet-stream') class IZIPFile(IBinaryFile): """Zip file""" IZIPFile.setTaggedValue(MTM,re.compile('application/x-zip')) IZIPFile.setTaggedValue(MT,'application/x-zip') class ITARFile(IBinaryFile): """Binary file""" ITARFile.setTaggedValue(MTM,re.compile('application/x-tar')) ITARFile.setTaggedValue(MT,'application/x-tar') class IBZIP2File(IBinaryFile): """BZIP2 file""" IBZIP2File.setTaggedValue(MTM,re.compile('application/x-bzip2')) IBZIP2File.setTaggedValue(MT,'application/x-bzip2') class IGZIPFile(IBinaryFile): """Binary file""" IGZIPFile.setTaggedValue(MTM,re.compile('application/x-gzip')) IGZIPFile.setTaggedValue(MT,'application/x-gzip') class ITextFile(ITypedFile): """text files""" ITextFile.setTaggedValue(MTM,re.compile('^text/.+$')) ITextFile.setTaggedValue(MT,'text/plain') class IImageFile(interface.Interface): """marker for image files""" class IPDFFile(IBinaryFile): """pdf files""" IPDFFile.setTaggedValue(MTM,re.compile('application/pdf')) IPDFFile.setTaggedValue(MT,'application/pdf') class IBMPFile(IImageFile, IBinaryFile): """jpeg file""" IBMPFile.setTaggedValue(MTM,re.compile('image/bmp')) IBMPFile.setTaggedValue(MT,'image/bmp') class IJPGFile(IImageFile, IBinaryFile): """jpeg file""" IJPGFile.setTaggedValue(MTM,re.compile('image/jpe?g')) IJPGFile.setTaggedValue(MT,'image/jpeg') class IPNGFile(IImageFile, IBinaryFile): """png file""" IPNGFile.setTaggedValue(MTM,re.compile('image/png')) IPNGFile.setTaggedValue(MT,'image/png') class IGIFFile(IImageFile, IBinaryFile): """gif file""" IGIFFile.setTaggedValue(MTM,re.compile('image/gif')) IGIFFile.setTaggedValue(MT,'image/gif') class IVideoFile(interface.Interface): """marker for video file""" class IQuickTimeFile(IVideoFile, IBinaryFile): """Quicktime Video File Format""" IQuickTimeFile.setTaggedValue(MTM,re.compile('video/quicktime')) IQuickTimeFile.setTaggedValue(MT,'video/quicktime') class IAVIFile(IVideoFile, IBinaryFile): """Quicktime Video File Format""" IAVIFile.setTaggedValue(MTM,re.compile('video/x-msvideo')) IAVIFile.setTaggedValue(MT,'video/x-msvideo') class IMPEGFile(IVideoFile, IBinaryFile): """MPEG Video File Format""" IMPEGFile.setTaggedValue(MTM,re.compile('video/mpe?g')) IMPEGFile.setTaggedValue(MT,'video/mpeg') class IMP4File(IQuickTimeFile): """IMP4File IPod Video File Format""" IMP4File.setTaggedValue(MTM,re.compile('video/mp4')) IMP4File.setTaggedValue(MT,'video/mp4') class IFLVFile(IVideoFile, IBinaryFile): """Macromedia Flash FLV Video File Format""" IFLVFile.setTaggedValue(MTM,re.compile('video/x-flv')) IFLVFile.setTaggedValue(MT,'video/x-flv') class IASFFile(IVideoFile, IBinaryFile): """Windows Media File Format""" IASFFile.setTaggedValue(MTM,re.compile('video/x-ms-asf')) IASFFile.setTaggedValue(MT,'video/x-ms-asf') class IAudioFile(interface.Interface): """audio file""" class IAudioMPEGFile(IAudioFile, IBinaryFile): """audio file""" IAudioMPEGFile.setTaggedValue(MTM,re.compile('audio/mpeg')) IAudioMPEGFile.setTaggedValue(MT,'audio/mpeg') class IWMAFile(IAudioFile, IBinaryFile): """Windows Media File Format""" interface.taggedValue(MTM,re.compile('audio/x-ms-wma')) interface.taggedValue(MT,'audio/x-ms-wma') class IHTMLFile(ITextFile): """HTML file""" IHTMLFile.setTaggedValue(MTM,re.compile('text/html')) IHTMLFile.setTaggedValue(MT,'text/html') class IXMLFile(ITextFile): """XML File""" IXMLFile.setTaggedValue(MTM,re.compile('text/xml')) IXMLFile.setTaggedValue(MT,'text/xml') class IMSOfficeFile(IBinaryFile): """Microsoft Office File""" class IMSWordFile(IMSOfficeFile): """Microsoft Word File""" IMSWordFile.setTaggedValue(MTM,re.compile('application/.*msword')) IMSWordFile.setTaggedValue(MT,'application/msword') class IMSExcelFile(IMSOfficeFile): """Microsoft Excel File""" IMSExcelFile.setTaggedValue(MTM,re.compile('application/.*excel')) IMSExcelFile.setTaggedValue(MT,'application/msexcel') class IMSPowerpointFile(IMSOfficeFile): """Microsoft Powerpoint File""" IMSPowerpointFile.setTaggedValue(MTM,re.compile('application/.*powerpoint')) IMSPowerpointFile.setTaggedValue(MT,'application/mspowerpoint')
z3c.filetype
/z3c.filetype-1.2.1.tar.gz/z3c.filetype-1.2.1/src/z3c/filetype/interfaces/filetypes.py
filetypes.py
============== Flash messages ============== Components to display small messages to users. Sending a message to the current user ===================================== To send a message to the current user, you can use the session-based message source. Let's set one up: >>> from z3c.flashmessage.sources import SessionMessageSource >>> from __future__ import unicode_literals >>> source = SessionMessageSource() >>> source.send('The world will come to an end in 40 seconds!') The source allows to list all current messages: >>> m = list(source.list()) >>> m [<z3c.flashmessage.message.Message object at 0x...>] >>> m[0].message 'The world will come to an end in 40 seconds!' >>> str(m[0].type) 'message' Receiving messages ================== The standard message that is generated removes itself from the source when it is received. The receiver will call `prepare()` on the message before it is handed out to the code that receives it: >>> m[0].prepare(source) >>> list(source.list()) [] There also is another default message that does not delete itself when being read: >>> from z3c.flashmessage.message import PersistentMessage >>> source.send(PersistentMessage('I will stay forever!')) >>> m = list(source.list())[0] >>> m.message 'I will stay forever!' >>> m.prepare(source) >>> list(source.list()) [<z3c.flashmessage.message.PersistentMessage object at 0x...>] Global receiver =============== There is a global receiver that queries all message sources that are set up as utilities. Let's set up a session message source as a utility: >>> from zope.component import provideUtility >>> provideUtility(source) >>> source.send('Test!') >>> from z3c.flashmessage.sources import RAMMessageSource >>> source2 = RAMMessageSource() >>> provideUtility(source2, name='other') >>> source2.send('Test 2!') >>> source2.send('Test 3!') >>> from z3c.flashmessage.receiver import GlobalMessageReceiver >>> receiver = GlobalMessageReceiver() >>> m = list(receiver.receive()) >>> len(m) 4 >>> m[0].message 'I will stay forever!' >>> m[1].message 'Test!' >>> m[2].message 'Test 2!' >>> m[3].message 'Test 3!' After the receiver handed out the messages, they are gone from the sources, because the receiver notifies the messages that they were read: >>> len(list(receiver.receive())) 1 Filtering message types ======================= When listing messages from a message source, we can restrict which messages we see. If we don't give a type, then all messages are returned. The default type of a message is `message`: >>> source3 = RAMMessageSource() >>> source3.send('Test 2!') >>> list(source3.list()) [<z3c.flashmessage.message.Message object at 0x...>] >>> list(source3.list('message')) [<z3c.flashmessage.message.Message object at 0x...>] >>> list(source3.list('somethingelse')) [] Performance and Scalability Issues ================================== By default, messages are stored persistently in the ZODB using zope.session. This can be a significant scalability problem; see design.txt in zope.session for more information. You should think twice before using flashmessages for unauthenticated users, as this can easily lead to unnecessary database growth on anonymous page views, and conflict errors under heavy load. One solution is to configure your system to store flashmessages in RAM. You would do this by configuring a utility providing ``z3c.flashmessage.interfaces.IMessageSource`` with the factory set to ``z3c.flashmessage.sources.RAMMessageSource``, and a specific name if your application expects one. RAM storage is much faster and removes the persistence issues described above, but there are two new problems. First, be aware that if your server process restarts for any reason, all unread flashmessages will be lost. Second, if you cluster your application servers using e.g. ZEO, you must also ensure that your load-balancer supports session affinity (so a specific client always hits the same back end server). This somewhat reduces the performance benefits of clustering.
z3c.flashmessage
/z3c.flashmessage-3.0-py3-none-any.whl/z3c/flashmessage/README.rst
README.rst
"""A message source that stores messages in the session.""" import persistent.list import zope.interface import zope.session.interfaces import z3c.flashmessage.interfaces import z3c.flashmessage.message @zope.interface.implementer(z3c.flashmessage.interfaces.IMessageSource) class ListBasedMessageSource: """An (abstract) base class that stores messages in a list. Sub-classes have to define the method `_get_storage(self, for_write=False)`. """ def send(self, message, type="message"): """Send a message to this source.""" if not z3c.flashmessage.interfaces.IMessage.providedBy(message): # The programmer has passed in not a message, so we create a # message for him. This is allowed by the API for convenience. message = z3c.flashmessage.message.Message(message, type=type) message.source = self self._get_storage(for_write=True).append(message) def list(self, type=None): """Return all messages of the given type from this source.""" for message in self._get_storage(for_write=False): if type is None or message.type == type: yield message def delete(self, message): """Remove the given message from the source.""" self._get_storage(for_write=True).remove(message) def _get_storage(self, for_write=False): """Return the storage which must have a list API. When `for_write` is True the caller want's to write to the storage. To be implemented in concreate sub classes """ class SessionMessageSource(ListBasedMessageSource): """Source which stores its data in the session of the user.""" _pkg_id = 'z3c.flashmessage' def _get_storage(self, for_write=False): request = zope.security.management.getInteraction().participations[0] session = zope.session.interfaces.ISession(request) if for_write: # Creating a new session when it does not exist yet. session_data = session[self._pkg_id] else: # Making sure we do *not* create a new session when it not exists: session_data = session.get(self._pkg_id, {}) return session_data.setdefault('messages', persistent.list.PersistentList()) class RAMMessageSource(ListBasedMessageSource): """Source which stores its data in RAM. Caution: This source is not able to store messages for individual users. """ def __init__(self): super().__init__() self._storage = [] def _get_storage(self, for_write=False): return self._storage
z3c.flashmessage
/z3c.flashmessage-3.0-py3-none-any.whl/z3c/flashmessage/sources.py
sources.py
========= Changelog ========= 5.1 (2023-07-19) ---------------- - HTMLFormElement.attributes: Allow to extend HTML attributes programmatically. 5.0 (2023-07-17) ---------------- - Add support for Python 3.11. - Drop support for Python 2.7, 3.5, 3.6. - Drop deprecated support for ``python setup.py test``. - HTMLFormElement.addClass: Improve removal of duplicates. It's now possible to add multiple classes as whitespace separated string and still detect class duplicates. 4.3 (2022-03-24) ---------------- - Add support for Python 3.10. - Update tests to ``lxml > 4.7``, thus requiring at least that version. (`#107 <https://github.com/zopefoundation/z3c.form/issues/107>`_) - Remove unused ``ISubformFactory```. (`#110 <https://github.com/zopefoundation/z3c.form/issues/110>`_) [petschki] 4.2 (2021-07-29) ---------------- - Fix ``MultiConverter.toFieldValue`` tuple typed field support (when ``field._type`` is a tuple of types, not a single type). - Add Python 3.9 compatibility and testing. - Apply ``zopefoundation.meta`` config - Fix tests for the ``zope.schema.Bool`` required default change. - Fix tests for the ``zope.interface repr()`` change. - Fix compatibility with changed repeat syntax. Fixes `issue 94 <https://github.com/zopefoundation/z3c.form/issues/94>`_. - Some fixes in spanish translation. [erral] - Drop support for Python 3.4. - Add support for Python 3.8b4. - Try to fix the buggy hidden mode behaviour of checkbox widgets. Fixes `issue 89 <https://github.com/zopefoundation/z3c.form/issues/89>`_. 4.1.2 (2019-03-04) ------------------ - Fix an edge case when field ``missing_value`` is not ```None``` but a custom value that works as ``None``. That ended up calling ``zope.i18n NumberFormat.format`` with ``None`` what then failed. 4.1.1 (2018-11-26) ------------------ - Fix ``FieldWidgets.copy()``. It was broken since ``SelectionManager`` was reimplemented using ``OrderedDict``. 4.1.0 (2018-11-15) ------------------ - Add support for Python 3.7. - Deal with items with same name but different values in ordered field widget. [rodfersou] - Move homegrown Manager implementation to ``OrderedDict``. [tomgross] - Adapt tests to ``lxml >= 4.2``, ``zope.configuration >= 4.3`` and ``zope.schema >= 4.7``. 4.0.0 (2017-12-20) ------------------ - Upgrade the major version 4 to reflect the breaking changes in 3.3.0. (Version 3.6 will be a re-release of 3.2.x not containing the changes since 3.3.0 besides cherry-picks.) Fixes: https://github.com/zopefoundation/z3c.form/issues/41 - Host documentation at https://z3cform.readthedocs.io 3.5.0 (2017-09-19) ------------------ - Add support for Python 3.6. - Drop support for Python 3.3. - Avoid duplicated IDs when using a non-required field with ``z3c.formwidget.query.widget.QuerySourceRadioWidget``. [pgrunewald] 3.4.0 (2016-11-15) ------------------ - Drop support for Python 2.6. - Support Python 3.5 officially. - Fix TypeError: object of type 'generator' has no ``len()``. Happens with z3c.formwidget.query. [maurits] - Turned ``items`` into a property again on all widgets. For the select widget it was a method since 2.9.0. For the radio and checkbox widgets it was a method since 3.2.10. For orderedselect and multi it was always a property. Fixes https://github.com/zopefoundation/z3c.form/issues/44 [maurits] - Fix handling of missing terms in collections. (See version 2.9 describing this feature.) - Fix ``orderedselect_input.js`` resource to be usable on browser layers which do not extend ``zope.publisher.interfaces.browser.IDefaultBrowserLayer``. 3.3.0 (2016-03-09) ------------------ - *MAJOR* overhaul of ObjectWidget: * low level unittests passed, but high level was not tops basic rule is that widgets want RAW values and all conversion must be done in ``ObjectConverter`` * ``ObjectSubForm`` and ``SubformAdapter`` is removed, it was causing more problems than good * added high level integration tests - Removed ``z3c.coverage`` from ``test`` extra. [gforcada, maurits] 3.2.10 (2016-03-09) ------------------- - RadioWidget items are better determined when they are needed [agroszer] - CheckBoxWidget items are better determined when they are needed [agroszer] - Bugfix: The ``ChoiceTerms`` adapter blindly assumed that the passed in field is unbound, which is not necessarily the case in interesting ObjectWidget scenarios. Not it checks for a non-None field context first. [srichter] 3.2.9 (2016-02-01) ------------------ - Correctly handled ``noValueToken`` in RadioWidget. This avoids a ``LookupError: --NOVALUE--``. [gaudenz,ale-rt] - Added ``json`` method for forms and ``json_data`` method for widgets. [mmilkin] - Change javascript for updating ordered select widget hidden structure so it works again on IE11 and doesn't send back an empty list that deletes all selections on save. Fixes https://github.com/zopefoundation/z3c.form/issues/23 [fredvd] - Started on Dutch translations. [maurits] 3.2.8 (2015-11-09) ------------------ - Standardized namespace ``__init__``. [agroszer] 3.2.7 (2015-09-20) ------------------ - Remove "cannot move farther up/down" messages in ordered select widget. [esteele] - Updated Traditional Chinese translation. [l34marr] 3.2.6 (2015-09-10) ------------------ - Fixed warnings in headers of locales files. Checked with ``msgfmt -c``. [maurits] - Added Finnish translation. [petri] - Added Traditional Chinese translation. [l34marr] 3.2.5 (2015-09-09) ------------------ - Fixed error on Python 3: NameError: global name 'basestring' is not defined. This fixes a bug introduced in version 3.2.1. [maurits] 3.2.4 (2015-07-18) ------------------ - Fix ordered select input widget not working. [vangheem] - ReSt fix. [timo] 3.2.3 (2015-03-21) ------------------ - 3.2.2 was a brown bag release. Fix MANIFEST.in to include the js file that has been added in 3.2.2. [timo] 3.2.2 (2015-03-21) ------------------ - move js to separate file to prevent escaped entities in Plone 5. [pbauer] 3.2.1 (2014-06-09) ------------------ - Add DataExtractedEvent, which is thrown after data and errors are extracted from widgets. Fixes https://github.com/zopefoundation/z3c.form/pull/18 - Remove spaces at start and end of text field values. - Explicitly hide span in ``orderedselect_input.pt``. This only contains hidden inputs, but Internet Explorer 10 was showing them anyway. Fixes https://github.com/zopefoundation/z3c.form/issues/19 3.2.0 (2014-03-18) ------------------ - Feature: Added text and password widget HTML5 attributes required by plone.login. 3.1.1 (2014-03-02) ------------------ - Feature: Added a consistent id on single checkbox and multi checkbox widgets. 3.1.0 (2013-12-02) ------------------ - Feature: Added a consistent id on ordered selection widget. - Feature: Added a hidden template for the textlines widget. - Feature: added an API to render each radio button separately. 3.0.5 (2013-10-09) ------------------ - Bug: Remove errors for cases where the key field of a dict field uses a sequence widget (most notably choices). The sequence widget always returns lists as widget values, which are not hashable. We convert those lists to tuples now within the dict support. 3.0.4 (2013-10-06) ------------------ - Feature: Moved registration of translation directories to a separate ZCML file. - Bug: Fixed a typo in German translations. 3.0.3 (2013-09-06) ------------------ - Feature: Version 2.9 introduced a solution for missing terms in vocabularies. Adapted sources to this solution, too. 3.0.2 (2013-08-14) ------------------ - Bug: Fix unicode decode error in weird cases in ``checkbox.CheckboxWidget.update()`` and ``radio.RadioWidget.update()`` (eg: when ``term.value`` is an Plone Archetype ATFile) 3.0.1 (2013-06-25) ------------------ - Bug: The alpha slipped out as 3.0.0, removed ``ZODB-4.0.0dev.tar.gz`` to reduce damage - Bug: Fixed a bug in ``widget.py`` ``def wrapCSSClass`` 3.0.0 (2013-06-24) ------------------ - Feature: Added support for ``IDict`` field in ``MultiWidget``. - Bug: Only add the 'required' CSS class to widgets when they are in input mode. - Bug: Catch bug where if a select value was set as from hidden input or through a rest url as a single value, it won't error out when trying to remove from ignored list. Probably not the 100% right fix but it catches core dumps and is sane anyways. 3.0.0a3 (2013-04-08) -------------------- - Feature: Updated pt_BR translation. - Bug: Fixed a bug where file input value was interpeted as UTF-8. 3.0.0a2 (2013-02-26) -------------------- - Bug: The 3.0.0a1 release was missing some files (e.g. ``locales``) due to an incomplete ``MANIFEST.in``. 3.0.0a1 (2013-02-24) -------------------- - Feature: Removed several parts to be installed by default, since some packages are not ported yet. - Feature: Added support for Python 3.3. - Feature: Replaced deprecated ``zope.interface.implements`` usage with equivalent ``zope.interface.implementer`` decorator. - Feature: Dropped support for Python 2.4 and 2.5. - Bug: Make sure the call to the method that returns the default value is made with a field which has its context bound. 2.9.1 (2012-11-27) ------------------ - Feautre: The ``updateWidgets`` method has received an argument ``prefix`` which allows setting the prefix of the field widgets adapter. This allows updating the common widgets prefix before the individual widgets are updated, useful for situations where neither a form, nor a widgets prefix is desired. - Bug: Capitalize the messages 'no value' and 'select a value'. This change has been applied also to the existing translations (where applicable). - Bug: ``TextLinesConverter``: Do not ignore newlines at the end of the inputted string, thus do not eat blank items - Bug: ``TextLinesConverter``: ``toFieldValue()``, convert conversion exceptions to ``FormatterValidationError``, for cases like got a string instead of int. 2.9.0 (2012-09-17) ------------------ - Feature: Missing terms in vocabularies: this was a pain until now. Now it's possible to have the same (missing) value unchanged on the object with an EditForm after save as it was before editing. That brings some changes with it: * *MAJOR*: unchanged values/fields do not get validated anymore (unless they are empty or are FileUploads) * A temporary ``SimpleTerm`` gets created for the missing value Title is by default "Missing: ${value}". See MissingTermsMixin. - Feature: Split ``configure.zcml`` - Bug: ``SequenceWidget`` DISPLAY_MODE: silently ignore missing tokens, because INPUT_MODE and HIDDEN_MODE does that too. 2.8.2 (2012-08-17) ------------------ - Feature: Added ``IForm.ignoreRequiredOnValidation``, ``IWidgets.ignoreRequiredOnValidation``, ``IWidget.ignoreRequiredOnValidation``. Those enable ``extract`` and ``extractData`` to return without errors in case a required field is not filled. That also means the usual "Missing value" error will not get displayed. But the ``required-info`` (usually the ``*``) yes. This is handy to store partial state. 2.8.1 (2012-08-06) ------------------ - Fixed broken release, my python 2.7 windows setup didn't release the new widget.zcml, widget_layout.pt and widget_layout_hidden.pt files. After enhance the pattern in MANIFEST.in everything seems fine. That's probably because I patched my python version with the \*build exclude pattern patch. And yes, the new files where added to the svn repos! After deep into this again, it seems that only previous added \*.txt, \*.pt files get added to the release. A fresh checkout sdist release only contains the \*.py and \*.mo files. Anyway the enhanced MANIFEST.in file solved the problem. 2.8.0 (2012-08-06) ------------------ - Feature: Implemented widget layout concept similar to z3c.pagelet. The new layout concept allows to register layout templates additional to the widget templates. Such a layout template only get used if a widget get called. This enhacement is optional and compatible with all previous z3c.form versions and doesn't affect existing code and custom implementations except if you implemented a own ``__call__`` method for widgets which wasn't implemented in previous versions. The new ``__call__`` method will lookup and return a layout template which supports additional HTML code used as a wrapper for the HTML code returned from the widget render method. This concept allows to define additional HTML construct provided for all widget and render specific CSS classes arround the widget per context, view, request, etc discriminators. Such a HTML constuct was normaly supported in form macros which can't get customized on a per widget, view or context base. Summary; the new layout concept allows us to define a wrapper CSS elements for the widget element (label, widget, error) on a per widgte base and skip the generic form macros offered from z3c.formui. Note; you only could get into trouble if you define a widget in tal without to prefix them with ``nocall:`` e.g. tal:define="widget view/widgets/foo" Just add a nocall like tal:define="widget nocall:view/widgets/foo" if your rendering engine calls the __call__method by default. Also note that the following will also call the ``__call__`` method ``tal:define="widget myWidget"``. - Fixed content type extraction test which returned different values. This probably depends on a newer version of guess_content_type. Just allow image/x-png and image/pjpeg as valid values. 2.7.0 (2012-07-11) ------------------ - Remove ``zope34`` extra, use an older version of z3c.form if you need to support pre-ZTK versions. - Require at least zope.app.container 3.7 for adding support. - Avoid dependency on ZODB3. - Added IField.showDefault and IWidget.showDefault That controls whether the widget should look for field default values to display. This can be really helpful in EditForms, where you don't want to have default values instead of actual (missing) values. By default it is True to provide backwards compatibility. 2.6.1 (2012-01-30) ------------------ - Fixed a potential problem where a non-ascii vocabulary/source term value could cause the checkbox and readio widget to crash. - Fixed a problem with the ``datetime.timedelta`` converter, which failed to convert back to the field value, when the day part was missing. 2.6.0 (2012-01-30) ------------------ - Remove ":list" from radio inputs, since radio buttons can be only one value by definition. See LP580840. - Changed radio button and checkbox widget labels from token to value (wrapped by a unicode conversion) to make it consistent with the parent ``SequenceWidget`` class. This way, edit and display views of the widgets show the same label. See LP623210. - Remove dependency on zope.site.hooks, which was moved to zope.component in 3.8.0 (present in ZTK 1.0 and above). - Make zope.container dependency more optional (it is only used in tests) - Properly escape JS code in script tag for the ordered-select widget. See LP829484. - Cleaned whitespace in page templates. - Fix ``IGroupForm`` interface and actually use it in the ``GroupForm`` class. See LP580839. - Added Spanish translation. - Added Hungarian translation. 2.5.1 (2011-11-26) ------------------ - Better compatibility with Chameleon 2.x. - Added \*.mo files missing in version 2.5.0. - Pinned minimum version of test dependency ``z3c.template``. 2.5.0 (2011-10-29) ------------------ - Fixed coverage report generator script buildout setup. - Note: z3c.pt and chameleon are not fully compatible right now with TAL. Traversing the repeat wrapper is not done the same way. ZPT uses the following pattern: <tal:block condition="not:repeat/value/end">, </tal:block> Chameleon only supports python style traversing: <tal:block condition="not:python:repeat['value'].end">, </tal:block> - Upgrade to chameleon 2.0 template engine and use the newest z3c.pt and z3c.ptcompat packages adjusted to work with chameleon 2.0. See the notes from the z3c.ptcompat package: Update z3c.ptcompat implementation to use component-based template engine configuration, plugging directly into the Zope Toolkit framework. The z3c.ptcompat package no longer provides template classes, or ZCML directives; you should import directly from the ZTK codebase. Also, note that the ``PREFER_Z3C_PT`` environment option has been rendered obsolete; instead, this is now managed via component configuration. Attention: You need to include the configure.zcml file from z3c.ptcompat for enable the z3c.pt template engine. The configure.zcml will plugin the template engine. Also remove any custom built hooks which will import z3c.ptcompat in your tests or other places. You can directly use the BoundPageTemplate and ViewPageTempalteFile from zope.browserpage.viewpagetemplatefile if needed. This templates will implicit use the z3c.pt template engine if the z3c.ptcompat configure.zcml is loaded. 2.4.4 (2011-07-11) ------------------ - Remove unneeded dependency on deprecated ``zope.app.security``. - Fixed ButtonActions.update() to correctly remove actions when called again, after the button condition become false. 2.4.3 (2011-05-20) ------------------ - Declare TextLinesFieldWidget as an IFieldWidget implementer. - Clarify MultiWidget.extract(), when there are zero items, this is now [] instead of <NO_VALUE> - Some typos fixed - Fixed test failure due to change in floating point representation in Python 2.7. - Ensure at least min_length widgets are rendered for a MultiWidget in input mode. - Added Japanese translation. - Added base of Czech translation. - Added Portuguese Brazilian translation. 2.4.2 (2011-01-22) ------------------ - Adjust test for the contentprovider feature to not depend on the ContentProviderBase class that was introduced in zope.contentprovider 3.5.0. This restores compatibility with Zope 2.10. - Security issue, removed IBrowserRequest from IFormLayer. This prevents to mixin IBrowserRequest into non IBrowserRequest e.g. IJSONRPCRequest. This should be compatible since a browser request using z3c.form already provides IBrowserRequest and the IFormLayer is only a marker interface used as skin layer. - Add English translation (generated from translation template using msgen z3c.form.pot > en/LC_MESSAGES/z3c.form.po). - Added Norwegian translation, thanks to Helge Tesdal and Martijn Pieters. - Updated German translation. 2.4.1 (2010-07-18) ------------------ - Since version 2.3.4 ``applyChanges`` required that the value exists when the field had a ``DictionaryField`` data manager otherwise it broke with an ``AttributeError``. Restored previous behavior that values need not to be exist before ``applyChanges`` was called by using ``datamanager.query()`` instead of ``datamanager.get()`` to get the previous value. - Added missing dependency on ``zope.contentprovider``. - No longer using deprecated ``zope.testing.doctest`` by using python's built-in ``doctest`` module. 2.4.0 (2010-07-01) ------------------ - Feature: mix fields and content providers in forms. This allow to enrich the form by interlacing html snippets produced by content providers. Adding html outside the widgets avoids the systematic need of subclassing or changing the full widget rendering. - Bug: Radio widget was not treating value as a list in hidden mode. 2.3.4 (2010-05-17) ------------------ - Bugfix: applyChanges should not try to compare old and new values if the old value can not be accessed. - Fix DictionaryField to conform to the IDataManager spec: get() should raise an exception if no value can be found. 2.3.3 (2010-04-20) ------------------ - The last discriminator of the 'message' IValue adapter used in the ErrorViewSnippet is called 'content', but it was looked up as the error view itself. It is now looked up on the form's context. - Don't let util.getSpecification() generate an interface more than once. This causes strange effects when used in value adapters: if two adapters use e.g. ISchema['some_field'] as a "discriminator" for 'field', with one adapter being more specific on a discriminator that comes later in the discriminator list (e.g. 'form' for an ErrorViewMessage), then depending on the order in which these two were set up, the adapter specialisation may differ, giving unexpected results that make it look like the adapter registry is picking the wrong adapter. - Fix trivial test failures on Python 2.4 stemming from differences in pprint's sorting of dicts. - Don't invoke render() when publishing the form as a view if the HTTP status code has been set to one in the 3xx range (e.g. a redirect or not-modified response) - the response body will be ignored by the browser anyway. - Handle Invalid exceptions from constraints and field validators. - Don't create unnecessary self.items in update() method of SelectWidget in DISPLAY_MODE. Now items is a property. - Add hidden widget templates for radio buttons and checkboxes. 2.3.2 (2010-01-21) ------------------ - Reverted changes made in the previous release as the ``getContent`` method can return anything it wants to as long as a data manager can map the fields to it. So ``context`` should be used for group instantiation. In cases where ``context`` is not wanted, the group can be instantiated in the ``update`` method of its parent group or form. See also https://mail.zope.org/pipermail/zope-dev/2010-January/039334.html (So version 2.3.2 is the same as version 2.3.0.) 2.3.1 (2010-01-18) ------------------ - ``GroupForm`` and ``Group`` now use ``getContent`` method when instantiating group classes instead of directly accessing ``self.context``. 2.3.0 (2009-12-28) ------------------ Refactoring ~~~~~~~~~~~ - Removed deprecated zpkg slug and ZCML slugs. - Adapted tests to ``zope.schema`` 3.6.0. - Avoid to use ``zope.testing.doctestunit`` as it is now deprecated. Update ~~~~~~ - Updated German translations. 2.2.0 (2009-10-27) ------------------ - Feature: Add ``z3c.form.error.ComputedErrorViewMessage`` factory for easy creation of dynamically computed error messages. - Bug: <div class="error"> was generated twice for MultiWidget and ObjectWidget in input mode. - Bug: Replace dots with hyphens when generating form id from its name. - Refactored OutputChecker to its own module to allow using ``z3c.form.testing`` without needing to depend on ``lxml``. - Refactored: Folded duplicate code in ``z3c.form.datamanager.AttributeField`` into a single property. 2.1.0 (2009-07-22) ------------------ - Feature: The ``DictionaryFieldManager`` now allows all mappings (``zope.interface.common.mapping.IMapping``), even ``persistent.mapping.PersistentMapping`` and ``persistent.dict.PersistentDict``. By default, however, the field manager is only registered for dict, because it would otherwise get picked up in undesired scenarios. - Bug: Updated code to pass all tests on the latest package versions. - Bug: Completed the Zope 3.4 backwards-compatibility. Also created a buidlout configuration file to test the Zope 3.4 compatibility. Note: You *must* use the 'latest' or 'zope34' extra now to get all required packages. Alternatively, you can specify the packages listed in either of those extras explicitely in your product's required packages. 2.0.0 (2009-06-14) ------------------ Features ~~~~~~~~ - KGS 3.4 compatibility. This is a real hard thing, because ``z3c.form`` tests use ``lxml`` >= 2.1.1 to check test output, but KGS 3.4 has ``lxml` 1.3.6. Therefore we agree on that if tests pass with all package versions nailed by KGS 3.4 but ``lxml`` overridden to 2.1.1 then the ``z3c.form`` package works with a plain KGS 3.4. - Removed hard ``z3c.ptcompat`` and thus ``z3c.pt`` dependency. If you have ``z3c.ptcompat`` on the Python path it will be used. - Added nested group support. Groups are rendered as fieldsets. Nested fieldsets are very useful when designing forms. WARNING: If your group did have an ``applyChanges()`` (or any added(?)) method the new one added by this change might not match the signature. - Added ``labelRequired`` and ``requiredInfo`` form attributes. This is useful for conditional rendering a required info legend in form templates. The ``requiredInfo`` label depends by default on a given ``labelRequired`` message id and will only return the label if at least one widget field is required. - Add support for refreshing actions after their execution. This is useful when button action conditions are changing as a result of action execution. All you need is to set the ``refreshActions`` flag of the form to ``True`` in your action handler. - Added support for using sources. Where it was previosly possible to use a vocabulary it is now also possible to use a source. This works both for basic and contextual sources. **IMPORTANT:** The ``ChoiceTerms`` and ``CollectionTerms`` in ``z3c.form.term` are now simple functions that query for real ``ITerms`` adapters for field's ``source`` or ``value_type`` respectively. So if your code inherits the old ``ChoiceTerms`` and ``CollectionTerms`` classes, you'll need to review and adapt it. See the ``z3c.form.term`` module and its documentation. - The new ``z3c.form.interfaces.NOT_CHANGED`` special value is available to signal that the current value should be left as is. It's currently handled in the ``z3c.form.form.applyChanges()`` function. - When no file is specified in the file upload widget, instead of overwriting the value with a missing one, the old data is retained. This is done by returning the new ``NOT_CHANGED`` special value from the ``FileUploadDataConvereter``. - Preliminary support for widgets for the ``schema.IObject`` field has been added. However, there is a big caveat, please read the ``object-caveat.txt`` document inside the package. A new ``objectWidgetTemplate`` ZCML directive is provided to register widget templates for specific object field schemas. - Implemented the ``MultiWidget`` widget. This widget allows you to use simple fields like ``ITextLine``, ``IInt``, ``IPassword``, etc. in a ``IList`` or ``ITuple`` sequence. - Implemented ``TextLinesWidget`` widget. This widget offers a text area element and splits lines in sequence items. This is usfull for power user interfaces. The widget can be used for sequence fields (e.g. ``IList``) that specify a simple value type field (e.g. ``ITextLine`` or ``IInt``). - Added a new flag ``ignoreContext`` to the form field, so that one can individually select which fields should and which ones should not ignore the context. - Allow raw request values of sequence widgets to be non-sequence values, which makes integration with Javascript libraries easier. - Added support in the file upload widget's testing flavor to specify 'base64'-encoded strings in the hidden text area, so that binary data can be uploaded as well. - Allow overriding the ``required`` widget attribute using ``IValue`` adapter just like it's done for ``label`` and ``name`` attributes. - Add the ``prompt`` attribute of the ``SequenceWidget`` to the list of adaptable attributes. - Added benchmarking suite demonstrating performance gain when using ``z3c.pt``. - Added support for ``z3c.pt``. Usage is switched on via the "PREFER_Z3C_PT" environment variable or via ``z3c.ptcompat.config.[enable/diable]()``. - The ``TypeError`` message used when a field does not provide ``IFormUnicode`` now also contains the type of the field. - Add support for internationalization of ``z3c.form`` messages. Added Russian, French, German and Chinese translations. - Sphinx documentation for the package can now be created using the new ``docs`` script. - The widget for fields implementing ``IChoice`` is now looked up by querying for an adapter for ``(field, field.vocabulary, request)`` so it can be differentiated according to the type of the source used for the field. - Move ``formErrorsMessage`` attribute from ``AddForm`` and ``EditForm`` to the ``z3c.form.form.Form`` base class as it's very common validation status message and can be easily reused (especially when translations are provided). Refactoring ~~~~~~~~~~~ - Removed compatibility support with Zope 3.3. - Templates now declare XML namespaces. - HTML output is now compared using a modified version of the XML-aware output checker provided by ``lxml``. - Remove unused imports, adjust buildout dependencies in ``setup.py``. - Use the ``z3c.ptcompat`` template engine compatibility layer. Fixed Bugs ~~~~~~~~~~ - **IMPORTANT** - The signature of ``z3c.form.util.extractFileName`` function changed because of spelling mistake fix in argument name. The ``allowEmtpyPostFix`` is now called ``allowEmptyPostfix`` (note ``Empty`` instead of ``Emtpy`` and ``Postfix`` instead of ``PostFix``). - **IMPORTANT** - The ``z3c.form.interfaces.NOVALUE`` special value has been renamed to ``z3c.form.interfaces.NO_VALUE`` to follow the common naming style. The backward-compatibility ``NOVALUE`` name is still in place, but the ``repr`` output of the object has been also changed, thus it may break your doctests. - When dealing with ``Bytes`` fields, we should do a null conversion when going to its widget value. - ``FieldWidgets`` update method were appending keys and values within each update call. Now the ``util.Manager`` uses a ``UniqueOrderedKeys`` implementation which will ensure that we can't add duplicated manager keys. The implementation also ensures that we can't override the ``UniqueOrderedKeys`` instance with a new list by using a decorator. If this ``UniqueOrderedKeys`` implementation doesn't fit for all use cases, we should probably use a customized ``UserList`` implementation. Now we can call ``widgets.update()`` more then one time without any side effect. - ``ButtonActions`` update where appending keys and values within each update call. Now we can call ``actions.update()`` more then one time without any side effect. - The ``CollectionSequenceDataConverter`` no longer throws a ``TypeError: 'NoneType' object is not iterable`` when passed the value of a non-required field (which in the case of a ``List`` field is ``None``). - The ``SequenceDataConverter`` and ``CollectionSequenceDataConverter`` converter classes now ignore values that are not present in the terms when converting to a widget value. - Use ``nocall:`` modifier in ``orderedselect_input.pt`` to avoid calling list entry if it is callable. - ``SingleCheckBoxFieldWidget`` doesn't repeat the label twice (once in ``<div class="label">``, and once in the ``<label>`` next to the checkbox). - Don't cause warnings in Python 2.6. - ``validator.SimpleFieldValidator`` is now able to handle ``interfaces.NOT_CHANGED``. This value is set for file uploads when the user does not choose a file for upload. 1.9.0 (2008-08-26) ------------------ - Feature: Use the ``query()`` method in the widget manager to try extract a value. This ensures that the lookup is never failing, which is particularly helpful for dictionary-based data managers, where dictionaries might not have all keys. - Feature: Changed the ``get()`` method of the data manager to throw an error when the data for the field cannot be found. Added ``query()`` method to data manager that returns a default value, if no value can be found. - Feature: Deletion of widgets from field widget managers is now possible. - Feature: Groups now produce detailed ``ObjectModifiedEvent`` descriptions like regular edit forms do. (Thanks to Carsten Senger for providing a patch.) - Feature: The widget manager's ``extract()`` method now supports an optional ``setErrors`` (default value: True) flag that allows one to not set errors on the widgets and widget manager during data extraction. Use case: You want to inspect the entered data and handle errors manually. - Bug: The ``ignoreButtons`` flag of the ``z3c.form.form.extends()`` method was not honored. (Thanks to Carsten Senger for providing a patch.) - Bug: Group classes now implement ``IGroup``. This also helps with the detection of group instantiation. (Thanks to Carsten Senger for providing a patch.) - Bug: The list of changes in a group were updated incorrectly, since it was assumed that groups would modify mutually exclusive interfaces. Instead of using an overwriting dictionary ``update()`` method, a purely additive merge is used now. (Thanks to Carsten Senger for providing a patch.) - Bug: Added a widget for ``IDecimal`` field in testing setup. - Feature: The ``z3c.form.util`` module has a new function, ``createCSSId()`` method that generates readable ids for use with css selectors from any unicode string. - Bug: The ``applyChanges()`` method in group forms did not return a changes dictionary, but simply a boolean. This is now fixed and the group form changes are now merged with the main form changes. - Bug: Display widgets did not set the style attribute if it was available, even though the input widgets did set the style attribute. 1.8.2 (2008-04-24) ------------------ - Bug: Display Widgets added spaces (due to code indentation) to the displayed values, which in some cases, like when displaying Python source code, caused the appearance to be incorrect. - Bug: Prevent to call ``__len__`` on ``ITerms`` and use ``is None`` for check for existence. Because ``__len__`` is not a part of the ITerms API and ``not widget.terms`` will end in calling ``__len__`` on existing terms. 1.8.1 (2008-04-08) ------------------ - Bug: Fixed a bug that prohibited groups from having different contents than the parent form. Previously, the groups contents were not being properly updated. Added new documentation on how to use groups to generate object-based sub-forms. Thanks to Paul Carduner for providing the fix and documentation. 1.8.0 (2008-01-23) ------------------ - Feature: Implemented ``IDisplayForm`` interface. - Feature: Added integration tests for form interfaces. Added default class attribute called ``widgets`` in form class with default value ``None``. This helps to pass the integration tests. Now, the ``widgets`` attribute can also be used as a indicator for updated forms. - Feature: Implemented additional ``createAndAdd`` hook in ``AddForm``. This allows you to implement create and add in a single method. It also supports graceful abortion of a create and add process if we do not return the new object. This means it can also be used as a hook for custom error messages for errors happen during create and add. - Feature: Add a hidden widget template for the ``ISelectWidget``. - Feature: Arrows in the ordered select widget replaced by named entities. - Feature: Added ``CollectionSequenceDataConverter`` to ``setupFormDefaults``. - Feature: Templates for the CheckBox widget are now registered in ``checkbox.zcml``. - Feature: If a value cannot be converted from its unicode representation to a field value using the field's ``IFromUnicode`` interface, the resulting type error now shows the field name, if available. - Bug: ``createId`` could not handle arbitrary unicode input. Thanks to Andreas Reuleaux for reporting the bug and a patch for it. (Added descriptive doctests for the function in the process.) - Bug: Interface invariants where not working when not all fields needed for computing the invariant are in the submitted form. - Bug: Ordered select didn't submit selected values. - Bug: Ordered select lists displayed tokens instead of value, - Bug: ``SequenceWidget`` displayed tokens instead of value. 1.7.0 (2007-10-09) ------------------ - Feature: Implemented ``ImageButton``, ``ImageAction``, ``ImageWidget``, and ``ImageFieldWidget`` to support imge submit buttons. - Feature: The ``AttributeField`` data manager now supports adapting the content to the fields interface when the content doesn't implement this interface. - Feature: Implemented single checkbox widget that can be used for boolean fields. They are not available by default but can be set using the ``widgetFactory`` attribute. - Bug: More lingual issues have been fixed in the documentation. Thanks to Martijn Faassen for doing this. - Bug: When an error occurred during processing of the request the widget ended up being security proxied and the system started throwing ``TraversalError``-'s trying to access the ``label`` attribute of the widget. Declared that the widgets require the ``zope.Public`` permission in order to access these attributes. - Bug: When rendering a widget the ``style`` attribute was not honored. Thanks to Andreas Reuleaux for reporting. - Bug: When an error occurred in the sub-form, the status message was not set correctly. Fixed the code and the incorrect test. Thanks to Markus Kemmerling for reporting. - Bug: Several interfaces had the ``self`` argument in the method signature. Thanks to Markus Kemmerling for reporting. 1.6.0 (2007-08-24) ------------------ - Feature: An event handler for ``ActionErrorOccurred`` events is registered to merge the action error into the form's error collectors, such as ``form.widgets.errors`` and ``form.widgets['name'].error`` (if applicable). It also sets the status of the form. (Thanks to Herman Himmelbauer, who requested the feature, for providing use cases.) - Feature: Action can now raise ``ActionExecutionError`` exceptions that will be handled by the framework. These errors wrap the original error. If an error is specific to a widget, then the widget name is passed to a special ``WidgetActionExecutionError`` error. (Thanks to Herman Himmelbauer, who requested the feature, for providing use cases.) - Feature: After an action handler has been executed, an action executed event is sent to the system. If the execution was successful, the event is ``ActionSuccessfull`` event is sent. If an action execution error was raised, the ``ActionErrorOccurred`` event is raised. (Thanks to Herman Himmelbauer, who requested the feature, for providing use cases.) - Feature: The ``applyChanges()`` function now returns a dictionary of changes (grouped by interface) instead of a boolean. This allows us to generate a more detailed object-modified event. If no changes are applied, an empty dictionary is returned. The new behavior is compatible with the old one, so no changes to your code are required. (Thanks to Darryl Cousins for the request and implementation.) - Feature: A new ``InvalidErrorViewSnippet`` class provides an error view snippet for ``zope.interface.Invalid`` exceptions, which are frequently used for invariants. - Feature: When a widget is required, HTML-based widgets now declare a "required" class. - Feature: The validation data wrapper now knows about the context of the validation, which provides a hook for invariants to access the environment. - Feature: The BoolTerms term tokens are now cosntants and stay the same, even if the label has changed. The choice for the token is "true" and "false". By default it used to be "yes" and "no", so you probably have to change some unit tests. Functional tests are still okay, because you select by term title. - Feature: BoolTerms now expose the labels for the true and false values to the class. This makes it a matter of doing trivial sub-classing to change the labels for boolean terms. - Feature: Exposed several attributes of the widget manager to the form for convenience. The attributes are: mode, ignoreContext, ignoreRequest, ignoreReadonly. - Feature: Provide more user-friendly error messages for number formatting. - Refactoring: The widget specific class name was in camel-case. A converntion that later developed uses always dash-based naming of HTML/CSS related variables. So for example, the class name "textWidget" is now "text-widget". This change will most likely require some changes to your CSS declarations! - Documentation: The text of ``field.txt`` has been reviewed linguistically. - Documentation: While reviewing the ``form.txt`` with some people, several unclear and incomplete statements were discovered and fixed. - Bug (IE): In Internet Explorer, when a label for a radio input field is only placed around the text describing the choice, then only the text is surrounded by a dashed box. IE users reported this to be confusing, thus we now place the label around the text and the input element so that both are surrounded by the dashed border. In Firefox and KHTML (Safari) only the radio button is surrounded all the time. - Bug: When extracting and validating data in the widget manager, invariant errors were not converted to error view snippets. - Bug: When error view snippets were not widget-specific -- in other words, the ``widget`` attribute was ``None`` -- rendering the template would fail. 1.5.0 (2007-07-18) ------------------ - Feature: Added a span around values for widgets in display mode. This allows for easier identification widget values in display mode. - Feature: Added the concept of widget events and implemented a particular "after widget update" event that is called right after a widget is updated. - Feature: Restructured the approach to customize button actions, by requiring the adapter to provide a new interface ``IButtonAction``. Also, an adapter is now provided by default, still allowing cusotmization using the usual methods though. - Feature: Added button widget. While it is not very useful without Javascript, it still belongs into this package for completion. - Feature: All ``IFieldWidget`` instances that are also HTML element widgets now declare an additional CSS class of the form "<fieldtype.lower()>-field". - Feature: Added ``addClass()`` method to HTML element widgets, so that adding a new CSS class is simpler. - Feature: Renamed "css" attribute of the widget to "klass", because the class of an HTML element is a classification, not a CSS marker. - Feature: Reviewed all widget attributes. Added all available HTML attributes to the widgets. - Documentation: Removed mentioning of widget's "hint" attribute, since it does not exist. - Optimization: The terms for a sequence widget were looked up multiple times among different components. The widget is now the canonical source for the terms and other components, such as the converter uses them. This avoids looking up the terms multiple times, which can be an expensive process for some applications. - Bug/Feature: Correctly create labels for radio button choices. - Bug: Buttons did not honor the name given by the schema, if created within one, because we were too anxious to give buttons a name. Now name assignment is delayed until the button is added to the button manager. - Bug: Button actions were never updated in the actions manager. - Bug: Added tests for textarea widget. 1.4.0 (2007-06-29) ------------------ - Feature: The select widget grew a new ``prompt`` flag, which allows you to explicitely request a selection prompt as the first option in the selection (even for required fields). When set, the prompt message is shown. Such a prompt as option is common in Web-UIs. - Feature: Allow "no value message" of select widgets to be dynamically changed using an attribute value adapter. - Feature: Internationalized data conversion for date, time, date/time, integer, float and decimal. Now the locale data is used to format and parse those data types to provide the bridge to text-based widgets. While those features require the latest zope.i18n package, backward compatibility is provided. - Feature: All forms now have an optional label that can be used by the UI. - Feature: Implemented groups within forms. Groups allow you to combine a set of fields/widgets into a logical unit. They were designed with ease of use in mind. - Feature: Button Actions -- in other words, the widget for the button field -- can now be specified either as the "actionFactory" on the button field or as an adapter. - Bug: Recorded all public select-widget attributes in the interface. 1.3.0 (2007-06-22) ------------------ - Feature: In an edit form applying the data and generating all necessary messages was all done within the "Apply" button handler. Now the actual task of storing is factored out into a new method called "applyChanges(data)", which returns whether the data has been changed. This is useful for forms not dealing with objects. - Feature: Added support for ``hidden`` fields. You can now use the ``hidden`` mode for widgets which should get rendered as ``<input type="hidden" />``. Note: Make sure you use the new formui templates which will avoid rendering labels for hidden widgets or adjust your custom form macros. - Feature: Added ``missing_value`` support to data/time converters - Feature: Added named vocabulary lookup in ``ChoiceTerms`` and ``CollectionTerms``. - Feature: Implemented support for ``FileUpload`` in ``FileWidget``. * Added helper for handling ``FileUpload`` widgets: + ``extractContentType(form, id)`` Extracts the content type if ``IBytes``/``IFileWidget`` was used. + ``extractFileName(form, id, cleanup=True, allowEmtpyPostFix=False)`` Extracts a filename if ``IBytes``/``IFileWidget`` was used. Uploads from win/IE need some cleanup because the filename includes also the path. The option ``cleanup=True`` will do this for you. The option ``allowEmtpyPostFix`` allows you to pass a filename without extensions. By default this option is set to ``False`` and will raise a ``ValueError`` if a filename doesn't contain an extension. * Created afile upload data converter registered for ``IBytes``/``IFileWidget`` ensuring that the converter will only be used for fiel widgets. The file widget is now the default for the bytes field. If you need to use a text area widget for ``IBytes``, you have to register a custom widget in the form using:: fields['foobar'].widgetFactory = TextWidget - Feature: Originally, when an attribute access failed in Unauthorized or ForbiddenAttribute exceptions, they were ignored as if the attribute would have no value. Now those errors are propagated and the system will fail providing the developer with more feedback. The datamanager also grew a new ``query()`` method that returns always a default and the ``get()`` method propagates any exceptions. - Feature: When writing to a field is forbidden due to insufficient priviledges, the resulting widget mode will be set to "display". This behavior can be overridden by explicitely specifying the mode on a field. - Feature: Added an add form implementation against ``IAdding``. While this is not an encouraged method of adding components, many people still use this API to extend the ZMI. - Feature: The ``IFields`` class' ``select()`` and ``omit()`` method now support two ketword arguments "prefix" and "interface" that allow the selection and omission of prefixed fields and still specify the short name. Thanks to Nikolay Kim for the idea. - Feature: HTML element ids containing dots are not very good, because then the "element#id" CSS selector does not work and at least in Firefox the attribute selector ("element[attr=value]") does not work for the id either. Converted the codebase to use dashes in ids instead. - Bug/Feature: The ``IWidgets`` component is now an adapter of the form content and not the form context. This guarantees that vocabulary factories receive a context that is actually useful. - Bug: The readonly flag within a field was never honored. When a field is readonly, it is displayed in "display" mode now. This can be overridden by the widget manager's "ignoreReadonly" flag, which is necessary for add forms. - Bug: The mode selection made during the field layout creation was not honored and the widget manager always overrode the options providing its value. Now the mode specified in the field is more important than the one from the widget manager. - Bug: It sometimes happens that the sequence widget has the no-value token as one element. This caused ``displayValue()`` to fail, since it tried to find a term for it. For now we simply ignore the no-value token. - Bug: Fixed the converter when the incoming value is an empty string. An empty string really means that we have no value and it is thus missing, returning the missing value. - Bug: Fix a slightly incorrect implementation. It did not cause any harm in real-world forms, but made unit testing much harder, since an API expectation was not met correctly. - Bug: When required selections where not selected in radio and checkbox widgets, then the conversion did not behave correctly. This also revealed some issues with the converter code that have been fixed now. - Bug: When fields only had a vocabulary name, the choice terms adaptation would fail, since the field was not bound. This has now been corrected. - Documentation: Integrated English language and content review improvements by Roy Mathew in ``form.txt``. 1.2.0 (2007-05-30) ------------------ - Feature: Added ability to change the button action title using an ``IValue`` adapter. 1.1.0 (2007-05-30) ------------------ - Feature: Added compatibility for Zope 3.3 and thus Zope 2.10. 1.0.0 (2007-05-24) ------------------ - Initial Release
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/CHANGES.rst
CHANGES.rst
========== z3c.form ========== .. image:: https://img.shields.io/pypi/v/z3c.form.svg :target: https://pypi.python.org/pypi/z3c.form/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/z3c.form.svg :target: https://pypi.org/project/z3c.form/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/z3c.form/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/z3c.form/actions/workflows/tests.yml .. image:: https://coveralls.io/repos/github/zopefoundation/z3c.form/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/z3c.form?branch=master .. image:: https://readthedocs.org/projects/z3cform/badge/?version=latest :target: https://z3cform.readthedocs.io/en/latest/ :alt: Documentation Status ``z3c.form`` provides an implementation for both HTML and JSON forms and according widgets. Its goal is to provide a simple API but with the ability to easily customize any data or steps. There are currently two maintained branches: * `master <https://github.com/zopefoundation/z3c.form/tree/master>`_ with the latest changes * `3.x <https://github.com/zopefoundation/z3c.form/tree/3.x>`_ without the object widget overhaul and still including the ``ObjectSubForm`` and the ``SubformAdapter``. Documentation on this implementation and its API can be found at https://z3cform.readthedocs.io/
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/README.rst
README.rst
Authors ======= Initial developers ------------------ * Stephan Richter (stephan.richter <at> gmail.com) * Roger Ineichen (roger <at> projekt01.ch) Contributors ------------ * Adam Groszer * Axel Muller * Brian Sutherland * Carsten Senger * Christian Zagrodnick * Christopher Combelles * Dan Korostelev * Daniel Nouri * Darryl Cousins * David Glick * Herman Himmelbauer * Jacob Holm * Laurent Mignon * Malthe Borch * Marius Gedminas * Martijn Faassen * Martin Aspeli * Michael Howitz * Michael Kerrin * Paul Carduner * Dylan Jay * Chris Calloway
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/AUTHOR.rst
AUTHOR.rst
====================== To-dos and help wanted ====================== Python 3 -------- - Activate parts as packages get ported. - Support new schema fields, ``NativeString`` and ``NativeStringLine``. Framework --------- - There is only hidden widget templates registered for ``ITextWidget`` and ``ISelectWidget``. We have to define more hidden widgets. Widgets ------- - The MultiWidget should render a minimum number of elements by default if the field defines min_length. Also, if user tries to remove elements so the number of widgets becomes less than minimum - the widget should add widgets to make their number minimum again. (Did you understand this?:)) - The MultiWidget should provide a way to reorder elements if used for the ISequence field. - The values defined in "browser" widgets, like ``klass`` or ``onclick`` should be overridable by value adapters. - File upload widget and converter should have a "clear current" option available to clear current value if there's any and the field is not required. Documentation ------------- - Proofread documentation - Extend API documentation Samples ------- Write some samples to show the power of the new widget and form framework. - Object name as an additional field in an add form Improvements ------------ Add explicit difference between error and confirmation message e.g. "There were some errors." and "No changes were applied." Think about making the framework use NOT_CHANGED on every widget that does not change it's value.
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/TODOS.rst
TODOS.rst
__docformat__ = "reStructuredText" import zope.component import zope.interface from z3c.form import interfaces from z3c.form import util @zope.interface.implementer(interfaces.IValue) class StaticValue: """Static value adapter.""" def __init__(self, value): self.value = value def get(self): return self.value def __repr__(self): return '<{} {!r}>'.format(self.__class__.__name__, self.value) @zope.interface.implementer(interfaces.IValue) class ComputedValue: """Static value adapter.""" def __init__(self, func): self.func = func def get(self): return self.func(self) def __repr__(self): return '<{} {!r}>'.format(self.__class__.__name__, self.get()) class ValueFactory: """Computed value factory.""" def __init__(self, value, valueClass, discriminators): self.value = value self.valueClass = valueClass self.discriminators = discriminators def __call__(self, *args): sv = self.valueClass(self.value) for name, value in zip(self.discriminators, args): setattr(sv, name, value) return sv class ValueCreator: """Base class for value creator""" valueClass = StaticValue def __init__(self, discriminators): self.discriminators = discriminators def __call__(self, value, **kws): # Step 1: Check that the keyword argument names match the # discriminators if set(kws).difference(set(self.discriminators)): raise ValueError( 'One or more keyword arguments did not match the ' 'discriminators.') # Step 2: Create an attribute value factory factory = ValueFactory(value, self.valueClass, self.discriminators) # Step 3: Build the adaptation signature signature = [] for disc in self.discriminators: spec = util.getSpecification(kws.get(disc)) signature.append(spec) # Step 4: Assert the adaptation signature onto the factory zope.component.adapter(*signature)(factory) zope.interface.implementer(interfaces.IValue)(factory) return factory class StaticValueCreator(ValueCreator): """Creates static value.""" valueClass = StaticValue class ComputedValueCreator(ValueCreator): """Creates computed value.""" valueClass = ComputedValue
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/value.py
value.py
__docformat__ = "reStructuredText" import zope.component import zope.interface import zope.location import zope.schema.interfaces from z3c.form import interfaces from z3c.form import util from z3c.form.error import MultipleErrors from z3c.form.widget import AfterWidgetUpdateEvent def _initkw(keepReadOnly=(), omitReadOnly=False, **defaults): return keepReadOnly, omitReadOnly, defaults class WidgetFactories(dict): def __init__(self): super().__init__() self.default = None def __getitem__(self, key): if key not in self and self.default: return self.default return super().__getitem__(key) def get(self, key, default=None): if key not in self and self.default: return self.default return super().get(key, default) class WidgetFactoryProperty: def __get__(self, inst, klass): if not hasattr(inst, '_widgetFactories'): inst._widgetFactories = WidgetFactories() return inst._widgetFactories def __set__(self, inst, value): if not hasattr(inst, '_widgetFactories'): inst._widgetFactories = WidgetFactories() inst._widgetFactories.default = value @zope.interface.implementer(interfaces.IField) class Field: """Field implementation.""" widgetFactory = WidgetFactoryProperty() def __init__(self, field, name=None, prefix='', mode=None, interface=None, ignoreContext=None, showDefault=None): self.field = field if name is None: name = field.__name__ assert name self.__name__ = util.expandPrefix(prefix) + name self.prefix = prefix self.mode = mode if interface is None: interface = field.interface self.interface = interface self.ignoreContext = ignoreContext self.showDefault = showDefault def __repr__(self): return '<{} {!r}>'.format(self.__class__.__name__, self.__name__) @zope.interface.implementer(interfaces.IFields) class Fields(util.SelectionManager): """Field manager.""" managerInterface = interfaces.IFields def __init__(self, *args, **kw): keepReadOnly, omitReadOnly, defaults = _initkw(**kw) fields = [] for arg in args: if isinstance(arg, zope.interface.interface.InterfaceClass): for name, field in zope.schema.getFieldsInOrder(arg): fields.append((name, field, arg)) elif zope.schema.interfaces.IField.providedBy(arg): name = arg.__name__ if not name: raise ValueError("Field has no name") fields.append((name, arg, arg.interface)) elif self.managerInterface.providedBy(arg): for form_field in arg.values(): fields.append( (form_field.__name__, form_field, form_field.interface)) elif isinstance(arg, Field): fields.append((arg.__name__, arg, arg.interface)) else: raise TypeError("Unrecognized argument type", arg) super().__init__() for name, field, iface in fields: if isinstance(field, Field): form_field = field else: if field.readonly: if omitReadOnly and (name not in keepReadOnly): continue customDefaults = defaults.copy() if iface is not None: customDefaults['interface'] = iface form_field = Field(field, **customDefaults) name = form_field.__name__ if name in self: raise ValueError("Duplicate name", name) self[name] = form_field def select(self, *names, **kwargs): """See interfaces.IFields""" prefix = kwargs.pop('prefix', None) interface = kwargs.pop('interface', None) assert len(kwargs) == 0 if prefix: names = [util.expandPrefix(prefix) + name for name in names] mapping = self if interface is not None: mapping = {field.field.__name__: field for field in self.values() if field.field.interface is interface} return self.__class__(*[mapping[name] for name in names]) def omit(self, *names, **kwargs): """See interfaces.IFields""" prefix = kwargs.pop('prefix', None) interface = kwargs.pop('interface', None) assert len(kwargs) == 0 if prefix: names = [util.expandPrefix(prefix) + name for name in names] return self.__class__( *[field for name, field in self.items() if not ((name in names and interface is None) or (field.field.interface is interface and field.field.__name__ in names))]) @zope.interface.implementer_only(interfaces.IWidgets) class FieldWidgets(util.Manager): """Widget manager for IFieldWidget.""" zope.component.adapts( interfaces.IFieldsForm, interfaces.IFormLayer, zope.interface.Interface) prefix = 'widgets.' mode = interfaces.INPUT_MODE errors = () hasRequiredFields = False ignoreContext = False ignoreRequest = False ignoreReadonly = False ignoreRequiredOnExtract = False setErrors = True def __init__(self, form, request, content): super().__init__() self.form = form self.request = request self.content = content def validate(self, data): fields = self.form.fields.values() # Step 1: Collect the data for the various schemas schemaData = {} for field in fields: schema = field.interface if schema is None: continue fieldData = schemaData.setdefault(schema, {}) if field.__name__ in data: fieldData[field.field.__name__] = data[field.__name__] # Step 2: Validate the individual schemas and collect errors errors = () content = self.content if self.ignoreContext: content = None for schema, fieldData in schemaData.items(): validator = zope.component.getMultiAdapter( (content, self.request, self.form, schema, self), interfaces.IManagerValidator) errors += validator.validate(fieldData) return errors def update(self): """See interfaces.IWidgets""" # Create a unique prefix. prefix = util.expandPrefix(self.form.prefix) prefix += util.expandPrefix(self.prefix) # Walk through each field, making a widget out of it. d = {} d.update(self) for field in self.form.fields.values(): # Step 0. Determine whether the context should be ignored. ignoreContext = self.ignoreContext if field.ignoreContext is not None: ignoreContext = field.ignoreContext # Step 1: Determine the mode of the widget. mode = self.mode if field.mode is not None: mode = field.mode elif field.field.readonly and not self.ignoreReadonly: mode = interfaces.DISPLAY_MODE elif not ignoreContext: # If we do not have enough permissions to write to the # attribute, then switch to display mode. dm = zope.component.getMultiAdapter( (self.content, field.field), interfaces.IDataManager) if not dm.canWrite(): mode = interfaces.DISPLAY_MODE # Step 2: Get the widget for the given field. shortName = field.__name__ newWidget = True if shortName in self: # reuse existing widget widget = d[shortName] newWidget = False elif field.widgetFactory.get(mode) is not None: factory = field.widgetFactory.get(mode) widget = factory(field.field, self.request) else: widget = zope.component.getMultiAdapter( (field.field, self.request), interfaces.IFieldWidget) # Step 3: Set the prefix for the widget widget.name = prefix + shortName widget.id = (prefix + shortName).replace('.', '-') # Step 4: Set the context widget.context = self.content # Step 5: Set the form widget.form = self.form # Optimization: Set both interfaces here, rather in step 4 and 5: # ``alsoProvides`` is quite slow zope.interface.alsoProvides( widget, interfaces.IContextAware, interfaces.IFormAware) # Step 6: Set some variables widget.ignoreContext = ignoreContext widget.ignoreRequest = self.ignoreRequest if field.showDefault is not None: widget.showDefault = field.showDefault # Step 7: Set the mode of the widget widget.mode = mode # Step 8: Update the widget widget.update() zope.event.notify(AfterWidgetUpdateEvent(widget)) # Step 9: Add the widget to the manager if widget.required: self.hasRequiredFields = True if newWidget: d[shortName] = widget zope.location.locate(widget, self, shortName) self.create_according_to_list(d, self.form.fields.keys()) def _extract(self, returnRaw=False): data = {} errors = () for name, widget in self.items(): if widget.mode == interfaces.DISPLAY_MODE: continue value = widget.field.missing_value try: widget.setErrors = self.setErrors raw = widget.extract() if raw is not interfaces.NO_VALUE: value = interfaces.IDataConverter(widget).toFieldValue(raw) widget.ignoreRequiredOnValidation = ( self.ignoreRequiredOnExtract) zope.component.getMultiAdapter( (self.content, self.request, self.form, getattr(widget, 'field', None), widget), interfaces.IValidator).validate(value) except (zope.interface.Invalid, ValueError, MultipleErrors) as error: view = zope.component.getMultiAdapter( (error, self.request, widget, widget.field, self.form, self.content), interfaces.IErrorViewSnippet) view.update() if self.setErrors: widget.error = view errors += (view,) else: name = widget.__name__ if returnRaw: data[name] = raw else: data[name] = value for error in self.validate(data): view = zope.component.getMultiAdapter( (error, self.request, None, None, self.form, self.content), interfaces.IErrorViewSnippet) view.update() errors += (view,) if self.setErrors: self.errors = errors return data, errors def extract(self): """See interfaces.IWidgets""" return self._extract(returnRaw=False) def extractRaw(self): """See interfaces.IWidgets""" return self._extract(returnRaw=True) def copy(self): """See interfaces.ISelectionManager""" clone = self.__class__(self.form, self.request, self.content) super(self.__class__, clone).update(self) return clone
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/field.py
field.py
========================= Add Forms for ``IAdding`` ========================= While using ``IAdding``-based add forms is strongly discouraged by this package due to performance and code complexity concerns, there is still the need for add forms based on IAdding, especially when one wants to extend the default ZMI and use the add menu. Before we get started, we need to register a bunch of form-related components: >>> from z3c.form import testing >>> testing.setupFormDefaults() Let's first create a content component: >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... ... name = zope.schema.TextLine( ... title=u'Name', ... required=True) >>> from zope.schema.fieldproperty import FieldProperty >>> @zope.interface.implementer(IPerson) ... class Person(object): ... name = FieldProperty(IPerson['name']) ... ... def __init__(self, name): ... self.name = name ... ... def __repr__(self): ... return '<%s %r>' %(self.__class__.__name__, self.name) Next we need a container to which we wish to add the person: >>> from zope.container.btree import BTreeContainer >>> people = BTreeContainer() When creating and adding a new object using the ``IAdding`` API, the container is adapted to ``IAdding`` view: >>> request = testing.TestRequest() >>> from zope.app.container.browser.adding import Adding >>> adding = Adding(people, request) >>> adding <zope.app.container.browser.adding.Adding object at ...> To be able to create a person using ``IAdding``, we need to create an add form for it now: >>> import os >>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile >>> from z3c.form import tests, field >>> from z3c.form.adding import AddForm >>> class AddPersonForm(AddForm): ... template = ViewPageTemplateFile( ... 'simple_edit.pt', os.path.dirname(tests.__file__)) ... ... fields = field.Fields(IPerson) ... ... def create(self, data): ... return Person(**data) Besides the usual template and field declarations, one must also implement the ``create()`` method. Note that the ``add()`` and ``nextURL()`` methods are implemented for you already in comparison to the default add form. After instantiating the form, ... >>> add = AddPersonForm(adding, request) ... we can now view the form: >>> print(add()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="form-widgets-name">Name</label> <input type="text" id="form-widgets-name" name="form.widgets.name" class="text-widget required textline-field" value="" /> </div> <div class="action"> <input type="submit" id="form-buttons-add" name="form.buttons.add" class="submit-widget button-field" value="Add" /> </div> </form> </body> </html> Once the form is filled out and the add button is clicked, ... >>> request = testing.TestRequest( ... form={'form.widgets.name': u'Stephan', 'form.buttons.add': 1}) >>> adding = Adding(people, request) >>> add = AddPersonForm(adding, request) >>> add.update() ... the person is added to the container: >>> sorted(people.keys()) [u'Person'] >>> people['Person'] <Person u'Stephan'> When the add form is rendered, nothing is returned and only the redirect header is set to the next URL. For this to work, we need to setup the location root correctly: >>> from zope.traversing.interfaces import IContainmentRoot >>> zope.interface.alsoProvides(people, IContainmentRoot) >>> add.render() '' >>> request.response.getHeader('Location') 'http://127.0.0.1/@@contents.html'
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/adding.rst
adding.rst
=================== ObjectWidget caveat =================== ObjectWidget itself seems to be fine, but we discovered a fundamental problem in z3c.form. The meat is that widget value * validation * extraction * applying values need to be separated and made recursive-aware. Currently --------- * There is a loop that extracts and validates each widgets value. Then it moves on to the next widget in the same loop. * The problem is that the ObjectWidget MUST keep it's values in the object itself, not in any dict or helper structure. That means in case of a validation failure later in the loop the ObjectWidget's values are already applied and cannot be reverted. * Also on a single level of widgets this loop might be OK, because the loop is just flat. We need ------- * To do a loop to validate ALL widget values. * To do a loop to extract ALL values. (maybe apply too, let's think about it...) * Then in a different loop apply those extracted (and validated) values. * Problem is that the current API does not support separate methods for that. * One more point is to take into account that with the ObjectWidget forms and widgets can be _recursive_, that means there can be a form-widgets-subform-widgets-subform-widgets level of widgets. An example: > The situation is the following: > - schema is like this: > class IMySubObject(zope.interface.Interface): > foofield = zope.schema.Int( > title=u"My foo field", > default=1111, > max=9999) > barfield = zope.schema.Int( > title=u"My dear bar", > default=2222, > required=False) > class IMyObject(zope.interface.Interface): > subobject = zope.schema.Object(title=u'my object', > schema=IMySubObject) > name = zope.schema.TextLine(title=u'name') > > - on object editing > - we need to keep the (**old**) (IMySubObject) object in place > -- do not create a new one > - value setting is done in the editform handleApply > - extractData, extract needs to extract recursively > - return assignable values > - it has no idea about subobjects > - let's say the IMySubObject data is validated OK, but there's an > error in IMyObject (with name) > - now the problem is: > - IMyObject.subobject extract gets called first > it sets the values on the existing object (and fires > ObjectModifiedEvent) > - IMyObject.name detects the error > it does not set the value > BUT IMyObject.subobject sticks to the extracted value that should be > discarded, because the whole form did not validate?!?!?!
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/object-caveat.rst
object-caveat.rst
__docformat__ = "reStructuredText" import binascii import re import string from collections import OrderedDict from functools import total_ordering import zope.contenttype import zope.interface import zope.schema from z3c.form import interfaces from z3c.form.i18n import MessageFactory as _ _identifier = re.compile('[A-Za-z][a-zA-Z0-9_]*$') classTypes = (type,) _acceptableChars = string.ascii_letters + string.digits + '_-' def toUnicode(obj): if isinstance(obj, bytes): return obj.decode('utf-8', 'ignore') return str(obj) def toBytes(obj): if isinstance(obj, bytes): return obj if isinstance(obj, str): return obj.encode('utf-8') return str(obj).encode('utf-8') def createId(name): """Returns a *native* string as id of the given name.""" if _identifier.match(name): return str(name).lower() id = binascii.hexlify(name.encode('utf-8')) return id.decode() @total_ordering class MinType: def __le__(self, other): return True def __eq__(self, other): return (self is other) def sortedNone(items): Min = MinType() return sorted(items, key=lambda x: Min if x is None else x) def createCSSId(name): return str(''.join([ (char if char in _acceptableChars else binascii.hexlify(char.encode('utf-8')).decode()) for char in name])) def getSpecification(spec, force=False): """Get the specification of the given object. If the given object is already a specification acceptable to the component architecture, it is simply returned. This is true for classes and specification objects (which includes interfaces). In case of instances, an interface is generated on the fly and tagged onto the object. Then the interface is returned as the specification. """ # If the specification is an instance, then we do some magic. if (force or (spec is not None and not zope.interface.interfaces.ISpecification.providedBy(spec) and not isinstance(spec, classTypes))): # Step 1: Calculate an interface name ifaceName = 'IGeneratedForObject_%i' % id(spec) # Step 2: Find out if we already have such an interface existingInterfaces = [ i for i in zope.interface.directlyProvidedBy(spec) if i.__name__ == ifaceName ] # Step 3a: Return an existing interface if there is one if len(existingInterfaces) > 0: spec = existingInterfaces[0] # Step 3b: Create a new interface if not else: iface = zope.interface.interface.InterfaceClass(ifaceName) zope.interface.alsoProvides(spec, iface) spec = iface return spec def expandPrefix(prefix): """Expand prefix string by adding a trailing period if needed. expandPrefix(p) should be used instead of p+'.' in most contexts. """ if prefix and not prefix.endswith('.'): return prefix + '.' return prefix def getWidgetById(form, id): """Get a widget by it's rendered DOM element id.""" # convert the id to a name name = id.replace('-', '.') prefix = form.prefix + form.widgets.prefix if not name.startswith(prefix): raise ValueError(f"Name {name!r} must start with prefix {prefix!r}") shortName = name[len(prefix):] return form.widgets.get(shortName, None) def extractContentType(form, id): """Extract the content type of the widget with the given id.""" widget = getWidgetById(form, id) return zope.contenttype.guess_content_type(widget.filename)[0] def extractFileName(form, id, cleanup=True, allowEmptyPostfix=False): """Extract the filename of the widget with the given id. Uploads from win/IE need some cleanup because the filename includes also the path. The option ``cleanup=True`` will do this for you. The option ``allowEmptyPostfix`` allows to have a filename without extensions. By default this option is set to ``False`` and will raise a ``ValueError`` if a filename doesn't contain a extension. """ widget = getWidgetById(form, id) if not allowEmptyPostfix or cleanup: # We need to strip out the path section even if we do not reomve them # later, because we just need to check the filename extension. cleanFileName = widget.filename.split('\\')[-1] cleanFileName = cleanFileName.split('/')[-1] dottedParts = cleanFileName.split('.') if not allowEmptyPostfix: if len(dottedParts) <= 1: raise ValueError(_('Missing filename extension.')) if cleanup: return cleanFileName return widget.filename def changedField(field, value, context=None): """Figure if a field's value changed Comparing the value of the context attribute and the given value""" if context is None: context = field.context if context is None: # IObjectWidget madness return True if zope.schema.interfaces.IObject.providedBy(field): return True # Get the datamanager and get the original value dm = zope.component.getMultiAdapter( (context, field), interfaces.IDataManager) # now figure value chaged status # Or we can not get the original value, in which case we can not check # Or it is an Object, in case we'll never know if (not dm.canAccess() or dm.query() != value): return True else: return False def changedWidget(widget, value, field=None, context=None): """figure if a widget's value changed Comparing the value of the widget context attribute and the given value""" if (interfaces.IContextAware.providedBy(widget) and not widget.ignoreContext): # if the widget is context aware, figure if it's field changed if field is None: field = widget.field if context is None: context = widget.context return changedField(field, value, context=context) # otherwise we cannot, return 'always changed' return True @zope.interface.implementer(interfaces.IManager) class Manager(OrderedDict): """Non-persistent IManager implementation.""" def create_according_to_list(self, d, l_): """Arrange elements of d according to sorting of l_.""" # TODO: If we are on Python 3 only reimplement on top of `move_to_end` self.clear() for key in l_: if key in d: self[key] = d[key] def __getitem__(self, key): if key not in self: try: return getattr(self, key) except AttributeError: # make sure an KeyError is raised later pass return super().__getitem__(key) @zope.interface.implementer(interfaces.ISelectionManager) class SelectionManager(Manager): """Non-persisents ISelectionManager implementation.""" managerInterface = None def __add__(self, other): if not self.managerInterface.providedBy(other): return NotImplemented return self.__class__(self, other) def select(self, *names): """See interfaces.ISelectionManager""" return self.__class__(*[self[name] for name in names]) def omit(self, *names): """See interfaces.ISelectionManager""" return self.__class__( *[item for name, item in self.items() if name not in names]) def copy(self): """See interfaces.ISelectionManager""" return self.__class__(*self.values())
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/util.py
util.py
__docformat__ = "reStructuredText" import sys import zope.event import zope.interface import zope.location import zope.schema import zope.traversing.api from zope.component import hooks from zope.interface import adapter from zope.schema.fieldproperty import FieldProperty from z3c.form import action from z3c.form import interfaces from z3c.form import util from z3c.form import value from z3c.form.browser import image from z3c.form.browser import submit from z3c.form.widget import AfterWidgetUpdateEvent StaticButtonActionAttribute = value.StaticValueCreator( discriminators=('form', 'request', 'content', 'button', 'manager') ) ComputedButtonActionAttribute = value.ComputedValueCreator( discriminators=('form', 'request', 'content', 'button', 'manager') ) @zope.interface.implementer(interfaces.IButton) class Button(zope.schema.Field): """A simple button in a form.""" accessKey = FieldProperty(interfaces.IButton['accessKey']) actionFactory = FieldProperty(interfaces.IButton['actionFactory']) def __init__(self, *args, **kwargs): # Provide some shortcut ways to specify the name if args: kwargs['__name__'] = args[0] args = args[1:] if 'name' in kwargs: kwargs['__name__'] = kwargs['name'] del kwargs['name'] # Extract button-specific arguments self.accessKey = kwargs.pop('accessKey', None) self.condition = kwargs.pop('condition', None) # Initialize the button super().__init__(*args, **kwargs) def __repr__(self): return '<{} {!r} {!r}>'.format( self.__class__.__name__, self.__name__, self.title) @zope.interface.implementer(interfaces.IImageButton) class ImageButton(Button): """A simple image button in a form.""" image = FieldProperty(interfaces.IImageButton['image']) def __init__(self, image=None, *args, **kwargs): self.image = image super().__init__(*args, **kwargs) def __repr__(self): return '<{} {!r} {!r}>'.format( self.__class__.__name__, self.__name__, self.image) @zope.interface.implementer(interfaces.IButtons) class Buttons(util.SelectionManager): """Button manager.""" managerInterface = interfaces.IButtons prefix = 'buttons' def __init__(self, *args): buttons = [] for arg in args: if zope.interface.interfaces.IInterface.providedBy(arg): for name, button in zope.schema.getFieldsInOrder(arg): if interfaces.IButton.providedBy(button): buttons.append((name, button)) elif self.managerInterface.providedBy(arg): buttons += arg.items() elif interfaces.IButton.providedBy(arg): if not arg.__name__: arg.__name__ = util.createId(arg.title) buttons.append((arg.__name__, arg)) else: raise TypeError("Unrecognized argument type", arg) super().__init__(buttons) @zope.interface.implementer(interfaces.IButtonHandlers) class Handlers: """Action Handlers for a Button-based form.""" def __init__(self): self._registry = adapter.AdapterRegistry() self._handlers = () def addHandler(self, button, handler): """See interfaces.IButtonHandlers""" # Create a specification for the button buttonSpec = util.getSpecification(button) if isinstance(buttonSpec, util.classTypes): buttonSpec = zope.interface.implementedBy(buttonSpec) # Register the handler self._registry.register( (buttonSpec,), interfaces.IButtonHandler, '', handler) self._handlers += ((button, handler),) def getHandler(self, button): """See interfaces.IButtonHandlers""" buttonProvided = zope.interface.providedBy(button) return self._registry.lookup1( buttonProvided, interfaces.IButtonHandler) def copy(self): """See interfaces.IButtonHandlers""" handlers = Handlers() for button, handler in self._handlers: handlers.addHandler(button, handler) return handlers def __add__(self, other): """See interfaces.IButtonHandlers""" if not isinstance(other, Handlers): raise NotImplementedError handlers = self.copy() for button, handler in other._handlers: handlers.addHandler(button, handler) return handlers def __repr__(self): return '<Handlers %r>' % [ handler for button, handler in self._handlers] @zope.interface.implementer(interfaces.IButtonHandler) class Handler: def __init__(self, button, func): self.button = button self.func = func def __call__(self, form, action): return self.func(form, action) def __repr__(self): return '<{} for {!r}>'.format(self.__class__.__name__, self.button) def handler(button): """A decorator for defining a success handler.""" def createHandler(func): handler = Handler(button, func) frame = sys._getframe(1) f_locals = frame.f_locals handlers = f_locals.setdefault('handlers', Handlers()) handlers.addHandler(button, handler) return handler return createHandler def buttonAndHandler(title, **kwargs): # Add the title to button constructor keyword arguments kwargs['title'] = title # Extract directly provided interfaces: provides = kwargs.pop('provides', ()) # Create button and add it to the button manager button = Button(**kwargs) zope.interface.alsoProvides(button, provides) frame = sys._getframe(1) f_locals = frame.f_locals f_locals.setdefault('buttons', Buttons()) f_locals['buttons'] += Buttons(button) # Return the handler decorator return handler(button) @zope.interface.implementer(interfaces.IButtonAction) class ButtonAction(action.Action, submit.SubmitWidget, zope.location.Location): zope.component.adapts(interfaces.IFormLayer, interfaces.IButton) def __init__(self, request, field): action.Action.__init__(self, request, field.title) submit.SubmitWidget.__init__(self, request) self.field = field @property def accesskey(self): return self.field.accessKey @property def value(self): return self.title @property def id(self): return self.name.replace('.', '-') class ImageButtonAction(image.ImageWidget, ButtonAction): zope.component.adapts(interfaces.IFormLayer, interfaces.IImageButton) def __init__(self, request, field): action.Action.__init__(self, request, field.title) submit.SubmitWidget.__init__(self, request) self.field = field @property def src(self): site = hooks.getSite() src = util.toUnicode(zope.traversing.api.traverse( site, '++resource++' + self.field.image, request=self.request)()) return src def isExecuted(self): return self.name + '.x' in self.request.form class ButtonActions(action.Actions): zope.component.adapts( interfaces.IButtonForm, zope.interface.Interface, zope.interface.Interface) def update(self): """See z3c.form.interfaces.IActions.""" # Create a unique prefix. prefix = util.expandPrefix(self.form.prefix) prefix += util.expandPrefix(self.form.buttons.prefix) # Walk through each field, making an action out of it. d = {} d.update(self) for name, button in self.form.buttons.items(): # Step 1: Only create an action for the button, if the condition is # fulfilled. if button.condition is not None and not button.condition( self.form): # Step 1.1: If the action already existed, but now the # condition became false, remove the old action. if name in d: del d[name] continue # Step 2: Get the action for the given button. newButton = True if name in self: buttonAction = self[name] newButton = False elif button.actionFactory is not None: buttonAction = button.actionFactory(self.request, button) else: buttonAction = zope.component.getMultiAdapter( (self.request, button), interfaces.IButtonAction) # Step 3: Set the name on the button buttonAction.name = prefix + name # Step 4: Set any custom attribute values. title = zope.component.queryMultiAdapter( (self.form, self.request, self.content, button, self), interfaces.IValue, name='title') if title is not None: buttonAction.title = title.get() # Step 5: Set the form buttonAction.form = self.form if not interfaces.IFormAware.providedBy(buttonAction): zope.interface.alsoProvides( buttonAction, interfaces.IFormAware) # Step 6: Update the new action buttonAction.update() zope.event.notify(AfterWidgetUpdateEvent(buttonAction)) # Step 7: Add the widget to the manager if newButton: d[name] = buttonAction zope.location.locate(buttonAction, self, name) self.create_according_to_list(d, self.form.buttons.keys()) class ButtonActionHandler(action.ActionHandlerBase): zope.component.adapts( interfaces.IHandlerForm, zope.interface.Interface, zope.interface.Interface, ButtonAction) def __call__(self): handler = self.form.handlers.getHandler(self.action.field) # If no handler is found, then that's okay too. if handler is None: return return handler(self.form, self.action)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/button.py
button.py
================= Forms and Widgets ================= This package provides an implementation for HTML forms and widgets. The goal is to provide a simple API but with the ability to easily customize any data or steps. This document, provides the content of this package's documentation files. The documents are ordered in the way they should be read: - ``form.rst`` [must read] Describes the setup and usage of forms in the most common usages. Some details are provided to the structure of form components. - ``group.rst`` [must read] This document describes how widget groups are implemented within this package and how they can be used. - ``subform.rst`` [must read] Introduces the complexities surrounding sub-forms and details two classes of sub-forms, including code examples. - ``field.rst`` [must read] Provides a comprehensive explanation of the field manager API and how it is to be used. - ``button.rst`` [must read] Provides a comprehensive explanation of the button manager API. It also outlines how to create buttons within schemas and how buttons are converted to actions. - ``zcml.rst`` [must read] Explains the ZCML directives defines by this package, which are designed to make it easier to register new templates without writing Python code. - ``validator.rst`` [advanced users] Validators are used to validate converted form data. This document provides a comprehensive overview of the API and how to use it effectively. - ``widget.rst`` [advanced users] Explains in detail the design goals surrounding widgets and widget managers and how they were realized with the implemented API. - ``contentprovider.rst`` [advanced users] Explains how to mix content providers in forms to render more html around widgets. - ``action.rst`` [advanced users] Explains in detail the design goals surrounding action managers and actions. The execution of actions using action handlers is also covered. The document demonstrates how actions can be created without the use of buttons. - ``value.rst`` [informative] The concept of attribute value adapters is introduced and fully explained. Some motivation for this new and powerful pattern is given as well. - ``datamanager.rst`` [informative] Data managers are resposnsible for accessing and writing the data. While attribute access is the most common case, data managers can also manage other data structures, such as dictionaries. - ``converter.rst`` [informative] Data converters convert data between internal and widget values and vice versa. - ``term.rst`` [informative] Terms are wrappers around sources and vocabularies to provide a common interface for choices in this package. - ``util.rst`` [informative] The ``util`` module provides several helper functions and classes. The components not tested otherwise are explained in this file. - ``adding.rst`` [informative] This module provides a base class for add forms that work with the ``IAdding`` interface. - ``testing.rst`` [informative] The ``testing`` module provides helper functions that make it easier to tet form-based code in unit tests. It also provides components that simplify testing in testbrowser and Selenium. - ``object-caveat.rst`` [informative] Explains the current problems of ObjectWidget. Browser Documentation --------------------- There are several documentation files in the ``browser/`` sub-package. They mainly document the basic widgets provided by the package. - ``README.rst`` [advanced users] This file contains a checklist, ensuring that all fields have a widget. - ``<fieldname>.rst`` Each field name documentation file comprehensively explains the widget and how it is ensured to work properly.
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/README.rst
README.rst
========== Directives ========== Widget template directive ------------------------- Show how we can use the widget template directive. Register the meta configuration for the directive. >>> import sys >>> from zope.configuration import xmlconfig >>> import z3c.form >>> context = xmlconfig.file('meta.zcml', z3c.form) We need a custom widget template >>> import os, tempfile >>> temp_dir = tempfile.mkdtemp() >>> widget_file = os.path.join(temp_dir, 'widget.pt') >>> with open(widget_file, 'w') as file: ... _ = file.write(''' ... <html xmlns="http://www.w3.org/1999/xhtml" ... xmlns:tal="http://xml.zope.org/namespaces/tal" ... tal:omit-tag=""> ... <input type="text" id="" name="" value="" size="" ... tal:attributes="id view/id; ... name view/name; ... size view/size; ... value view/value;" /> ... </html> ... ''') and a interface >>> import zope.interface >>> from z3c.form import interfaces >>> class IMyWidget(interfaces.IWidget): ... """My widget interface.""" and a widget class: >>> from z3c.form.testing import TestRequest >>> from z3c.form.browser import text >>> @zope.interface.implementer(IMyWidget) ... class MyWidget(text.TextWidget): ... pass >>> request = TestRequest() >>> myWidget = MyWidget(request) Make them available under the fake package ``custom``: >>> sys.modules['custom'] = type( ... 'Module', (), ... {'IMyWidget': IMyWidget})() and register them as a widget template within the ``z3c:widgetTemplate`` directive: >>> context = xmlconfig.string(""" ... <configure ... xmlns:z3c="http://namespaces.zope.org/z3c"> ... <z3c:widgetTemplate ... template="%s" ... widget="custom.IMyWidget" ... /> ... </configure> ... """ % widget_file, context=context) Let's get the template >>> import zope.component >>> from z3c.template.interfaces import IPageTemplate >>> template = zope.component.queryMultiAdapter((None, request, None, None, ... myWidget), interface=IPageTemplate, name='input') and check it: >>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile >>> isinstance(template, ViewPageTemplateFile) True Let's use the template within the widget. >>> print(template(myWidget)) <input type="text" value="" /> We normally render the widget which returns the registered template. >>> print(myWidget.render()) <input type="text" value="" /> If the template does not exist, then the widget directive should fail immediately: >>> unknownFile = os.path.join(temp_dir, 'unknown.pt') >>> context = xmlconfig.string(""" ... <configure ... xmlns:z3c="http://namespaces.zope.org/z3c"> ... <z3c:widgetTemplate ... template="%s" ... widget="custom.IMyWidget" ... /> ... </configure> ... """ % unknownFile, context=context) Traceback (most recent call last): ... ConfigurationError: ('No such file', '...unknown.pt') Object Widget template directive -------------------------------- Show how we can use the objectwidget template directive. The big difference between the 'simple' Widget template and the Object Widget directive is that the Object Widget template takes the field's schema into account. That makes it easy to register different widget templates for different sub-schemas. You can use this together with SubformAdapter to get a totally custom subwidget. We need a custom widget template >>> widget_file = os.path.join(temp_dir, 'widget.pt') >>> with open(widget_file, 'w') as file: ... _ = file.write(''' ... <html xmlns="http://www.w3.org/1999/xhtml" ... xmlns:tal="http://xml.zope.org/namespaces/tal" ... tal:omit-tag=""> ... <div class="object-widget" tal:attributes="class view/klass"> ... yeah, this can get complex ... </div> ... </html> ... ''') and a interface >>> class IMyObjectWidget(interfaces.IObjectWidget): ... """My objectwidget interface.""" and a widget class: >>> from z3c.form.browser import object >>> @zope.interface.implementer(IMyObjectWidget) ... class MyObjectWidget(object.ObjectWidget): ... pass >>> request = TestRequest() >>> myObjectWidget = MyObjectWidget(request) >>> from z3c.form.testing import IMySubObject >>> import zope.schema >>> field = zope.schema.Object( ... __name__='subobject', ... title=u'my object widget', ... schema=IMySubObject) >>> myObjectWidget.field = field Make them available under the fake package ``custom``: >>> sys.modules['custom'] = type( ... 'Module', (), ... {'IMyObjectWidget': IMyObjectWidget})() and register them as a widget template within the ``z3c:objectWidgetTemplate`` directive: >>> context = xmlconfig.string(""" ... <configure ... xmlns:z3c="http://namespaces.zope.org/z3c"> ... <z3c:objectWidgetTemplate ... template="%s" ... widget="custom.IMyObjectWidget" ... /> ... </configure> ... """ % widget_file, context=context) Let's get the template >>> template = zope.component.queryMultiAdapter((None, request, None, None, ... myObjectWidget, None), interface=IPageTemplate, name='input') and check it: >>> isinstance(template, ViewPageTemplateFile) True Let's use the template within the widget. >>> print(template(myObjectWidget)) <div class="object-widget">yeah, this can get complex</div> We normally render the widget which returns the registered template. >>> print(myObjectWidget.render()) <div class="object-widget">yeah, this can get complex</div> If the template does not exist, then the widget directive should fail immediately: >>> unknownFile = os.path.join(temp_dir, 'unknown.pt') >>> context = xmlconfig.string(""" ... <configure ... xmlns:z3c="http://namespaces.zope.org/z3c"> ... <z3c:objectWidgetTemplate ... template="%s" ... widget="custom.IMyObjectWidget" ... /> ... </configure> ... """ % unknownFile, context=context) Traceback (most recent call last): ... ConfigurationError: ('No such file', '...unknown.pt') Register a specific template for a schema: We need a custom widget template >>> widgetspec_file = os.path.join(temp_dir, 'widgetspec.pt') >>> with open(widgetspec_file, 'w') as file: ... _ = file.write(''' ... <html xmlns="http://www.w3.org/1999/xhtml" ... xmlns:tal="http://xml.zope.org/namespaces/tal" ... tal:omit-tag=""> ... <div class="object-widget" tal:attributes="class view/klass"> ... this one is specific ... </div> ... </html> ... ''') >>> context = xmlconfig.string(""" ... <configure ... xmlns:z3c="http://namespaces.zope.org/z3c"> ... <z3c:objectWidgetTemplate ... template="%s" ... widget="custom.IMyObjectWidget" ... schema="z3c.form.testing.IMySubObject" ... /> ... </configure> ... """ % widgetspec_file, context=context) Let's get the template >>> template = zope.component.queryMultiAdapter((None, request, None, None, ... myObjectWidget, None), interface=IPageTemplate, name='input') and check it: >>> print(myObjectWidget.render()) <div class="object-widget">this one is specific</div> Cleanup ------- Now we need to clean up the custom module. >>> del sys.modules['custom'] Also let's not leave temporary files lying around >>> import shutil >>> shutil.rmtree(temp_dir)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/zcml.rst
zcml.rst
============= Data Managers ============= For the longest time the way widgets retrieved and stored their values on the actual content/model was done by binding the field to a context and then setting and getting the attribute from it. This has several distinct design shortcomings: 1. The field has too much responsibility by knowing about its implementations. 2. There is no way of redefining the method used to store and access data other than rewriting fields. 3. Finding the right content/model to modify is an implicit policy: Find an adapter for the field's schema and then set the value there. While implementing some real-world projects, we noticed that this approach is too limiting and we often could not use the form framework when we wanted or had to jump through many hoops to make it work for us. For example, if we want to display a form to collect data that does not correspond to a set of content components, we were forced to not only write a schema for the form, but also implement that schema as a class. but all we wanted was a dictionary. For edit-form like tasks we often also had an initial dictionary, which we just wanted modified. Data managers abstract the getting and setting of the data. A data manager is responsible for setting one piece of data in a particular context. >>> from z3c.form import datamanager Attribute Field Manager ----------------------- The most common case, of course, is the management of class attributes through fields. In this case, the data manager needs to know about the context and the field it is managing the data for. >>> import zope.interface >>> import zope.schema >>> class IPerson(zope.interface.Interface): ... name = zope.schema.TextLine( ... title='Name', ... default='<no name>') ... phone = zope.schema.TextLine( ... title='Phone') >>> @zope.interface.implementer(IPerson) ... class Person(object): ... name = '' ... def __init__(self, name): ... self.name = name >>> stephan = Person('Stephan Richter') We can now instantiate the data manager for Stephan's name: >>> nameDm = datamanager.AttributeField(stephan, IPerson['name']) The data manager consists of a few simple methods to accomplish its purpose. Getting the value is done using the ``get()`` or ``query()`` method: >>> nameDm.get() 'Stephan Richter' >>> nameDm.query() 'Stephan Richter' The value can be set using ``set()``: >>> nameDm.set('Stephan "Caveman" Richter') >>> nameDm.get() 'Stephan "Caveman" Richter' >>> stephan.name 'Stephan "Caveman" Richter' If an attribute is not available, ``get()`` fails and ``query()`` returns a default value: >>> phoneDm = datamanager.AttributeField(stephan, IPerson['phone']) >>> phoneDm.get() Traceback (most recent call last): ... AttributeError: 'Person' object has no attribute 'phone' >>> phoneDm.query() <NO_VALUE> >>> phoneDm.query('nothing') 'nothing' A final feature that is supported by the data manager is the check whether a value can be accessed and written. When the context is not security proxied, both, accessing and writing, is allowed: >>> nameDm.canAccess() True >>> nameDm.canWrite() True To demonstrate the behavior for a security-proxied component, we first have to provide security declarations for our person: >>> from zope.security.management import endInteraction >>> from zope.security.management import newInteraction >>> from zope.security.management import setSecurityPolicy >>> import z3c.form.testing >>> endInteraction() >>> newPolicy = z3c.form.testing.SimpleSecurityPolicy() >>> newPolicy.allowedPermissions = ('View', 'Edit') >>> oldpolicy = setSecurityPolicy(newPolicy) >>> newInteraction() >>> from zope.security.checker import Checker >>> from zope.security.checker import defineChecker >>> personChecker = Checker({'name':'View', 'name':'Edit'}) >>> defineChecker(Person, personChecker) We now need to wrap stephan into a proxy: >>> protectedStephan = zope.security.checker.ProxyFactory(stephan) Since we are not logged in as anyone, we cannot acces or write the value: >>> nameDm = datamanager.AttributeField(protectedStephan, IPerson['name']) >>> nameDm.canAccess() False >>> nameDm.canWrite() False Clearly, this also means that ``get()`` and ``set()`` are also shut off: >>> nameDm.get() Traceback (most recent call last): ... Unauthorized: (<Person object at ...>, 'name', 'Edit') >>> nameDm.set('Stephan') Traceback (most recent call last): ... ForbiddenAttribute: ('name', <Person object at ...>) Now we have to setup the security system and "log in" as a user: >>> newPolicy.allowedPermissions = ('View', 'Edit') >>> newPolicy.loggedIn = True The created principal, with which we are logged in now, can only access the attribute: >>> nameDm.canAccess() True >>> nameDm.canWrite() False Thus only the ``get()`` method is allowed: >>> nameDm.get() 'Stephan "Caveman" Richter' >>> nameDm.set('Stephan') Traceback (most recent call last): ... ForbiddenAttribute: ('name', <Person object at ...>) If field's schema is not directly provided by the context, the datamanager will attempt to find an adapter. Let's give the person an address for example: >>> class IAddress(zope.interface.Interface): ... city = zope.schema.TextLine(title='City') >>> @zope.interface.implementer(IAddress) ... class Address(object): ... zope.component.adapts(IPerson) ... def __init__(self, person): ... self.person = person ... @property ... def city(self): ... return getattr(self.person, '_city', None) ... @city.setter ... def city(self, value): ... self.person._city = value >>> zope.component.provideAdapter(Address) Now we can create a data manager for the city attribute: >>> cityDm = datamanager.AttributeField(stephan, IAddress['city']) We can access and write to the city attribute: >>> cityDm.canAccess() True >>> cityDm.canWrite() True Initially there is no value, but of course we can create one: >>> cityDm.get() >>> cityDm.set('Maynard') >>> cityDm.get() 'Maynard' The value can be accessed through the adapter itself as well: >>> IAddress(stephan).city 'Maynard' While we think that implicitly looking up an adapter is not the cleanest solution, it allows us to mimic the behavior of ``zope.formlib``. We think that we will eventually provide alternative ways to accomplish the same in a more explicit way. If we try to set a value that is read-only, a type error is raised: >>> readOnlyName = zope.schema.TextLine( ... __name__='name', ... readonly=True) >>> nameDm = datamanager.AttributeField(stephan, readOnlyName) >>> nameDm.set('Stephan') Traceback (most recent call last): ... TypeError: Can't set values on read-only fields (name=name, class=__builtin__.Person) Finally, we instantiate the data manager with a ``zope.schema`` field. And we can access the different methods like before. >>> nameDm = datamanager.AttributeField( ... stephan, zope.schema.TextLine(__name__ = 'name')) >>> nameDm.canAccess() True >>> nameDm.canWrite() True >>> nameDm.get() 'Stephan "Caveman" Richter' >>> nameDm.query() 'Stephan "Caveman" Richter' >>> nameDm.set('Stephan Richter') >>> nameDm.get() 'Stephan Richter' Dictionary Field Manager ------------------------ Another implementation of the data manager interface is provided by the dictionary field manager, which does not expect an instance with attributes as its context, but a dictionary. It still uses a field to determine the key to modify. >>> personDict = {} >>> nameDm = datamanager.DictionaryField(personDict, IPerson['name']) The datamanager can really only deal with dictionaries and mapping types: >>> import zope.interface.common.mapping >>> import persistent.mapping >>> import persistent.dict >>> @zope.interface.implementer(zope.interface.common.mapping.IMapping) ... class MyMapping(object): ... pass >>> datamanager.DictionaryField(MyMapping(), IPerson['name']) <z3c.form.datamanager.DictionaryField object at ...> >>> datamanager.DictionaryField(persistent.mapping.PersistentMapping(), ... IPerson['name']) <z3c.form.datamanager.DictionaryField object at ...> >>> datamanager.DictionaryField(persistent.dict.PersistentDict(), ... IPerson['name']) <z3c.form.datamanager.DictionaryField object at ...> >>> datamanager.DictionaryField([], IPerson['name']) Traceback (most recent call last): ... ValueError: Data are not a dictionary: <type 'list'> Let's now access the name: >>> nameDm.get() Traceback (most recent call last): ... AttributeError >>> nameDm.query() <NO_VALUE> Initially we get the default value (as specified in the field), since the person dictionariy has no entry. If no default value has been specified in the field, the missing value is returned. Now we set a value and it should be available: >>> nameDm.set('Roger Ineichen') >>> nameDm.get() 'Roger Ineichen' >>> personDict {'name': 'Roger Ineichen'} Since this dictionary is not security proxied, any field can be accessed and written to: >>> nameDm.canAccess() True >>> nameDm.canWrite() True As with the attribute data manager, readonly fields cannot be set: >>> nameDm = datamanager.DictionaryField(personDict, readOnlyName) >>> nameDm.set('Stephan') Traceback (most recent call last): ... TypeError: Can't set values on read-only fields name=name Cleanup ------- We clean up the changes we made in these examples: >>> endInteraction() >>> ignore = setSecurityPolicy(oldpolicy)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/datamanager.rst
datamanager.rst
========= Sub-Forms ========= Traditionally, the Zope community talks about sub-forms in a generic manner without defining their purpose, restrictions and assumptions. When we initially talked about sub-forms for this package, we quickly noticed that there are several classes of sub-forms with different goals. Of course, we need to setup our defaults for this demonstration as well: >>> from z3c.form import testing >>> testing.setupFormDefaults() Class I: The form within the form --------------------------------- This class of sub-forms provides a complete form within a form, including its own actions. When an action of the sub-form is submitted, the parent form usually does not interact with that action at all. The same is true for the reverse; when an action of the parent form is submitted, the sub-form does not react. A classic example for this type of sub-form is uploading an image. The subform allows uploading a file and once the file is uploaded the image is shown as well as a "Delete"/"Clear" button. The sub-form will store the image in the session and when the main form is submitted it looks in the session for the image. This scenario was well supported in ``zope.formlib`` and also does not require special support in ``z3c.form``. Let me show you, how this can be done. In this example, we would like to describe a car and its owner: >>> import zope.interface >>> import zope.schema >>> class IOwner(zope.interface.Interface): ... name = zope.schema.TextLine(title='Name') ... license = zope.schema.TextLine(title='License') >>> class ICar(zope.interface.Interface): ... model = zope.schema.TextLine(title='Model') ... make = zope.schema.TextLine(title='Make') ... owner = zope.schema.Object(title='Owner', schema=IOwner) Let's now implement the two interfaces and create instances, so that we can create edit forms for it: >>> @zope.interface.implementer(IOwner) ... class Owner(object): ... def __init__(self, name, license): ... self.name = name ... self.license = license >>> @zope.interface.implementer(ICar) ... class Car(object): ... def __init__(self, model, make, owner): ... self.model = model ... self.make = make ... self.owner = owner >>> me = Owner('Stephan Richter', 'MA-1231FW97') >>> mycar = Car('Nissan', 'Sentra', me) We define the owner sub-form as we would any other form. The only difference is the template, which should not render a form-tag: >>> import os >>> from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile >>> from z3c.form import form, field, tests >>> templatePath = os.path.dirname(tests.__file__) >>> class OwnerForm(form.EditForm): ... template = ViewPageTemplateFile( ... 'simple_owneredit.pt', templatePath) ... fields = field.Fields(IOwner) ... prefix = 'owner' Next we define the car form, which has the owner form as a sub-form. The car form also needs a special template, since it needs to render the sub-form at some point. For the simplicity of this example, I have duplicated a lot of template code here, but you can use your favorite template techniques, such as METAL macros, viewlets, or pagelets to make better reuse of some code. >>> class CarForm(form.EditForm): ... fields = field.Fields(ICar).select('model', 'make') ... template = ViewPageTemplateFile( ... 'simple_caredit.pt', templatePath) ... prefix = 'car' ... def update(self): ... self.owner = OwnerForm(self.context.owner, self.request) ... self.owner.update() ... super(CarForm, self).update() Let's now instantiate the form and render it: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() >>> carForm = CarForm(mycar, request) >>> carForm.update() >>> print(carForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="car-widgets-model">Model</label> <input type="text" id="car-widgets-model" name="car.widgets.model" class="text-widget required textline-field" value="Nissan" /> </div> <div class="row"> <label for="car-widgets-make">Make</label> <input type="text" id="car-widgets-make" name="car.widgets.make" class="text-widget required textline-field" value="Sentra" /> </div> <fieldset> <legend>Owner</legend> <div class="row"> <label for="owner-widgets-name">Name</label> <input type="text" id="owner-widgets-name" name="owner.widgets.name" class="text-widget required textline-field" value="Stephan Richter" /> </div> <div class="row"> <label for="owner-widgets-license">License</label> <input type="text" id="owner-widgets-license" name="owner.widgets.license" class="text-widget required textline-field" value="MA-1231FW97" /> </div> <div class="action"> <input type="submit" id="owner-buttons-apply" name="owner.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </fieldset> <div class="action"> <input type="submit" id="car-buttons-apply" name="car.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> I can now submit the owner form, which should not submit any car changes I might have made in the form: >>> request = TestRequest(form={ ... 'car.widgets.model': 'BMW', ... 'car.widgets.make': '325', ... 'owner.widgets.name': 'Stephan Richter', ... 'owner.widgets.license': 'MA-97097A87', ... 'owner.buttons.apply': 'Apply' ... }) >>> carForm = CarForm(mycar, request) >>> carForm.update() >>> mycar.model 'Nissan' >>> mycar.make 'Sentra' >>> me.name 'Stephan Richter' >>> me.license 'MA-97097A87' Also, the form should say that the data of the owner has changed: >>> print(carForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="car-widgets-model">Model</label> <input type="text" id="car-widgets-model" name="car.widgets.model" class="text-widget required textline-field" value="BMW" /> </div> <div class="row"> <label for="car-widgets-make">Make</label> <input type="text" id="car-widgets-make" name="car.widgets.make" class="text-widget required textline-field" value="325" /> </div> <fieldset> <legend>Owner</legend> <i>Data successfully updated.</i> <div class="row"> <label for="owner-widgets-name">Name</label> <input type="text" id="owner-widgets-name" name="owner.widgets.name" class="text-widget required textline-field" value="Stephan Richter" /> </div> <div class="row"> <label for="owner-widgets-license">License</label> <input type="text" id="owner-widgets-license" name="owner.widgets.license" class="text-widget required textline-field" value="MA-97097A87" /> </div> <div class="action"> <input type="submit" id="owner-buttons-apply" name="owner.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </fieldset> <div class="action"> <input type="submit" id="car-buttons-apply" name="car.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> The same is true the other way around as well. Submitting the overall form does not submit the owner form: >>> request = TestRequest(form={ ... 'car.widgets.model': 'BMW', ... 'car.widgets.make': '325', ... 'car.buttons.apply': 'Apply', ... 'owner.widgets.name': 'Claudia Richter', ... 'owner.widgets.license': 'MA-123403S2', ... }) >>> carForm = CarForm(mycar, request) >>> carForm.update() >>> mycar.model 'BMW' >>> mycar.make '325' >>> me.name 'Stephan Richter' >>> me.license 'MA-97097A87' Class II: The logical unit -------------------------- In this class of sub-forms, a sub-form is often just a collection of widgets without any actions. Instead, the sub-form must be able to react to the actions of the parent form. A good example of those types of sub-forms is actually the example I chose above. So let's redevelop our example above in a way that the owner sub-form is just a logical unit that shares the action with its parent form. Initially, the example does not look very different, except that we use ``EditSubForm`` as a base class: >>> from z3c.form import subform >>> class OwnerForm(subform.EditSubForm): ... template = ViewPageTemplateFile( ... 'simple_subedit.pt', templatePath) ... fields = field.Fields(IOwner) ... prefix = 'owner' The main form also is pretty much the same, except that a subform takes three constructor arguments, the last one being the parent form: >>> class CarForm(form.EditForm): ... fields = field.Fields(ICar).select('model', 'make') ... template = ViewPageTemplateFile( ... 'simple_caredit.pt', templatePath) ... prefix = 'car' ... ... def update(self): ... super(CarForm, self).update() ... self.owner = OwnerForm(self.context.owner, self.request, self) ... self.owner.update() Rendering the form works as before: >>> request = TestRequest() >>> carForm = CarForm(mycar, request) >>> carForm.update() >>> print(carForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="car-widgets-model">Model</label> <input type="text" id="car-widgets-model" name="car.widgets.model" class="text-widget required textline-field" value="BMW" /> </div> <div class="row"> <label for="car-widgets-make">Make</label> <input type="text" id="car-widgets-make" name="car.widgets.make" class="text-widget required textline-field" value="325" /> </div> <fieldset> <legend>Owner</legend> <div class="row"> <label for="owner-widgets-name">Name</label> <input type="text" id="owner-widgets-name" name="owner.widgets.name" class="text-widget required textline-field" value="Stephan Richter" /> </div> <div class="row"> <label for="owner-widgets-license">License</label> <input type="text" id="owner-widgets-license" name="owner.widgets.license" class="text-widget required textline-field" value="MA-97097A87" /> </div> </fieldset> <div class="action"> <input type="submit" id="car-buttons-apply" name="car.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> The interesting part of this setup is that the "Apply" button calls the action handlers for both, the main and the sub-form: >>> request = TestRequest(form={ ... 'car.widgets.model': 'Ford', ... 'car.widgets.make': 'F150', ... 'car.buttons.apply': 'Apply', ... 'owner.widgets.name': 'Claudia Richter', ... 'owner.widgets.license': 'MA-991723FDG', ... }) >>> carForm = CarForm(mycar, request) >>> carForm.update() >>> mycar.model 'Ford' >>> mycar.make 'F150' >>> me.name 'Claudia Richter' >>> me.license 'MA-991723FDG' Let's now have a look at cases where an error happens. If an error occurs in the parent form, the sub-form is still submitted: >>> request = TestRequest(form={ ... 'car.widgets.model': 'Volvo\n~', ... 'car.widgets.make': '450', ... 'car.buttons.apply': 'Apply', ... 'owner.widgets.name': 'Stephan Richter', ... 'owner.widgets.license': 'MA-991723FDG', ... }) >>> carForm = CarForm(mycar, request) >>> carForm.update() >>> mycar.model 'Ford' >>> mycar.make 'F150' >>> me.name 'Stephan Richter' >>> me.license 'MA-991723FDG' Let's look at the rendered form: >>> print(carForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <i>There were some errors.</i> <ul> <li> Model: <div class="error">Constraint not satisfied</div> </li> </ul> <form action="."> <div class="row"> <b><div class="error">Constraint not satisfied</div> </b><label for="car-widgets-model">Model</label> <input type="text" id="car-widgets-model" name="car.widgets.model" class="text-widget required textline-field" value="Volvo ~" /> </div> <div class="row"> <label for="car-widgets-make">Make</label> <input type="text" id="car-widgets-make" name="car.widgets.make" class="text-widget required textline-field" value="450" /> </div> <fieldset> <legend>Owner</legend> <i>Data successfully updated.</i> <div class="row"> <label for="owner-widgets-name">Name</label> <input type="text" id="owner-widgets-name" name="owner.widgets.name" class="text-widget required textline-field" value="Stephan Richter" /> </div> <div class="row"> <label for="owner-widgets-license">License</label> <input type="text" id="owner-widgets-license" name="owner.widgets.license" class="text-widget required textline-field" value="MA-991723FDG" /> </div> </fieldset> <div class="action"> <input type="submit" id="car-buttons-apply" name="car.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> Now, we know, we know. This might not be the behavior that *you* want. But remember how we started this document. We started with the recognition that there are many classes and policies surrounding subforms. So while this package provides some sensible default behavior, it is not intended to be comprehensive. Let's now create an error in the sub-form, ensuring that an error message occurs: >>> request = TestRequest(form={ ... 'car.widgets.model': 'Volvo', ... 'car.widgets.make': '450', ... 'car.buttons.apply': 'Apply', ... 'owner.widgets.name': 'Claudia\n Richter', ... 'owner.widgets.license': 'MA-991723F12', ... }) >>> carForm = CarForm(mycar, request) >>> carForm.update() >>> mycar.model 'Volvo' >>> mycar.make '450' >>> me.name 'Stephan Richter' >>> me.license 'MA-991723FDG' >>> print(carForm.render()) # doctest: +NOPARSE_MARKUP <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> ... <fieldset> <legend>Owner</legend> <i>There were some errors.</i> <ul> <li> Name: <div class="error">Constraint not satisfied</div> </li> </ul> ... </fieldset> ... </html> If the data did not change, it is also locally reported: >>> request = TestRequest(form={ ... 'car.widgets.model': 'Ford', ... 'car.widgets.make': 'F150', ... 'car.buttons.apply': 'Apply', ... 'owner.widgets.name': 'Stephan Richter', ... 'owner.widgets.license': 'MA-991723FDG', ... }) >>> carForm = CarForm(mycar, request) >>> carForm.update() >>> print(carForm.render()) # doctest: +NOPARSE_MARKUP <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> ... <fieldset> <legend>Owner</legend> <i>No changes were applied.</i> ... </fieldset> ... </html> Final Note: With ``zope.formlib`` and ``zope.app.form`` people usually wrote complex object widgets to handle objects within forms. We never considered this a good way of programming, since one loses control over the layout too easily. Context-free subforms --------------------- Ok, that was easy. But what about writing a form including a subform without a context? Let's show how we can write a form without any context using the sample above. Note, this sample form does not include actions which store the form input. You can store the values like in any other forms using the forms widget method ``self.widgets.extract()`` which will return the form and subform input values. >>> from z3c.form.interfaces import IWidgets >>> class OwnerAddForm(form.EditForm): ... template = ViewPageTemplateFile( ... 'simple_owneredit.pt', templatePath) ... fields = field.Fields(IOwner) ... prefix = 'owner' ... ... def updateWidgets(self): ... self.widgets = zope.component.getMultiAdapter( ... (self, self.request, self.getContent()), IWidgets) ... self.widgets.ignoreContext = True ... self.widgets.update() Next we define the car form, which has the owner form as a sub-form. >>> class CarAddForm(form.EditForm): ... fields = field.Fields(ICar).select('model', 'make') ... template = ViewPageTemplateFile( ... 'simple_caredit.pt', templatePath) ... prefix = 'car' ... ... def updateWidgets(self): ... self.widgets = zope.component.getMultiAdapter( ... (self, self.request, self.getContent()), IWidgets) ... self.widgets.ignoreContext = True ... self.widgets.update() ... ... def update(self): ... self.owner = OwnerAddForm(None, self.request) ... self.owner.update() ... super(CarAddForm, self).update() Let's now instantiate the form and render it. but first set up a simple container which we can use for the add form context: >>> class Container(object): ... """Simple context simulating a container.""" >>> container = Container() Set up a test request: >>> from z3c.form.testing import TestRequest >>> request = TestRequest() And render the form. As you can see, the widgets get rendered without any *real* context. >>> carForm = CarAddForm(container, request) >>> carForm.update() >>> print(carForm.render()) <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action="."> <div class="row"> <label for="car-widgets-model">Model</label> <input type="text" id="car-widgets-model" name="car.widgets.model" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="car-widgets-make">Make</label> <input type="text" id="car-widgets-make" name="car.widgets.make" class="text-widget required textline-field" value="" /> </div> <fieldset> <legend>Owner</legend> <div class="row"> <label for="owner-widgets-name">Name</label> <input type="text" id="owner-widgets-name" name="owner.widgets.name" class="text-widget required textline-field" value="" /> </div> <div class="row"> <label for="owner-widgets-license">License</label> <input type="text" id="owner-widgets-license" name="owner.widgets.license" class="text-widget required textline-field" value="" /> </div> <div class="action"> <input type="submit" id="owner-buttons-apply" name="owner.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </fieldset> <div class="action"> <input type="submit" id="car-buttons-apply" name="car.buttons.apply" class="submit-widget button-field" value="Apply" /> </div> </form> </body> </html> Let's show how we can extract the input values of the form and the subform. First give them some input: >>> request = TestRequest(form={ ... 'car.widgets.model': 'Ford', ... 'car.widgets.make': 'F150', ... 'owner.widgets.name': 'Stephan Richter', ... 'owner.widgets.license': 'MA-991723FDG', ... }) >>> carForm = CarAddForm(container, request) >>> carForm.update() Now get the form values. This is normally done in a action handler: >>> pprint(carForm.widgets.extract()) ({'make': 'F150', 'model': 'Ford'}, ()) >>> pprint(carForm.owner.widgets.extract()) ({'license': 'MA-991723FDG', 'name': 'Stephan Richter'}, ())
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/subform.rst
subform.rst
"""Custom Output Checker """ import doctest as pythondoctest import re import lxml.doctestcompare import lxml.etree from lxml.doctestcompare import LHTMLOutputChecker from zope.testing.renormalizing import RENormalizing class OutputChecker(LHTMLOutputChecker, RENormalizing): """Doctest output checker which is better equippied to identify HTML markup than the checker from the ``lxml.doctestcompare`` module. It also uses the text comparison function from the built-in ``doctest`` module to allow the use of ellipsis. Also, we need to support RENormalizing. """ _repr_re = re.compile( r'^<([A-Z]|[^>]+ (at|object) |[a-z]+ \'[A-Za-z0-9_.]+\'>)') def __init__(self, doctest=pythondoctest, patterns=()): RENormalizing.__init__(self, patterns) self.doctest = doctest # make sure these optionflags are registered doctest.register_optionflag('PARSE_HTML') doctest.register_optionflag('PARSE_XML') doctest.register_optionflag('NOPARSE_MARKUP') def _looks_like_markup(self, s): s = s.replace('<BLANKLINE>', '\n').strip() return (s.startswith('<') and not self._repr_re.search(s)) def text_compare(self, want, got, strip): if want is None: want = "" if got is None: got = "" checker = self.doctest.OutputChecker() return checker.check_output( want, got, self.doctest.ELLIPSIS | self.doctest.NORMALIZE_WHITESPACE) def check_output(self, want, got, optionflags): if got == want: return True for transformer in self.transformers: want = transformer(want) got = transformer(got) return LHTMLOutputChecker.check_output(self, want, got, optionflags) def output_difference(self, example, got, optionflags): want = example.want if not want.strip(): return LHTMLOutputChecker.output_difference( self, example, got, optionflags) # Dang, this isn't as easy to override as we might wish original = want for transformer in self.transformers: want = transformer(want) got = transformer(got) # temporarily hack example with normalized want: example.want = want result = LHTMLOutputChecker.output_difference( self, example, got, optionflags) example.want = original # repeat lines with a diff, otherwise it's wading through mud difflines = [line for line in result.splitlines() if '(got:' in line] if difflines: result += '\nLines with differences:\n' + '\n'.join(difflines) return result def get_parser(self, want, got, optionflags): NOPARSE_MARKUP = self.doctest.OPTIONFLAGS_BY_NAME.get( "NOPARSE_MARKUP", 0) PARSE_HTML = self.doctest.OPTIONFLAGS_BY_NAME.get( "PARSE_HTML", 0) PARSE_XML = self.doctest.OPTIONFLAGS_BY_NAME.get( "PARSE_XML", 0) parser = None if NOPARSE_MARKUP & optionflags: return None if PARSE_HTML & optionflags: parser = lxml.doctestcompare.html_fromstring elif PARSE_XML & optionflags: parser = lxml.etree.XML elif (want.strip().lower().startswith('<html') and got.strip().startswith('<html')): parser = lxml.doctestcompare.html_fromstring elif (self._looks_like_markup(want) and self._looks_like_markup(got)): parser = self.get_default_parser() return parser
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/outputchecker.py
outputchecker.py
__docformat__ = "reStructuredText" import json import sys import zope.component import zope.event import zope.interface import zope.lifecycleevent from zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile from zope.pagetemplate.interfaces import IPageTemplate from zope.publisher import browser from zope.schema.fieldproperty import FieldProperty from z3c.form import button from z3c.form import field from z3c.form import interfaces from z3c.form import util from z3c.form.events import DataExtractedEvent from z3c.form.i18n import MessageFactory as _ def applyChanges(form, content, data): changes = {} for name, field_ in form.fields.items(): # If the field is not in the data, then go on to the next one try: newValue = data[name] except KeyError: continue # If the value is NOT_CHANGED, ignore it, since the widget/converter # sent a strong message not to do so. if newValue is interfaces.NOT_CHANGED: continue if util.changedField(field_.field, newValue, context=content): # Only update the data, if it is different dm = zope.component.getMultiAdapter( (content, field_.field), interfaces.IDataManager) dm.set(newValue) # Record the change using information required later changes.setdefault(dm.field.interface, []).append(name) return changes def extends(*args, **kwargs): frame = sys._getframe(1) f_locals = frame.f_locals if not kwargs.get('ignoreFields', False): f_locals['fields'] = field.Fields() for arg in args: f_locals['fields'] += getattr(arg, 'fields', field.Fields()) if not kwargs.get('ignoreButtons', False): f_locals['buttons'] = button.Buttons() for arg in args: f_locals['buttons'] += getattr(arg, 'buttons', button.Buttons()) if not kwargs.get('ignoreHandlers', False): f_locals['handlers'] = button.Handlers() for arg in args: f_locals['handlers'] += getattr(arg, 'handlers', button.Handlers()) @zope.component.adapter(interfaces.IActionErrorEvent) def handleActionError(event): # Only react to the event, if the form is a standard form. if not (interfaces.IFormAware.providedBy(event.action) and interfaces.IForm.providedBy(event.action.form)): return # If the error was widget-specific, look up the widget. widget = None if isinstance(event.error, interfaces.WidgetActionExecutionError): widget = event.action.form.widgets[event.error.widgetName] # Create an error view for the error. action = event.action form = action.form errorView = zope.component.getMultiAdapter( (event.error.error, action.request, widget, getattr(widget, 'field', None), form, form.getContent()), interfaces.IErrorViewSnippet) errorView.update() # Assign the error view to all necessary places. if widget: widget.error = errorView form.widgets.errors += (errorView,) # If the form supports the ``formErrorsMessage`` attribute, then set the # status to it. if hasattr(form, 'formErrorsMessage'): form.status = form.formErrorsMessage @zope.interface.implementer(interfaces.IForm, interfaces.IFieldsForm) class BaseForm(browser.BrowserPage): """A base form.""" fields = field.Fields() label = None labelRequired = _('<span class="required">*</span>&ndash; required') prefix = 'form.' status = '' template = None widgets = None mode = interfaces.INPUT_MODE ignoreContext = False ignoreRequest = False ignoreReadonly = False ignoreRequiredOnExtract = False def getContent(self): '''See interfaces.IForm''' return self.context def updateWidgets(self, prefix=None): '''See interfaces.IForm''' self.widgets = zope.component.getMultiAdapter( (self, self.request, self.getContent()), interfaces.IWidgets) if prefix is not None: self.widgets.prefix = prefix self.widgets.mode = self.mode self.widgets.ignoreContext = self.ignoreContext self.widgets.ignoreRequest = self.ignoreRequest self.widgets.ignoreReadonly = self.ignoreReadonly self.widgets.update() @property def requiredInfo(self): if self.labelRequired is not None and self.widgets is not None \ and self.widgets.hasRequiredFields: return zope.i18n.translate( self.labelRequired, context=self.request) def extractData(self, setErrors=True): '''See interfaces.IForm''' self.widgets.setErrors = setErrors self.widgets.ignoreRequiredOnExtract = self.ignoreRequiredOnExtract data, errors = self.widgets.extract() zope.event.notify(DataExtractedEvent(data, errors, self)) return data, errors def update(self): '''See interfaces.IForm''' self.updateWidgets() def render(self): '''See interfaces.IForm''' # render content template if self.template is None: template = zope.component.getMultiAdapter((self, self.request), IPageTemplate) return template(self) return self.template() def json(self): data = { 'errors': [ error.message for error in (self.widgets.errors or []) if error.field is None ], 'prefix': self.prefix, 'status': self.status, 'mode': self.mode, 'fields': [widget.json_data() for widget in self.widgets.values()], 'label': self.label or '' } return json.dumps(data) @zope.interface.implementer(interfaces.IDisplayForm) class DisplayForm(BaseForm): mode = interfaces.DISPLAY_MODE ignoreRequest = True @zope.interface.implementer( interfaces.IInputForm, interfaces.IButtonForm, interfaces.IHandlerForm, interfaces.IActionForm) class Form(BaseForm): """The Form.""" buttons = button.Buttons() method = FieldProperty(interfaces.IInputForm['method']) enctype = FieldProperty(interfaces.IInputForm['enctype']) acceptCharset = FieldProperty(interfaces.IInputForm['acceptCharset']) accept = FieldProperty(interfaces.IInputForm['accept']) actions = FieldProperty(interfaces.IActionForm['actions']) refreshActions = FieldProperty(interfaces.IActionForm['refreshActions']) # common string for use in validation status messages formErrorsMessage = _('There were some errors.') @property def action(self): """See interfaces.IInputForm""" return self.request.getURL() @property def name(self): """See interfaces.IInputForm""" return self.prefix.strip('.') @property def id(self): return self.name.replace('.', '-') def updateActions(self): self.actions = zope.component.getMultiAdapter( (self, self.request, self.getContent()), interfaces.IActions) self.actions.update() def update(self): super().update() self.updateActions() self.actions.execute() if self.refreshActions: self.updateActions() def __call__(self): self.update() # Don't render anything if we are doing a redirect if self.request.response.getStatus() in ( 300, 301, 302, 303, 304, 305, 307,): return '' return self.render() @zope.interface.implementer(interfaces.IAddForm) class AddForm(Form): """A field and button based add form.""" ignoreContext = True ignoreReadonly = True _finishedAdd = False @button.buttonAndHandler(_('Add'), name='add') def handleAdd(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return obj = self.createAndAdd(data) if obj is not None: # mark only as finished if we get the new object self._finishedAdd = True def createAndAdd(self, data): obj = self.create(data) zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj)) self.add(obj) return obj def create(self, data): raise NotImplementedError def add(self, object): raise NotImplementedError def nextURL(self): raise NotImplementedError def render(self): if self._finishedAdd: self.request.response.redirect(self.nextURL()) return "" return super().render() @zope.interface.implementer(interfaces.IEditForm) class EditForm(Form): """A simple edit form with an apply button.""" successMessage = _('Data successfully updated.') noChangesMessage = _('No changes were applied.') def applyChanges(self, data): content = self.getContent() changes = applyChanges(self, content, data) # ``changes`` is a dictionary; if empty, there were no changes if changes: # Construct change-descriptions for the object-modified event descriptions = [] for interface, names in changes.items(): descriptions.append( zope.lifecycleevent.Attributes(interface, *names)) # Send out a detailed object-modified event zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent( content, *descriptions)) return changes @button.buttonAndHandler(_('Apply'), name='apply') def handleApply(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return changes = self.applyChanges(data) if changes: self.status = self.successMessage else: self.status = self.noChangesMessage class FormTemplateFactory: """Form template factory.""" def __init__(self, filename, contentType='text/html', form=None, request=None): self.template = ViewPageTemplateFile( filename, content_type=contentType) zope.component.adapter( util.getSpecification(form), util.getSpecification(request))(self) zope.interface.implementer(IPageTemplate)(self) def __call__(self, form, request): return self.template
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/form.py
form.py
__docformat__ = "reStructuredText" import zope.component import zope.interface import zope.schema from zope.interface.common import mapping from zope.security.checker import Proxy from zope.security.checker import canAccess from zope.security.checker import canWrite from zope.security.interfaces import ForbiddenAttribute from z3c.form import interfaces _marker = [] ALLOWED_DATA_CLASSES = [dict] try: import persistent.dict import persistent.mapping ALLOWED_DATA_CLASSES.append(persistent.mapping.PersistentMapping) ALLOWED_DATA_CLASSES.append(persistent.dict.PersistentDict) except ImportError: pass @zope.interface.implementer(interfaces.IDataManager) class DataManager: """Data manager base class.""" class AttributeField(DataManager): """Attribute field.""" zope.component.adapts( zope.interface.Interface, zope.schema.interfaces.IField) def __init__(self, context, field): self.context = context self.field = field @property def adapted_context(self): # get the right adapter or context context = self.context # NOTE: zope.schema fields defined in inherited interfaces will point # to the inherited interface. This could end in adapting the wrong # item. This is very bad because the widget field offers an explicit # interface argument which doesn't get used in Widget setup during # IDataManager lookup. We should find a concept which allows to adapt # the IDataManager use the widget field interface instead of the # zope.schema field.interface, ri if self.field.interface is not None: context = self.field.interface(context) return context def get(self): """See z3c.form.interfaces.IDataManager""" return getattr(self.adapted_context, self.field.__name__) def query(self, default=interfaces.NO_VALUE): """See z3c.form.interfaces.IDataManager""" try: return self.get() except ForbiddenAttribute as e: raise e except AttributeError: return default def set(self, value): """See z3c.form.interfaces.IDataManager""" if self.field.readonly: raise TypeError("Can't set values on read-only fields " "(name=%s, class=%s.%s)" % (self.field.__name__, self.context.__class__.__module__, self.context.__class__.__name__)) # get the right adapter or context setattr(self.adapted_context, self.field.__name__, value) def canAccess(self): """See z3c.form.interfaces.IDataManager""" context = self.adapted_context if isinstance(context, Proxy): return canAccess(context, self.field.__name__) return True def canWrite(self): """See z3c.form.interfaces.IDataManager""" context = self.adapted_context if isinstance(context, Proxy): return canWrite(context, self.field.__name__) return True class DictionaryField(DataManager): """Dictionary field. NOTE: Even though, this data manager allows nearly all kinds of mappings, by default it is only registered for dict, because it would otherwise get picked up in undesired scenarios. If you want to it use for another mapping, register the appropriate adapter in your application. """ zope.component.adapts( dict, zope.schema.interfaces.IField) _allowed_data_classes = tuple(ALLOWED_DATA_CLASSES) def __init__(self, data, field): if (not isinstance(data, self._allowed_data_classes) and not mapping.IMapping.providedBy(data)): raise ValueError("Data are not a dictionary: %s" % type(data)) self.data = data self.field = field def get(self): """See z3c.form.interfaces.IDataManager""" value = self.data.get(self.field.__name__, _marker) if value is _marker: raise AttributeError return value def query(self, default=interfaces.NO_VALUE): """See z3c.form.interfaces.IDataManager""" return self.data.get(self.field.__name__, default) def set(self, value): """See z3c.form.interfaces.IDataManager""" if self.field.readonly: raise TypeError("Can't set values on read-only fields name=%s" % self.field.__name__) self.data[self.field.__name__] = value def canAccess(self): """See z3c.form.interfaces.IDataManager""" return True def canWrite(self): """See z3c.form.interfaces.IDataManager""" return True
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/datamanager.py
datamanager.py
__docformat__ = "reStructuredText" import os import zope.component.zcml import zope.configuration.fields import zope.interface import zope.schema from zope.configuration.exceptions import ConfigurationError from zope.pagetemplate.interfaces import IPageTemplate from zope.publisher.interfaces.browser import IDefaultBrowserLayer from z3c.form import interfaces from z3c.form.i18n import MessageFactory as _ from z3c.form.object import ObjectWidgetTemplateFactory from z3c.form.widget import WidgetLayoutFactory from z3c.form.widget import WidgetTemplateFactory class IWidgetTemplateDirective(zope.interface.Interface): """Parameters for the widget template directive.""" template = zope.configuration.fields.Path( title=_('Layout template.'), description=_('Refers to a file containing a page template (should ' 'end in extension ``.pt`` or ``.html``).'), required=True) mode = zope.schema.ASCIILine( title=_('The mode of the template.'), description=_('The mode is used to define input and display ' 'templates'), default=interfaces.INPUT_MODE, required=False) for_ = zope.configuration.fields.GlobalObject( title=_('View'), description=_('The view for which the template should be available'), default=zope.interface.Interface, required=False) layer = zope.configuration.fields.GlobalObject( title=_('Layer'), description=_('The layer for which the template should be available'), default=IDefaultBrowserLayer, required=False) view = zope.configuration.fields.GlobalObject( title=_('View'), description=_('The view for which the template should be available'), default=zope.interface.Interface, required=False) field = zope.configuration.fields.GlobalObject( title=_('Field'), description=_('The field for which the template should be available'), default=zope.schema.interfaces.IField, required=False) widget = zope.configuration.fields.GlobalObject( title=_('View'), description=_('The widget for which the template should be available'), default=interfaces.IWidget, required=False) contentType = zope.schema.ASCIILine( title=_('Content Type'), description=_('The content type identifies the type of data.'), default='text/html', required=False) class IObjectWidgetTemplateDirective(IWidgetTemplateDirective): schema = zope.configuration.fields.GlobalObject( title=_('Schema'), description=_('The schema of the field for which the template should' ' be available'), default=zope.interface.Interface, required=False) def widgetTemplateDirective( _context, template, for_=zope.interface.Interface, layer=IDefaultBrowserLayer, view=None, field=None, widget=None, mode=interfaces.INPUT_MODE, contentType='text/html'): # Make sure that the template exists template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) factory = WidgetTemplateFactory(template, contentType) zope.interface.directlyProvides(factory, IPageTemplate) # register the template zope.component.zcml.adapter(_context, (factory,), IPageTemplate, (for_, layer, view, field, widget), name=mode) def widgetLayoutTemplateDirective( _context, template, for_=zope.interface.Interface, layer=IDefaultBrowserLayer, view=None, field=None, widget=None, mode=interfaces.INPUT_MODE, contentType='text/html'): # Make sure that the template exists template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) factory = WidgetLayoutFactory(template, contentType) zope.interface.directlyProvides(factory, interfaces.IWidgetLayoutTemplate) # register the template zope.component.zcml.adapter( _context, (factory, ), interfaces.IWidgetLayoutTemplate, (for_, layer, view, field, widget), name=mode) def objectWidgetTemplateDirective( _context, template, for_=zope.interface.Interface, layer=IDefaultBrowserLayer, view=None, field=None, widget=None, schema=None, mode=interfaces.INPUT_MODE, contentType='text/html'): # Make sure that the template exists template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) factory = ObjectWidgetTemplateFactory(template, contentType) zope.interface.directlyProvides(factory, IPageTemplate) # register the template zope.component.zcml.adapter( _context, (factory, ), IPageTemplate, (for_, layer, view, field, widget, schema), name=mode)
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/zcml.py
zcml.py
"""Form and Widget Framework Interfaces """ __docformat__ = "reStructuredText" import zope.i18nmessageid import zope.interface import zope.schema from zope.interface.common import mapping from zope.location.interfaces import ILocation MessageFactory = _ = zope.i18nmessageid.MessageFactory('z3c.form') INPUT_MODE = 'input' DISPLAY_MODE = 'display' HIDDEN_MODE = 'hidden' class NOT_CHANGED: def __repr__(self): return '<NOT_CHANGED>' NOT_CHANGED = NOT_CHANGED() class NO_VALUE: def __repr__(self): return '<NO_VALUE>' NO_VALUE = NO_VALUE() # BBB: the object was renamed to follow common naming style NOVALUE = NO_VALUE # ----[ Layer Declaration ]-------------------------------------------------- class IFormLayer(zope.interface.Interface): """A layer that contains all registrations of this package. It is intended that someone can just use this layer as a base layer when using this package. Since version 2.4.2, this layer doesn't provide IBrowserRequst anymore. This makes it possible to use the IFormLayer within z3c.jsonrpc without to apply the IBrowserRequest into the jsonrpc request. """ # ----[ Generic Manager Interfaces ]----------------------------------------- class IManager(mapping.IEnumerableMapping): """A manager of some kind of items. *Important*: While managers are mappings, the order of the items is assumed to be important! Effectively a manager is an ordered mapping. In general, managers do not have to support a manipulation API. Oftentimes, managers are populated during initialization or while updating. """ class ISelectionManager(IManager): """Managers that support item selection and management. This manager allows one to more carefully specify the contained items. *Important*: The API is chosen in a way, that the manager is still immutable. All methods in this interface must return *new* instances of the manager. """ def __add__(other): """Used for merge two managers.""" def select(*names): """Return a modified instance with an ordered subset of items.""" def omit(*names): """Return a modified instance omitting given items.""" def copy(): """Copy all items to a new instance and return it.""" # ----[ Validators ]--------------------------------------------------------- class IData(zope.interface.Interface): """A proxy object for form data. The object will make all keys within its data attribute available as attributes. The schema that is represented by the data will be directly provided by instances. """ def __init__(schema, data, context): """The data proxy is instantiated using the schema it represents, the data fulfilling the schema and the context in which the data are validated. """ __context__ = zope.schema.Field( title=_('Context'), description=_('The context in which the data are validated.'), required=True) class IValidator(zope.interface.Interface): """A validator for a particular value.""" def validate(value, force=False): """Validate the value. If successful, return ``None``. Otherwise raise an ``Invalid`` error. """ class IManagerValidator(zope.interface.Interface): """A validator that validates a set of data.""" def validate(data): """Validate a dictionary of data. This method is only responsible of validating relationships between the values in the data. It can be assumed that all values have been validated in isolation before. The return value of this method is a tuple of errors that occurred during the validation process. """ def validateObject(obj): """Validate an object. The same semantics as in ``validate()`` apply, except that the values are retrieved from the object and not the data dictionary. """ # ----[ Errors ]-------------------------------------------------------------- class IErrorViewSnippet(zope.interface.Interface): """A view providing a view for an error""" widget = zope.schema.Field( title=_("Widget"), description=_("The widget that the view is on"), required=True) error = zope.schema.Field( title=_('Error'), description=_('Error the view is for.'), required=True) def update(): """Update view.""" def render(): """Render view.""" class IMultipleErrors(zope.interface.Interface): """An error that contains many errors""" errors = zope.interface.Attribute("List of errors") # ----[ Fields ]-------------------------------------------------------------- class IField(zope.interface.Interface): """Field wrapping a schema field used in the form.""" __name__ = zope.schema.TextLine( title=_('Title'), description=_('The name of the field within the form.'), required=True) field = zope.schema.Field( title=_('Schema Field'), description=_('The schema field that is to be rendered.'), required=True) prefix = zope.schema.Field( title=_('Prefix'), description=_('The prefix of the field used to avoid name clashes.'), required=True) mode = zope.schema.Field( title=_('Mode'), description=_('The mode in which to render the widget for the field.'), required=True) interface = zope.schema.Field( title=_('Interface'), description=_('The interface from which the field is coming.'), required=True) ignoreContext = zope.schema.Bool( title=_('Ignore Context'), description=_('A flag, when set, forces the widget not to look at ' 'the context for a value.'), required=False) widgetFactory = zope.schema.Field( title=_('Widget Factory'), description=_('The widget factory.'), required=False, default=None, missing_value=None) showDefault = zope.schema.Bool( title=_('Show default value'), description=_('A flag, when set, makes the widget to display' 'field|adapter provided default values.'), default=True, required=False) class IFields(ISelectionManager): """IField manager.""" def select(prefix=None, interface=None, *names): """Return a modified instance with an ordered subset of items. This extension to the ``ISelectionManager`` allows for handling cases with name-conflicts better by separating field selection and prefix specification. """ def omit(prefix=None, interface=None, *names): """Return a modified instance omitting given items. This extension to the ``ISelectionManager`` allows for handling cases with name-conflicts better by separating field selection and prefix specification. """ class IContentProviders(IManager): """ A content provider manager """ # ----[ Data Managers ]------------------------------------------------------ class IDataManager(zope.interface.Interface): """Data manager.""" def get(): """Get the value. If no value can be found, raise an error """ def query(default=NO_VALUE): """Get the value. If no value can be found, return the default value. If access is forbidden, raise an error. """ def set(value): """Set the value""" def canAccess(): """Can the value be accessed.""" def canWrite(): """Can the data manager write a value.""" # ----[ Data Converters ]---------------------------------------------------- class IDataConverter(zope.interface.Interface): """A data converter from field to widget values and vice versa.""" def toWidgetValue(value): """Convert the field value to a widget output value. If conversion fails or is not possible, a ``ValueError`` *must* be raised. However, this method should effectively never fail, because incoming value is well-defined. """ def toFieldValue(value): """Convert an input value to a field/system internal value. This methods *must* also validate the converted value against the field. If the conversion fails, a ``ValueError`` *must* be raised. If the validation fails, a ``ValidationError`` *must* be raised. """ # value interfaces class IValue(zope.interface.Interface): """A value.""" def get(): """Returns the value.""" # term interfaces class ITerms(zope.interface.Interface): """ """ context = zope.schema.Field() request = zope.schema.Field() form = zope.schema.Field() field = zope.schema.Field() widget = zope.schema.Field() def getTerm(value): """Return an ITitledTokenizedTerm object for the given value LookupError is raised if the value isn't in the source """ def getTermByToken(token): """Return an ITokenizedTerm for the passed-in token. If `token` is not represented in the vocabulary, `LookupError` is raised. """ def getValue(token): """Return a value for a given identifier token LookupError is raised if there isn't a value in the source. """ def __iter__(): """Iterate over terms.""" def __len__(): """Return number of terms.""" def __contains__(value): """Check wether terms containes the ``value``.""" class IBoolTerms(ITerms): """A specialization that handles boolean choices.""" trueLabel = zope.schema.TextLine( title=_('True-value Label'), description=_('The label for a true value of the Bool field.'), required=True) falseLabel = zope.schema.TextLine( title=_('False-value Label'), description=_('The label for a false value of the Bool field.'), required=False) # ----[ Object factory ]----------------------------------------------------- class IObjectFactory(zope.interface.Interface): """Factory that will instantiate our objects for ObjectWidget. It could also pre-populate properties as it gets the values extracted from the form passed in ``value``. """ def __call__(value): """Return a default object created to be populated. """ # ----[ Widget layout template ]---------------------------------------------- class IWidgetLayoutTemplate(zope.interface.Interface): """Widget layout template marker used for render the widget layout. It is important that we don't inherit this template from IPageTemplate. otherwise we will get into trouble since we lookup an IPageTemplate in the widget/render method. """ # ----[ Widgets ]------------------------------------------------------------ class IWidget(ILocation): """A widget within a form""" name = zope.schema.ASCIILine( title=_('Name'), description=_('The name the widget is known under.'), required=True) label = zope.schema.TextLine( title=_('Label'), description=_(''' The widget label. Label may be translated for the request. The attribute may be implemented as either a read-write or read-only property, depending on the requirements for a specific implementation. '''), required=True) mode = zope.schema.ASCIILine( title=_('Mode'), description=_('A widget mode.'), default=INPUT_MODE, required=True) required = zope.schema.Bool( title=_('Required'), description=_('If true the widget should be displayed as required ' 'input.'), default=False, required=True) error = zope.schema.Field( title=_('Error'), description=_('If an error occurred during any step, the error view ' 'stored here.'), required=False) value = zope.schema.Field( title=_('Value'), description=_('The value that the widget represents.'), required=False) template = zope.interface.Attribute('''The widget template''') layout = zope.interface.Attribute('''The widget layout template''') ignoreRequest = zope.schema.Bool( title=_('Ignore Request'), description=_('A flag, when set, forces the widget not to look at ' 'the request for a value.'), default=False, required=False) # ugly thing to remove setErrors parameter from extract setErrors = zope.schema.Bool( title=_('Set errors'), description=_('A flag, when set, the widget sets error messages ' 'on calling extract().'), default=True, required=False) # a bit different from ignoreRequiredOnExtract, because we record # here the fact, but for IValidator, because the check happens there ignoreRequiredOnValidation = zope.schema.Bool( title=_('Ignore Required validation'), description=_("If set then required fields will pass validation " "regardless whether they're filled in or not"), default=False, required=True) showDefault = zope.schema.Bool( title=_('Show default value'), description=_('A flag, when set, makes the widget to display' 'field|adapter provided default values.'), default=True, required=False) def extract(default=NO_VALUE): """Extract the string value(s) of the widget from the form. The return value may be any Python construct, but is typically a simple string, sequence of strings or a dictionary. The value *must not* be converted into a native format. If an error occurs during the extraction, the default value should be returned. Since this should never happen, if the widget is properly designed and used, it is okay to NOT raise an error here, since we do not want to crash the system during an inproper request. If there is no value to extract, the default is to be returned. """ def update(): """Setup all of the widget information used for displaying.""" def render(): """Render the plain widget without additional layout""" def json_data(): """Returns a dictionary for the widget""" def __call__(): """Render a layout template which is calling widget/render""" class ISequenceWidget(IWidget): """Term based sequence widget base. The sequence widget is used for select items from a sequence. Don't get confused, this widget does support to choose one or more values from a sequence. The word sequence is not used for the schema field, it's used for the values where this widget can choose from. This widget base class is used for build single or sequence values based on a sequence which is in most use case a collection. e.g. IList of IChoice for sequence values or IChoice for single values. See also the MultiWidget for build sequence values based on none collection based values. e.g. IList of ITextLine """ noValueToken = zope.schema.ASCIILine( title=_('NO_VALUE Token'), description=_('The token to be used, if no value has been selected.')) terms = zope.schema.Object( title=_('Terms'), description=_('A component that provides the options for selection.'), schema=ITerms) def updateTerms(): """Update the widget's ``terms`` attribute and return the terms. This method can be used by external components to get the terms without having to worry whether they are already created or not. """ class IMultiWidget(IWidget): """None Term based sequence widget base. The multi widget is used for ITuple, IList or IDict if no other widget is defined. Some IList or ITuple are using another specialized widget if they can choose from a collection. e.g. a IList of IChoice. The base class of such widget is the ISequenceWidget. This widget can handle none collection based sequences and offers add or remove values to or from the sequence. Each sequence value get rendered by it's own relevant widget. e.g. IList of ITextLine or ITuple of IInt """ class ISelectWidget(ISequenceWidget): """Select widget with ITerms option.""" prompt = zope.schema.Bool( title=_('Prompt'), description=_('A flag, when set, enables a choice explicitely ' 'requesting the user to choose a value.'), default=False) items = zope.schema.Tuple( title=_('Items'), description=_('A collection of dictionaries containing all pieces of ' 'information for rendering. The following keys must ' 'be in each dictionary: id, value, content, selected')) noValueMessage = zope.schema.Text( title=_('No-Value Message'), description=_('A human-readable text that is displayed to refer the ' 'missing value.')) promptMessage = zope.schema.Text( title=_('Prompt Message'), description=_('A human-readable text that is displayed to refer the ' 'missing value.')) class IOrderedSelectWidget(ISequenceWidget): """Ordered Select widget with ITerms option.""" class ICheckBoxWidget(ISequenceWidget): """Checbox widget.""" class ISingleCheckBoxWidget(ICheckBoxWidget): """Single Checbox widget.""" class IRadioWidget(ISequenceWidget): """Radio widget.""" def renderForValue(value): """Render a single radio button element for a given value. Here the word ``value`` is used in the HTML sense, in other words it is a term token. """ class ISubmitWidget(IWidget): """Submit widget.""" class IImageWidget(IWidget): """Submit widget.""" class IButtonWidget(IWidget): """Button widget.""" class ITextAreaWidget(IWidget): """Text widget.""" class ITextLinesWidget(IWidget): """Text lines widget.""" class ITextWidget(IWidget): """Text widget.""" class IFileWidget(ITextWidget): """File widget.""" class IPasswordWidget(ITextWidget): """Password widget.""" class IObjectWidget(IWidget): """Object widget.""" def setupFields(): """setup fields on the widget, by default taking the fields of self.schema""" class IWidgets(IManager): """A widget manager""" prefix = zope.schema.ASCIILine( title=_('Prefix'), description=_('The prefix of the widgets.'), default='widgets.', required=True) mode = zope.schema.ASCIILine( title=_('Prefix'), description=_('The prefix of the widgets.'), default=INPUT_MODE, required=True) errors = zope.schema.Field( title=_('Errors'), description=_('The collection of errors that occured during ' 'validation.'), default=(), required=True) ignoreContext = zope.schema.Bool( title=_('Ignore Context'), description=_('If set the context is ignored to retrieve a value.'), default=False, required=True) ignoreRequest = zope.schema.Bool( title=_('Ignore Request'), description=_('If set the request is ignored to retrieve a value.'), default=False, required=True) ignoreReadonly = zope.schema.Bool( title=_('Ignore Readonly'), description=_('If set then readonly fields will also be shown.'), default=False, required=True) ignoreRequiredOnExtract = zope.schema.Bool( title=_('Ignore Required validation on extract'), description=_( "If set then required fields will pass validation " "on extract regardless whether they're filled in or not"), default=False, required=True) hasRequiredFields = zope.schema.Bool( title=_('Has required fields'), description=_('A flag set when at least one field is marked as ' 'required'), default=False, required=False) # ugly thing to remove setErrors parameter from extract setErrors = zope.schema.Bool( title=_('Set errors'), description=_('A flag, when set, the contained widgets set error ' 'messages on calling extract().'), default=True, required=False) def update(): """Setup widgets.""" def extract(): """Extract the values from the widgets and validate them. """ def extractRaw(): """Extract the RAW/string values from the widgets and validate them. """ class IFieldWidget(zope.interface.Interface): """Offers a field attribute. For advanced uses the widget will make decisions based on the field it is rendered for. """ field = zope.schema.Field( title=_('Field'), description=_('The schema field which the widget is representing.'), required=True) # ----[ Actions ]------------------------------------------------------------ class ActionExecutionError(Exception): """An error that occurs during the execution of an action handler.""" def __init__(self, error): self.error = error def __repr__(self): return '<{} wrapping {!r}>'.format(self.__class__.__name__, self.error) class WidgetActionExecutionError(ActionExecutionError): """An action execution error that occurred due to a widget value being incorrect.""" def __init__(self, widgetName, error): ActionExecutionError.__init__(self, error) self.widgetName = widgetName class IAction(zope.interface.Interface): """Action""" __name__ = zope.schema.TextLine( title=_('Name'), description=_('The object name.'), required=False, default=None) title = zope.schema.TextLine( title=_('Title'), description=_('The action title.'), required=True) def isExecuted(): """Determine whether the action has been executed.""" class IActionHandler(zope.interface.Interface): """Action handler.""" class IActionEvent(zope.interface.Interface): """An event specific for an action.""" action = zope.schema.Object( title=_('Action'), description=_('The action for which the event is created.'), schema=IAction, required=True) class IActionErrorEvent(IActionEvent): """An action event that is created when an error occurred.""" error = zope.schema.Field( title=_('Error'), description=_('The error that occurred during the action.'), required=True) class IActions(IManager): """A action manager""" executedActions = zope.interface.Attribute( '''An iterable of all executed actions (usually just one).''') def update(): """Setup actions.""" def execute(): """Exceute actions. If an action execution error is raised, the system is notified using the action occurred error; on the other hand, if successful, the action successfull event is sent to the system. """ class IButton(zope.schema.interfaces.IField): """A button in a form.""" accessKey = zope.schema.TextLine( title=_('Access Key'), description=_('The key when pressed causes the button to be pressed.'), min_length=1, max_length=1, required=False) actionFactory = zope.schema.Field( title=_('Action Factory'), description=_('The action factory.'), required=False, default=None, missing_value=None) class IImageButton(IButton): """An image button in a form.""" image = zope.schema.TextLine( title=_('Image Path'), description=_('A relative image path to the root of the resources.'), required=True) class IButtons(ISelectionManager): """Button manager.""" class IButtonAction(IAction, IWidget, IFieldWidget): """Button action.""" class IButtonHandlers(zope.interface.Interface): """A collection of handlers for buttons.""" def addHandler(button, handler): """Add a new handler for a button.""" def getHandler(button): """Get the handler for the button.""" def copy(): """Copy this object and return the copy.""" def __add__(other): """Add another handlers object. During the process a copy of the current handlers object should be created and the other one is added to the copy. The return value is the copy. """ class IButtonHandler(zope.interface.Interface): """A handler managed by the button handlers.""" def __call__(form, action): """Execute the handler.""" # ----[ Forms ]-------------------------------------------------------------- class IHandlerForm(zope.interface.Interface): """A form that stores the handlers locally.""" handlers = zope.schema.Object( title=_('Handlers'), description=_('A list of action handlers defined on the form.'), schema=IButtonHandlers, required=True) class IActionForm(zope.interface.Interface): """A form that stores executable actions""" actions = zope.schema.Object( title=_('Actions'), description=_('A list of actions defined on the form'), schema=IActions, required=True) refreshActions = zope.schema.Bool( title=_('Refresh actions'), description=_('A flag, when set, causes form actions to be ' 'updated again after their execution.'), default=False, required=True) class IContextAware(zope.interface.Interface): """Offers a context attribute. For advanced uses, the widget will make decisions based on the context it is rendered in. """ context = zope.schema.Field( title=_('Context'), description=_('The context in which the widget is displayed.'), required=True) ignoreContext = zope.schema.Bool( title=_('Ignore Context'), description=_('A flag, when set, forces the widget not to look at ' 'the context for a value.'), default=False, required=False) class IFormAware(zope.interface.Interface): """Offers a form attribute. For advanced uses the widget will make decisions based on the form it is rendered in. """ form = zope.schema.Field() class IForm(zope.interface.Interface): """Form""" mode = zope.schema.Field( title=_('Mode'), description=_('The mode in which to render the widgets.'), required=True) ignoreContext = zope.schema.Bool( title=_('Ignore Context'), description=_('If set the context is ignored to retrieve a value.'), default=False, required=True) ignoreRequest = zope.schema.Bool( title=_('Ignore Request'), description=_('If set the request is ignored to retrieve a value.'), default=False, required=True) ignoreReadonly = zope.schema.Bool( title=_('Ignore Readonly'), description=_('If set then readonly fields will also be shown.'), default=False, required=True) ignoreRequiredOnExtract = zope.schema.Bool( title=_('Ignore Required validation on extract'), description=_( "If set then required fields will pass validation " "on extract regardless whether they're filled in or not"), default=False, required=True) widgets = zope.schema.Object( title=_('Widgets'), description=_('A widget manager containing the widgets to be used in ' 'the form.'), schema=IWidgets) label = zope.schema.TextLine( title=_('Label'), description=_('A human readable text describing the form that can be ' 'used in the UI.'), required=False) labelRequired = zope.schema.TextLine( title=_('Label required'), description=_('A human readable text describing the form that can be ' 'used in the UI for rendering a required info legend.'), required=False) prefix = zope.schema.ASCIILine( title=_('Prefix'), description=_('The prefix of the form used to uniquely identify it.'), default='form.') status = zope.schema.Text( title=_('Status'), description=_('The status message of the form.'), default=None, required=False) def getContent(): '''Return the content to be displayed and/or edited.''' def updateWidgets(prefix=None): '''Update the widgets for the form. This method is commonly called from the ``update()`` method and is mainly meant to be a hook for subclasses. Note that you can pass an argument for ``prefix`` to override the default value of ``"widgets."``. ''' def extractData(setErrors=True): '''Extract the data of the form. setErrors: needs to be passed to extract() and to sub-widgets''' def update(): '''Update the form.''' def render(): '''Render the form.''' def json(): '''Returns the form in json format''' class ISubForm(IForm): """A subform.""" class IDisplayForm(IForm): """Mark a form as display form, used for templates.""" class IInputForm(zope.interface.Interface): """A form that is meant to process the input of the form controls.""" action = zope.schema.URI( title=_('Action'), description=_('The action defines the URI to which the form data are ' 'sent.'), required=True) name = zope.schema.TextLine( title=_('Name'), description=_('The name of the form used to identify it.'), required=False) id = zope.schema.TextLine( title=_('Id'), description=_('The id of the form used to identify it.'), required=False) method = zope.schema.Choice( title=_('Method'), description=_('The HTTP method used to submit the form.'), values=('get', 'post'), default='post', required=False) enctype = zope.schema.ASCIILine( title=_('Encoding Type'), description=_('The data encoding used to submit the data safely.'), default='multipart/form-data', required=False) acceptCharset = zope.schema.ASCIILine( title=_('Accepted Character Sets'), description=_('This is a list of character sets the server accepts. ' 'By default this is unknown.'), required=False) accept = zope.schema.ASCIILine( title=_('Accepted Content Types'), description=_('This is a list of content types the server can ' 'safely handle.'), required=False) class IAddForm(IForm): """A form to create and add a new component.""" def create(data): """Create the new object using the given data. Returns the newly created object. """ def add(object): """Add the object somewhere.""" def createAndAdd(data): """Call create and add. This method can be used for keep all attributes internal during create and add calls. On sucess we return the new created and added object. If something fails, we return None. The default handleAdd method will only set the _finishedAdd marker on sucess. """ class IEditForm(IForm): """A form to edit data of a component.""" def applyChanges(data): """Apply the changes to the content component.""" class IFieldsForm(IForm): """A form that is based upon defined fields.""" fields = zope.schema.Object( title=_('Fields'), description=_('A field manager describing the fields to be used for ' 'the form.'), schema=IFields) class IFieldsAndContentProvidersForm(IForm): """A form that is based upon defined fields and content providers""" contentProviders = zope.schema.Object( title=_('Content providers'), description=_( 'A manager describing the content providers to be used for ' 'the form.'), schema=IContentProviders) class IButtonForm(IForm): """A form that is based upon defined buttons.""" buttons = zope.schema.Object( title=_('Buttons'), description=_('A button manager describing the buttons to be used for ' 'the form.'), schema=IButtons) class IGroup(IForm): """A group of fields/widgets within a form.""" class IGroupForm(IForm): """A form that supports groups.""" groups = zope.schema.Tuple( title='Groups', description=('Initially a collection of group classes, which are ' 'converted to group instances when the form is ' 'updated.')) # ----[ Events ]-------------------------------------------------------------- class IWidgetEvent(zope.interface.Interface): """A simple widget event.""" widget = zope.schema.Object( title=_('Widget'), description=_('The widget for which the event was created.'), schema=IWidget) class IAfterWidgetUpdateEvent(IWidgetEvent): """An event sent out after the widget was updated.""" class IDataExtractedEvent(zope.interface.Interface): """Event sent after data and errors are extracted from widgets. """ data = zope.interface.Attribute( "Extracted form data. Usually, the widgets extract field names from " "the request and return a dictionary of field names and field values." ) errors = zope.interface.Attribute( "Tuple of errors providing IErrorViewSnippet." ) form = zope.interface.Attribute("Form instance.")
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/interfaces.py
interfaces.py
"""Data Converters.""" __docformat__ = "reStructuredText" import datetime import decimal import zope.component import zope.i18n.format import zope.interface import zope.publisher.browser import zope.schema from z3c.form import interfaces from z3c.form import util from z3c.form.i18n import MessageFactory as _ @zope.interface.implementer(interfaces.IDataConverter) class BaseDataConverter: """A base implementation of the data converter.""" _strip_value = True # Remove spaces at start and end of text line def __init__(self, field, widget): self.field = field self.widget = widget def _getConverter(self, field): # We rely on the default registered widget, this is probably a # restriction for custom widgets. If so use your own MultiWidget and # register your own converter which will get the right widget for the # used value_type. widget = zope.component.getMultiAdapter((field, self.widget.request), interfaces.IFieldWidget) if interfaces.IFormAware.providedBy(self.widget): # form property required by objectwidget widget.form = self.widget.form zope.interface.alsoProvides(widget, interfaces.IFormAware) converter = zope.component.getMultiAdapter( (field, widget), interfaces.IDataConverter) return converter def toWidgetValue(self, value): """See interfaces.IDataConverter""" if value == self.field.missing_value: return '' return util.toUnicode(value) def toFieldValue(self, value): """See interfaces.IDataConverter""" if self._strip_value and isinstance(value, str): value = value.strip() if value == '': return self.field.missing_value # this is going to burp with `Object is of wrong type.` # if a non-unicode value comes in from the request return self.field.fromUnicode(value) def __repr__(self): return '<{} converts from {} to {}>'.format( self.__class__.__name__, self.field.__class__.__name__, self.widget.__class__.__name__) class FieldDataConverter(BaseDataConverter): """A data converter using the field's ``fromUnicode()`` method.""" zope.component.adapts( zope.schema.interfaces.IField, interfaces.IWidget) def __init__(self, field, widget): super().__init__(field, widget) if not zope.schema.interfaces.IFromUnicode.providedBy(field): fieldName = '' if field.__name__: fieldName = '``%s`` ' % field.__name__ raise TypeError( f'Field {fieldName} of type ``{type(field).__name__}``' ' must provide ``IFromUnicode``.') @zope.component.adapter(interfaces.IFieldWidget) @zope.interface.implementer(interfaces.IDataConverter) def FieldWidgetDataConverter(widget): """Provide a data converter based on a field widget.""" return zope.component.queryMultiAdapter( (widget.field, widget), interfaces.IDataConverter) class FormatterValidationError(zope.schema.ValidationError): message = None def __init__(self, message, value): zope.schema.ValidationError.__init__(self, message, value) self.message = message def doc(self): return self.message class NumberDataConverter(BaseDataConverter): """A general data converter for numbers.""" type = None errorMessage = None def __init__(self, field, widget): super().__init__(field, widget) locale = self.widget.request.locale self.formatter = locale.numbers.getFormatter('decimal') self.formatter.type = self.type def toWidgetValue(self, value): """See interfaces.IDataConverter""" if value == self.field.missing_value: return '' return self.formatter.format(value) def toFieldValue(self, value): """See interfaces.IDataConverter""" if value == '': return self.field.missing_value try: return self.formatter.parse(value) except zope.i18n.format.NumberParseError: raise FormatterValidationError(self.errorMessage, value) class IntegerDataConverter(NumberDataConverter): """A data converter for integers.""" zope.component.adapts( zope.schema.interfaces.IInt, interfaces.IWidget) type = int errorMessage = _('The entered value is not a valid integer literal.') class FloatDataConverter(NumberDataConverter): """A data converter for integers.""" zope.component.adapts( zope.schema.interfaces.IFloat, interfaces.IWidget) type = float errorMessage = _('The entered value is not a valid decimal literal.') class DecimalDataConverter(NumberDataConverter): """A data converter for integers.""" zope.component.adapts( zope.schema.interfaces.IDecimal, interfaces.IWidget) type = decimal.Decimal errorMessage = _('The entered value is not a valid decimal literal.') class CalendarDataConverter(BaseDataConverter): """A special data converter for calendar-related values.""" type = None length = 'short' def __init__(self, field, widget): super().__init__(field, widget) locale = self.widget.request.locale self.formatter = locale.dates.getFormatter(self.type, self.length) def toWidgetValue(self, value): """See interfaces.IDataConverter""" if value is self.field.missing_value: return '' return self.formatter.format(value) def toFieldValue(self, value): """See interfaces.IDataConverter""" if value == '': return self.field.missing_value try: return self.formatter.parse(value) except zope.i18n.format.DateTimeParseError as err: raise FormatterValidationError(err.args[0], value) class DateDataConverter(CalendarDataConverter): """A special data converter for dates.""" zope.component.adapts( zope.schema.interfaces.IDate, interfaces.IWidget) type = 'date' class TimeDataConverter(CalendarDataConverter): """A special data converter for times.""" zope.component.adapts( zope.schema.interfaces.ITime, interfaces.IWidget) type = 'time' class DatetimeDataConverter(CalendarDataConverter): """A special data converter for datetimes.""" zope.component.adapts( zope.schema.interfaces.IDatetime, interfaces.IWidget) type = 'dateTime' class TimedeltaDataConverter(FieldDataConverter): """A special data converter for timedeltas.""" zope.component.adapts( zope.schema.interfaces.ITimedelta, interfaces.IWidget) def __init__(self, field, widget): self.field = field self.widget = widget def toFieldValue(self, value): """See interfaces.IDataConverter""" if value == '': return self.field.missing_value try: daysString, crap, timeString = value.split(' ') except ValueError: timeString = value days = 0 else: days = int(daysString) seconds = [int(part) * 60**(2 - n) for n, part in enumerate(timeString.split(':'))] return datetime.timedelta(days, sum(seconds)) class FileUploadDataConverter(BaseDataConverter): """A special data converter for bytes, supporting also FileUpload. Since IBytes represents a file upload too, this converter can handle zope.publisher.browser.FileUpload object as given value. """ zope.component.adapts( zope.schema.interfaces.IBytes, interfaces.IFileWidget) def toWidgetValue(self, value): """See interfaces.IDataConverter""" return None def toFieldValue(self, value): """See interfaces.IDataConverter""" if value is None or value == '': # When no new file is uploaded, send a signal that we do not want # to do anything special. return interfaces.NOT_CHANGED if isinstance(value, zope.publisher.browser.FileUpload): # By default a IBytes field is used for get a file upload widget. # But interfaces extending IBytes do not use file upload widgets. # Any way if we get a FileUpload object, we'll convert it. # We also store the additional FileUpload values on the widget # before we loose them. self.widget.headers = value.headers self.widget.filename = value.filename try: seek = value.seek read = value.read except AttributeError as e: raise ValueError(_('Bytes data are not a file object'), e) else: seek(0) data = read() if data or getattr(value, 'filename', ''): return data else: return self.field.missing_value else: return util.toBytes(value) class SequenceDataConverter(BaseDataConverter): """Basic data converter for ISequenceWidget.""" zope.component.adapts( zope.schema.interfaces.IField, interfaces.ISequenceWidget) def toWidgetValue(self, value): """Convert from Python bool to HTML representation.""" # if the value is the missing value, then an empty list is produced. if value is self.field.missing_value: return [] # Look up the term in the terms terms = self.widget.updateTerms() try: return [terms.getTerm(value).token] except LookupError: # Swallow lookup errors, in case the options changed. return [] def toFieldValue(self, value): """See interfaces.IDataConverter""" widget = self.widget if not len(value) or value[0] == widget.noValueToken: return self.field.missing_value widget.updateTerms() return widget.terms.getValue(value[0]) class CollectionSequenceDataConverter(BaseDataConverter): """A special converter between collections and sequence widgets.""" zope.component.adapts( zope.schema.interfaces.ICollection, interfaces.ISequenceWidget) def toWidgetValue(self, value): """Convert from Python bool to HTML representation.""" if value is self.field.missing_value: return [] widget = self.widget if widget.terms is None: widget.updateTerms() values = [] for entry in value: try: values.append(widget.terms.getTerm(entry).token) except LookupError: # Swallow lookup errors, in case the options changed. pass return values def toFieldValue(self, value): """See interfaces.IDataConverter""" widget = self.widget if widget.terms is None: widget.updateTerms() collectionType = self.field._type if isinstance(collectionType, tuple): collectionType = collectionType[-1] return collectionType([widget.terms.getValue(token) for token in value]) class TextLinesConverter(BaseDataConverter): """Data converter for ITextLinesWidget.""" zope.component.adapts( zope.schema.interfaces.ISequence, interfaces.ITextLinesWidget) def toWidgetValue(self, value): """Convert from text lines to HTML representation.""" # if the value is the missing value, then an empty list is produced. if value is self.field.missing_value: return '' return '\n'.join(util.toUnicode(v) for v in value) def toFieldValue(self, value): """See interfaces.IDataConverter""" collectionType = self.field._type if isinstance(collectionType, tuple): collectionType = collectionType[-1] if not len(value): return self.field.missing_value valueType = self.field.value_type._type if isinstance(valueType, tuple): valueType = valueType[0] # having a blank line at the end matters, one might want to have a # blank entry at the end, resp. do not eat it once we have one # splitlines ate that, so need to use split now value = value.replace('\r\n', '\n') items = [] for v in value.split('\n'): try: items.append(valueType(v)) except ValueError as err: raise FormatterValidationError(str(err), v) return collectionType(items) class MultiConverter(BaseDataConverter): """Data converter for IMultiWidget.""" zope.component.adapts( zope.schema.interfaces.ISequence, interfaces.IMultiWidget) def toWidgetValue(self, value): """Just dispatch it.""" if value is self.field.missing_value: return [] converter = self._getConverter(self.field.value_type) # we always return a list of values for the widget return [converter.toWidgetValue(v) for v in value] def toFieldValue(self, value): """Just dispatch it.""" if not len(value): return self.field.missing_value converter = self._getConverter(self.field.value_type) values = [converter.toFieldValue(v) for v in value] # convert the field values to a tuple or list collectionType = self.field._type if isinstance(collectionType, tuple): collectionType = collectionType[-1] return collectionType(values) class DictMultiConverter(BaseDataConverter): """Data converter for IMultiWidget.""" zope.component.adapts( zope.schema.interfaces.IDict, interfaces.IMultiWidget) def toWidgetValue(self, value): """Just dispatch it.""" if value is self.field.missing_value: return [] converter = self._getConverter(self.field.value_type) key_converter = self._getConverter(self.field.key_type) # we always return a list of values for the widget return [ (key_converter.toWidgetValue(k), converter.toWidgetValue(v)) for k, v in value.items()] def toFieldValue(self, value): """Just dispatch it.""" if not len(value): return self.field.missing_value converter = self._getConverter(self.field.value_type) key_converter = self._getConverter(self.field.key_type) return { key_converter.toFieldValue(k): converter.toFieldValue(v) for k, v in value} class BoolSingleCheckboxDataConverter(BaseDataConverter): "A special converter between boolean fields and single checkbox widgets." zope.component.adapts( zope.schema.interfaces.IBool, interfaces.ISingleCheckBoxWidget) def toWidgetValue(self, value): """Convert from Python bool to HTML representation.""" if value: return ['selected'] return [] def toFieldValue(self, value): """See interfaces.IDataConverter""" if value and value[0] == 'selected': return True return False
z3c.form
/z3c.form-5.1.tar.gz/z3c.form-5.1/src/z3c/form/converter.py
converter.py