pax_global_header00006660000000000000000000000064141270456450014522gustar00rootroot0000000000000052 comment=b318555e10643fff2b39e11de8306b655cf3d8e3 formencode-2.0.1/000077500000000000000000000000001412704564500136435ustar00rootroot00000000000000formencode-2.0.1/.gitattributes000066400000000000000000000004521412704564500165370ustar00rootroot00000000000000# Set default behaviour, in case users don't have core.autocrlf set. * text=auto *.bat text eol=crlf *.cfg text *.conf text *.css text *.html text *.in text *.ini text *.py text *.rst text *.sh text eol=lf *.txt text *.po text *.pot text *.mo binary *.png binary .git_archival.txt export-subst formencode-2.0.1/.github/000077500000000000000000000000001412704564500152035ustar00rootroot00000000000000formencode-2.0.1/.github/workflows/000077500000000000000000000000001412704564500172405ustar00rootroot00000000000000formencode-2.0.1/.github/workflows/run-tests.yml000066400000000000000000000014631412704564500217330ustar00rootroot00000000000000name: Tests on: push: branches: - main pull_request: {} jobs: build: runs-on: ${{ matrix.os }} timeout-minutes: 10 strategy: fail-fast: false matrix: python-version: [2.7, 3.6, 3.7, 3.8, 3.9, 3.10.0] os: [ubuntu-18.04, macOS-latest, windows-latest] include: # pypy3 on Windows currently fails trying to # run dnspython tests. Moving pypy3 to only test linux. - python-version: pypy3 os: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | make - name: Run tests run: | make ci formencode-2.0.1/.gitignore000066400000000000000000000002731412704564500156350ustar00rootroot00000000000000*.egg *.egg-info .eggs *.pyc *.pyo .tox .coverage coverage/ build dist/ docs/_build # IDE users, please keep your data locally .idea/ .project .pydevproject .settings .tool-versions formencode-2.0.1/CONTRIBUTORS.txt000066400000000000000000000041571412704564500163500ustar00rootroot00000000000000List of Contributors ==================== The below-signed are contributors to a code repository that is part of the project named "FormEncode". Each below-signed contributor has agreed to license their contributions under the MIT license (see LICENSE.txt) as of the date listed by their name. Contributors ------------ - Ian Bicking, 2015-11-14 - Christoph Zwerschke, 2015-11-14 - Christopher Lambacher, 2015-11-14 - Philip Jenvey, 2015-11-14 - Ian Wilson, 2015-11-14 - W. Mark Kubacki, 2015-11-14 - Greg Horvath, 2015-11-14 - Maxim Avanov, 2015-11-14 - Ben Bangert, 2015-11-14 - Matthew Desmarais, 2015-11-14 - Ethan Jucovy, 2015-11-14 - Marc Abramowitz, 2015-11-14 - Benjamin Behringer, 2015-11-14 - Richard Flosi, 2015-11-14 - Juliusz Gonera, 2015-11-14 - John Kraal, 2015-11-14 - Alessandro Molina, 2015-11-14 - Neil Muller, 2015-11-14 - Philipp Spitzer, 2015-11-14 - Vitaly Babiy, 2015-11-14 - David Stanek, 2015-11-14 - Ira, 2015-11-14 - Hong Minhee, 2015-11-14 - Felix Wolfsteller, 2015-11-14 - Keith Yang, 2015-11-14 - Elmer de Looff, 2015-11-14 - Jonathan Vanasco, 2015-11-14 - Luke Tucker, 2015-11-14 - Kevin Dangoor, 2015-11-14 - Mark Lipscombe, 2015-11-14 - Nina Plakalovic, 2015-11-14 - Oleg Broytman, 2015-11-14 - Christophe Benz, 2015-11-14 - Chris George, 2015-11-14 - Philipp Hagemeister, 2015-11-14 - Remco Verhoef, 2015-11-14 - Ryan P. Kelly, 2015-11-14 - Jason R. Coombs, 2015-11-14 - Joshua Bronson, 2015-11-14 - Aleksey Sivokon, 2015-11-14 - Stéphane Raimbault 2015-11-23 - Jason Culverhouse, 2015-11-24 - Michele Cella, 2015-11-30 - Arnaud Fontaine, 2015-12-01 - Bradley Arsenault, 2015-12-05 - Bo Du, 2015-12-28 - Miloš Gavrilov, 2015-12-06 The following people made their contributions under the PSF license and did not respond to requests to approve the change to the MIT license. If you are one of these contributors and you do not want you changes licensed under MIT please contact the project managers and we will work on removing your contributions. - Patrick Hunt - Dennis Muhlestein - Marius Gedminas - Jacob Smullyan formencode-2.0.1/LICENSE.txt000066400000000000000000000021021412704564500154610ustar00rootroot00000000000000Copyright (c) 2015 Ian Bicking and FormEncode Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. formencode-2.0.1/MANIFEST.in000066400000000000000000000000761412704564500154040ustar00rootroot00000000000000exclude .gitignore exclude .gitattributes exclude .travis.yml formencode-2.0.1/Makefile000066400000000000000000000010471412704564500153050ustar00rootroot00000000000000.PHONY: docs init: pip install -e . pip install -r requirements-dev.txt ci: pytest formencode flake8: flake8 --ignore=E501,F401,E128,E402,E731,F821 formencode coverage: pytest --cov-config .coveragerc --verbose --cov-report term --cov-report xml --cov=formencode formencode publish: pip install 'twine>=1.5.0' python setup.py sdist bdist_wheel twine upload dist/* rm -fr build dist .egg FormEncode.egg-info docs: cd docs && make html @echo "\033[95m\n\nBuild successful! View the docs homepage at docs/_build/html/index.html.\n\033[0m" formencode-2.0.1/README.rst000066400000000000000000000015101412704564500153270ustar00rootroot00000000000000FormEncode ========== .. image:: https://github.com/formencode/formencode/actions/workflows/run-tests.yml/badge.svg :target: https://github.com/formencode/formencode/actions :alt: Test Status Introduction ------------ FormEncode is a validation and form generation package. The validation can be used separately from the form generation. The validation works on compound data structures, with all parts being nestable. It is separate from HTTP or any other input mechanism. Documentation ------------- The latest documentation is available at http://www.formencode.org/ Testing ------- Use `pytest formencode` to run the test suite. Use `tox` to run the test suite for all supported Python versions. Changes ------- See the `What's new section of the documentation `_. formencode-2.0.1/docs/000077500000000000000000000000001412704564500145735ustar00rootroot00000000000000formencode-2.0.1/docs/Design.txt000066400000000000000000000201531412704564500165460ustar00rootroot00000000000000+++++++++++++++++ FormEncode Design +++++++++++++++++ :author: Ian Bicking :version: |release| :date: |today| .. contents:: This is a document to describe why FormEncode looks the way it looks, and how it fits into other applications. It also talks some about the false starts I've made. Basic Metaphor ============== FormEncode performs look-before-you-leap validation. The idea being that you check all the data related to an operation, then apply it. This is in contrast to a transactional system, where you just start applying the data and if there's a problem you raise an exception. Someplace else you catch the exception and roll back the transaction. Of course FormEncode works fine with such a system, but because nothing is done until everything validates, you can use this without transactions. FormEncode generally works on primitive types. These are things like strings, lists, dictionaries, integers, etc. This fits in with look-before-you-leap; often your domain objects won't exist until after you apply the user's request, so it's necessary to work on an early form of the data. Also, FormEncode doesn't know anything about your domain objects or classes; it's just easier to keep it this way. Validation only operates on a single "value" at a time. This is Python, collections are easy, and collections are themselves a single "value" made up of many pieces. A "Schema validator" is a validator made up of many subvalidators. By using this single metaphor, without separating the concept of "field" and "form", it is possible to create reusable validators that work on compound structures, to validate "whole forms" instead of just single fields, and to support better validation composition. Also, "validation" and "conversion" are generally applied at the same time. In the documentation this is frequently just referred to as "validation", but anywhere validation can happen, conversion can also happen. Domain Objects ============== These are your objects, specific to your application. I know nothing about them, and cannot know. FormEncode doesn't do anything with these objects, and doesn't try to know anything about them. Validation as directional, not intrinsic ======================================== One false start from earlier projects was an attempt to tie validators into the objects they validate against. E.g., you might have a SQLObject_ class like:: class Address(SQLObject): fname = StringCol(notNull=True) lname = StringCol(notNull=True) mi = StringCol() .. _SQLObject: http://sqlobject.org It is tempting to take the restrictions of the ``Address`` class and automatically come up with a validation schema. This may yet be a viable goal (and to a degree is attainable), but in practical terms validation tends to be both more and less restrictive. Also, validation is contextual; what validation you apply is dependent on the source of the data. Often in an API we are more restrictive than we may be in a user interface, demanding that everything be specified explicitly. In a UI we may assist the user by filling in values on their behalf. The specifics of this depend on the UI and the objects in question. At the same time, we are often more restrictive in a UI. For instance, we may demand that the user enter something that appears to be a valid phone number. But for historical reasons, we may not make that demand for objects that already exist, or we may put in a tight restriction on the UI keeping in mind that it can more easily be relaxed and refined than a restriction in the domain objects or underlying database. Also, we may trust the programmer to use the API in a reasonable way, but we seldom trust user data in the same way. In essence, there is an "inside" and an "outside" to the program. FormEncode is a toolkit for bridging those two areas in a sensible and secure way. The specific way we bridge this depends on the nature of the user interface. An XML-RPC interface can make some assumptions that a GUI cannot make. An HTML interface can typically make even fewer assumptions, including the basic integrity of the input data. It isn't reasonable that the object should know about all means of inputs, and the varying UI requirements of those inputs; user interfaces are volatile, and more art than science, but domain objects work better when they remain stable. For this reason the validation schemas are kept in separate objects. It also didn't work well to annotate domain objects with validation schemas, though the option remains open. This is experimentation that belongs outside of the core of FormEncode, simply because it's more specific to your domain than it is to FormEncode. Two sides, two aspects ====================== FormEncode does both validation and conversion at the same time. Validation necessarily happens with every conversion; for instance, you may want to convert string representation of dates to internal date objects; that conversion can fail if the string representation is malformed. To keep things simple, there's only one operation: conversion. An exception raised means there was an error. If you just want to validate, that's a conversion that doesn't change anything. Similarly, there's two sides to the system, the foreign data and the local data. In Validator the local data is called "python" (meaning, a natural Python data structure), so we convert ``to_python`` and ``from_python``. Unlike some systems, validators explicitly convert in *both* directions. For instance, consider the date conversion. In one form, you may want a date like ``mm/dd/yyyy``. It's easy enough to make the necessary converter; but the date object that the converter produces doesn't know how it's supposed to be formatted for that form. Using ``repr()`` or *any* method that binds an object to its form representation is a bad idea. The converter best knows how to undo its work. So a date converter that expects ``mm/dd/yyyy`` will also know how to turn a datetime into that format. (This becomes even more interesting with compound validators.) Presentation ============ At one time FormEncode included form generation in addition to validation. The form generation worked okay; it was reasonably attractive, and in many ways quite powerful. I might revisit it. But generation is limited. It works *great* at first, then you hit a wall -- you want to make a change, and you just *can't*, it doesn't fit into the automatic generation. There are also many ways to approach the generation; again it's something that is tied to the framework, the presentation layer, and the domain objects, and FormEncode doesn't know anything about those. FormEncode does provide `htmlfill `_. *You* produce the form however you want. Write it out by hand. Use a templating language. Use a form generator. Whatever. Then htmlfill (which specifically understands HTML) fills in the form and any error messages. There are several advantages to this: * Using ``htmlfill``, form generation is easy. You can just think about how to map a form description or model class to simple HTML. You don't have to think about any of the low-level stuff about filling attributes with defaults or past request values. * ``htmlfill`` works with anything that produces HTML. There's zero preference for any particular templating language, or even general style of templating language. * If you do form generation, but it later turns out to be insufficiently flexible, you can put the generated form into your template and extend it there; you'll lose automatic synchronization with your models, but you won't lose any functionality. * Hand-written forms are just as functional as generated forms. Declarative and Imperative ========================== All of the objects -- schemas, repeating elements, individual validators -- can be created imperatively, though more declarative styles often look better (specifically using subclassing instead of construction). You are free to build the objects either way. An example of programmatically building form generation: ``htmlfill_schemabuilder`` looks for special attributes in an HTML form and builds a validation schema from that. formencode-2.0.1/docs/Makefile000066400000000000000000000107761412704564500162460ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/FormEncode.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/FormEncode.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/FormEncode" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/FormEncode" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." formencode-2.0.1/docs/ToDo.txt000066400000000000000000000020471412704564500162040ustar00rootroot00000000000000++++++++++++ Things To Do ++++++++++++ :version: |release| :date: |today| * Add a parallel to Pipe for the Any compound validator that performs validation for each validator to python from left to right. * Make a test fixture for validators, to make testing really easy. * Consider moving htmlfill to ElementTree or another DOM-ish structure, instead of HTMLParser. Or re-implement with another parser but same interface. * Generate Javascript for validators, for client-side validation (when possible). * Relatedly, test and give recipes for Ajax-ish validation, when fully client-side validation doesn't work. * Better tests for ``htmlfill`` and ``htmlfill_schemabuilder``. * Include at least one good documented form generator. Consider including rich widgets (Javascript). * Seperate out ``doctest_xml_compare``, maybe (useful in any doctested web test). * Make ``doctest_xml_compare`` work with wildcards/ellipses. Maybe with non-XHTML. * Some more ways to build validation. Validation from docstrings or method signatures. formencode-2.0.1/docs/Validator.txt000066400000000000000000000626611412704564500172740ustar00rootroot00000000000000.. comment (set Emacs mode) -*- doctest -*- >>> import sys >>> import formencode +++++++++++++++++++++ FormEncode Validation +++++++++++++++++++++ :author: Ian Bicking :version: |release| :date: |today| .. contents:: Introduction ============ Validation (which encompasses conversion as well) is the core function of FormEncode. FormEncode really tries to *encode* the values from one source into another (hence the name). So a Python structure can be encoded in a series of HTML fields (a flat dictionary of strings). A HTML form submission can in turn be turned into a the original Python structure. Using Validation ================ In FormEncode validation and conversion happen simultaneously. Frequently you cannot convert a value without ensuring its validity, and validation problems can occur in the middle of conversion. The basic metaphor for validation is **to_python** and **from_python**. In this context "Python" is meant to refer to "here" -- the trusted application, your own Python objects. The "other" may be a web form, an external database, an XML-RPC request, or any data source that is not completely trusted or does not map directly to Python's object model. :meth:`to_python` is the process of taking external data and preparing it for internal use, :meth:`from_python` generally reverses this process (:meth:`from_python` is usually the less interesting of the pair, but provides some important features). The core of this validation process is two methods and an exception:: >>> import formencode >>> from formencode import validators >>> validator = validators.Int() >>> validator.to_python("10") 10 >>> validator.to_python("ten") Traceback (most recent call last): ... Invalid: Please enter an integer value ``"ten"`` isn't a valid integer, so we get a :class:`formencode.Invalid` exception. Typically we'd catch that exception, and use it for some sort of feedback. Like: .. comment (fake raw_input): >>> raw_input_input = [] >>> def raw_input(prompt): ... value = raw_input_input.pop(0) ... print ('%s%s' % (prompt, value)) ... return value >>> raw_input_input.extend(['ten', '10']) >>> raw_input_input.extend(['bob', 'bob@nowhere.com']) >>> import six >>> if not six.PY2: # Python 3 ... input = raw_input :: >>> def get_integer(): ... while 1: ... try: ... value = raw_input('Enter a number: ') ... return validator.to_python(value) ... except formencode.Invalid as e: ... print (e) ... >>> get_integer() Enter a number: ten Please enter an integer value Enter a number: 10 10 We can also generalize this kind of function:: >>> def valid_input(prompt, validator): ... while 1: ... try: ... value = raw_input(prompt) ... return validator.to_python(value) ... except formencode.Invalid as e: ... print (e) >>> valid_input('Enter your email: ', validators.Email()) Enter your email: bob An email address must contain a single @ Enter your email: bob@nowhere.com 'bob@nowhere.com' :class:`Invalid` exceptions generally give a good, user-readable error message about the problem with the input. Using the exception gets more complicated when you use compound data structures (dictionaries and lists), which we'll talk about later__. .. __: `Compound Validators`_ We'll talk more about these individual validators later, but first we'll talk about more complex validation than just integers or individual values. .. _Schemas: Available Validators -------------------- There's lots of validators. The best way to read about the individual validators available in the :mod:`formencode.validators` module is to read about :mod:`~formencode.validators` and :mod:`~formencode.national`. Compound Validators ------------------- While validating single values is useful, it's only a *little* useful. Much more interesting is validating a set of values. This is called a *Schema*. For instance, imagine a registration form for a website. It takes the following fields, with restrictions: * ``first_name`` (not empty) * ``last_name`` (not empty) * ``email`` (not empty, valid email) * ``username`` (not empty, unique) * ``password`` (reasonably secure) * ``password_confirm`` (matches password) There's a couple validators that aren't part of FormEncode, because they'll be specific to your application:: >>> # We don't really have a database of users, so we'll fake it: >>> usernames = [] >>> class UniqueUsername(formencode.FancyValidator): ... def _convert_to_python(self, value, state): ... if value in usernames: ... raise formencode.Invalid( ... 'That username already exists', ... value, state) ... return value .. note:: The class :class:`formencode.FancyValidator` is the superclass for most validators in FormEncode, and it provides a number of useful features that most validators can use -- for instance, you can pass ``strip=True`` into any of these validators, and they'll strip whitespace from the incoming value before any other validation. This overrides the internal :meth:`_convert_to_python()` method: :class:`formencode.FancyValidator` adds a number of extra features, and then calls the internal :meth:`_convert_to_python` method, which is the method you'll typically write. Contrary to the external method :meth:`to_python`, its only concern is the conversion part, not the validation part. If further validation is necessary, this can be done in two other internal methods, either :meth:`_validate_python()` or :meth:`_validate_other()`. We will give an example for that later. When a validator finds an error, it raises an exception (:class:`formencode.Invalid`), with the error message and the value and "state" objects. We'll talk about state_ later. Here's the other custom validator, that checks passwords against words in the standard Unix word file:: >>> class SecurePassword(formencode.FancyValidator): ... words_filename = '/usr/share/dict/words' ... def _convert_to_python(self, value, state): ... f = open(self.words_filename) ... lower = value.strip().lower() ... for line in f: ... if line.strip().lower() == lower: ... raise formencode.Invalid( ... 'Please do not base your password on a ' ... 'dictionary term', value, state) ... return value And here's a schema:: >>> class Registration(formencode.Schema): ... first_name = validators.ByteString(not_empty=True) ... last_name = validators.ByteString(not_empty=True) ... email = validators.Email(resolve_domain=True) ... username = formencode.All(validators.PlainText(), ... UniqueUsername()) ... password = SecurePassword() ... password_confirm = validators.ByteString() ... chained_validators = [validators.FieldsMatch( ... 'password', 'password_confirm')] Like any other validator, a :class:`Registration` instance will have the :meth:`to_python` and :meth:`from_python` methods. The input should be a dictionary (or a Paste MultiDict), with keys like ``"first_name"``, ``"password"``, etc. The validators you give as attributes will be applied to each of the values of the dictionary. *All* the values will be validated, so if there are multiple invalid fields you will get information about all of them. Most validators (anything that subclasses :class:`formencode.FancyValidator`) will take a certain standard set of constructor keyword arguments. See :class:`formencode.api.FancyValidator` for more -- here we use ``not_empty=True``. Another notable validator is :class:`formencode.compound.All` -- this is a *compound validator* -- that is, it's a validator that takes validators as input. Schemas are one example; in this case :class:`All` takes a list of validators and applies each of them in turn. :class:`formencode.compound.Any` is its compliment, that uses the first passing validator in its list. .. _pre_validators: .. _chained_validators: :attr:`chained_validators` are validators that are run on the entire dictionary after other validation is done (:attr:`pre_validators` are applied before the schema validation). chained_validators will also allow for multiple validators to fail and report to the error_dict so, for example, if you have an email_confirm and a password_confirm fields and use FieldsMatch on both of them as follows: >>> chained_validators = [ ... validators.FieldsMatch('password', ... 'password_confirm'), ... validators.FieldsMatch('email', ... 'email_confirm')] This will leave the error_dict with both password_confirm and email_confirm error keys, which is likely the desired behavior for web forms. Since a :class:`formencode.schema.Schema` is just another kind of validator, you can nest these indefinitely, validating dictionaries of dictionaries. .. _SimpleFormValidator: Another way to do simple validation of a complete form is with :class:`formencode.schema.SimpleFormValidator`. This class wraps a simple function that you write. For example:: >>> from formencode.schema import SimpleFormValidator >>> def validate_state(value_dict, state, validator): ... if value_dict.get('country', 'US') == 'US': ... if not value_dict.get('state'): ... return {'state': 'You must enter a state'} >>> ValidateState = SimpleFormValidator(validate_state) >>> ValidateState.to_python({'country': 'US'}, None) Traceback (most recent call last): ... Invalid: state: You must enter a state The :func:`validate_state` function (or any validation function) returns any errors in the form (or it may raise Invalid directly). It can also modify the :obj:`value_dict` dictionary directly. When it returns None this indicates that everything is valid. You can use this with a :class:`Schema` by putting :class:`ValidateState` in :attr:`pre_validators` (all validation will be done before the schema's validation, and if there's an error the schema won't be run). Or you can put it in :attr:`chained_validators` and it will be run *after* the schema. If the schema fails (the values are invalid) then :class:`ValidateState` will not be run, unless you set :attr:`validate_partial_form` to True (like ``ValidateState = SimpleFormValidator(validate_state, validate_partial_form=True)``. If you validate a partial form you should be careful that you handle missing keys and other possibly-invalid values gracefully. .. _ForEach: You can also validate lists of items using :class:`formencode.foreach.ForEach`. For example, let's say we have a form where someone can edit a list of book titles. Each title has an associated book ID, so we can match up the new title and the book it is for:: >>> class BookSchema(formencode.Schema): ... id = validators.Int() ... title = validators.ByteString(not_empty=True) >>> validator = formencode.ForEach(BookSchema()) The :obj:`validator` we've created will take a list of dictionaries as input (like ``[{"id": "1", "title": "War & Peace"}, {"id": "2", "title": "Brave New World"}, ...]``). It applies the :class:`BookSchema` to each entry, and collects any errors and reraises them. Of course, when you are validating input from an HTML form you won't get well structured data like this (we'll talk about that later__). .. __: `HTTP/HTML Form Input`_ Writing Your Own Validator -------------------------- We gave a brief introduction to creating a validator earlier (:class:`UniqueUsername` and :class:`SecurePassword`). We'll discuss that a little more. Here's a more complete implementation of :class:`SecurePassword`:: >>> import re >>> class SecurePassword(validators.FancyValidator): ... ... min = 3 ... non_letter = 1 ... letter_regex = re.compile(r'[a-zA-Z]') ... ... messages = { ... 'too_few': 'Your password must be longer than %(min)i ' ... 'characters long', ... 'non_letter': 'You must include at least %(non_letter)i ' ... 'characters in your password', ... } ... ... def _convert_to_python(self, value, state): ... # _convert_to_python gets run before _validate_python. ... # Here we strip whitespace off the password, because leading ... # and trailing whitespace in a password is too elite. ... return value.strip() ... ... def _validate_python(self, value, state): ... if len(value) < self.min: ... raise formencode.Invalid(self.message("too_few", state, ... min=self.min), ... value, state) ... non_letters = self.letter_regex.sub('', value) ... if len(non_letters) < self.non_letter: ... raise formencode.Invalid(self.message("non_letter", state, ... non_letter=self.non_letter), ... value, state) With all validators, any arguments you pass to the constructor will be used to set instance variables. So :class:`SecureValidator(min=5)` will be a minimum-five-character validator. This makes it easy to also subclass other validators, giving different default values. Unlike the previous implementation we use the already mentioned :meth:`_validate_python` method, which is another internal method :class:`FancyValidator` allows us to override. :meth:`_validate_python` doesn't have any return value, it simply raises an exception if it needs to. It validates the value *after* it has been converted (by :meth:`_convert_to_python`). :meth:`_validate_other` validates before conversion, but that's usually not that useful. The external method :meth:`to_python` cares about the extra features such as the :attr:`if_empty` parameter, and uses the internal methods to do the actual conversion and validation; first it calls :meth:`_validate_other`, then :meth:`_convert_to_python` and at last :meth:`_validate_python`. The use of ``self.message(...)`` is meant to make the messages easy to format for different environments, and replacable (with translations, or simply with different text). Each message should have an identifier (``"min"`` and ``"non_letter"`` in this example). The keyword arguments to :meth:`message` are used for message substitution. See Messages_ for more. Other Validator Usage --------------------- Validators use instance variables to store their customization information. You can use either subclassing or normal instantiation to set these. These are (effectively) equivalent:: >>> plain = validators.Regex(regex='^[a-zA-Z]+$') >>> # and... >>> class Plain(validators.Regex): ... regex = '^[a-zA-Z]+$' >>> plain = Plain() You can actually use classes most places where you could use an instance; :meth:`.to_python()` and :meth:`.from_python()` will create instances as necessary, and many other methods are available on both the instance and the class level. When dealing with nested validators this class syntax is often easier to work with, and better displays the structure. .. _FancyValidator: There are several options that most validators support (including your own validators, if you subclass from :class:`formencode.FancyValidator`): :attr:`if_empty`: If set, then this value will be returned if the input evaluates to false (empty list, empty string, None, etc), but not the 0 or False objects. This only applies to ``.to_python()``. :attr:`not_empty`: If true, then if an empty value is given raise an error. (Both with ``.to_python()`` and also ``.from_python()`` if ``.validate_python`` is true). :attr:`strip`: If true and the input is a string, strip it (occurs before empty tests). :attr:`if_invalid`: If set, then when this validator would raise Invalid during ``.to_python()``, instead return this value. :attr:`if_invalid_python`: If set, when the Python value (converted with ``.from_python()``) is invalid, this value will be returned. :attr:`accept_python`: If True (the default), then ``._validate_python()`` and ``._validate_other()`` will not be called when ``.from_python()`` is used. :attr:`if_missing`: Typically when a field is missing the schema will raise an error. In that case no validation is run -- so things like ``if_invalid`` won't be triggered. This special attribute (if set) will be used when the field is missing, and no error will occur. (``None`` or ``()`` are common values) State ----- All the validators receive a magic, somewhat meaningless ``state`` argument (which defaults to ``None``). It's used for very little in the validation system as distributed, but is primarily intended to be an object you can use to hook your validator into the context of the larger system. For instance, imagine a validator that checks that a user is permitted access to some resource. How will the validator know which user is logged in? State! Imagine you are localizing it, how will the validator know the locale? State! Whatever else you need to pass in, just put it in the state object as an attribute, then look for that attribute in your validator. Also, during compound validation (a :class:`formencode.schema.Schema` or :class:`formencode.foreach.ForEach`) the state (if not None) will have more instance variables added to it. During a :class:`Schema` (dictionary) validation the instance variable ``key`` and ``full_dict`` will be added -- ``key`` is the current key (i.e., validator name), and ``full_dict`` is the rest of the values being validated. During a :class:`ForEeach` (list) validation, ``index`` and ``full_list`` will be set. Invalid Exceptions ------------------ Besides the string error message, :class:`formencode.Invalid` exceptions have a few other instance variables: :attr:`value`: The input to the validator that failed. :attr:`state`: The associated state_. :attr:`msg`: The error message (``str(exc)`` returns this) :attr:`error_list`: If the exception happened in a ``ForEach`` (list) validator, then this will contain a list of ``Invalid`` exceptions. Each item from the list will have an entry, either None for no error, or an exception. :attr:`error_dict`: If the exception happened in a :class:`Schema` (dictionary) validator, then this will contain :class:`Invalid` exceptions for each failing field. Passing fields not be included in this dictionary. :meth:`.unpack_errors()`: This method returns a set of lists and dictionaries containing strings, for each error. It's an unpacking of :attr:`error_list`, :attr:`error_dict` and :attr:`msg`. If you get an Invalid exception from a :class:`Schema`, you probably want to call this method on the exception object. .. _Messages: Messages, Language Customization -------------------------------- All of the error messages can be customized. Each error message has a key associated with it, like ``"too_few"`` in the registration example. You can overwrite these messages by using you own ``messages = {"key": "text"}`` in the class statement, or as an argument when you call a class. Either way, you do not lose messages that you do not define, you only overwrite ones that you specify. Messages often take arguments, like the number of characters, the invalid portion of the field, etc. These are always substituted as a dictionary (by name). So you will use placeholders like ``%(key)s`` for each substitution. This way you can reorder or even ignore placeholders in your new message. When you are creating a validator, for maximum flexibility you should use the :meth:`message` method, like:: messages = { 'key': 'my message (with a %(substitution)s)', } def _validate_python(self, value, state): raise formencode.Invalid(self.message('key', state, substitution='apples'), value, state) Localization of Error Messages (i18n) ------------------------------------- When a failed validation occurs FormEncode tries to output the error message in the appropriate language. For this it uses the standard `gettext `_ mechanism of python. To translate the message in the appropriate message FormEncode has to find a gettext function that translates the string. The language to be translated into and the used domain is determined by the found gettext function. To serve a standard translation mechanism and to enable custom translations it looks in the following order to find a gettext (``_``) function: 1. method of the :obj:`state` object 2. function :func:`__builtin__._`. This function is only used when:: Validator.use_builtin_gettext == True #True is default 3. formencode builtin :func:`_stdtrans` function for standalone use of FormEncode. The language to use is determined out of the locale system (see gettext documentation). Optionally you can also set the language or the domain explicitly with the function:: formencode.api.set_stdtranslation(domain="FormEncode", languages=["de"]) Formencode comes with a Domain ``FormEncode`` and the corresponding messages in the directory ``localedir/language/LC_MESSAGES/FormEncode.mo`` 4. Custom gettext function and addtional parameters If you use a custom gettext function and you want FormEncode to call your function with additional parameters you can set the dictionary:: Validators.gettextargs Available languages ~~~~~~~~~~~~~~~~~~~ All available languages are distributed with the code. You can see the currently available languages in the source under the directory ``formencode/i18n``. If your language is not present yet, please consider contributing a translation (where ```` is you language code):: $ svn co http://svn.formencode.org/FormEncode/trunk/ $ easy_install Babel $ python setup.py init_catalog -l $ emacs formencode/i18n//LC_MESSAGES/FormEncode.po # or whatever # editor you prefer make the translation $ python setup.py compile_catalog -l Then test, and send the PO and MO files to g...@gregor-horvath.com. See also `the Python internationalization documents `_. Optionally you can also add a test of your language to ``tests/test_i18n.py``. An Example of a language test:: ne = formencode.validators.NotEmpty() [...] def test_de(): _test_lang("de", u"Bitte einen Wert eingeben") And the test for your language:: def test_(): _test_lang("", u"") HTTP/HTML Form Input -------------------- The validation expects nested data structures; specifically :class:`formencode.schema.Schema` and :class:`formencode.foreach.ForEach` deal with these structures well. HTML forms, however, do not produce nested structures -- they produce flat structures with keys (input names) and associated values. Validator includes the module :mod:`formencode.variabledecode`, which allows you to encode nested dictionary and list structures into a flat dictionary. To do this it uses keys with ``"."`` for nested dictionaries, and ``"-int"`` for (ordered) lists. So something like: +--------------------+--------------------+ | key | value | +====================+====================+ | names-1.fname | John | +--------------------+--------------------+ | names-1.lname | Doe | +--------------------+--------------------+ | names-2.fname | Jane | +--------------------+--------------------+ | names-2.lname | Brown | +--------------------+--------------------+ | names-3 | Tim Smith | +--------------------+--------------------+ | action | save | +--------------------+--------------------+ | action.option | overwrite | +--------------------+--------------------+ | action.confirm | yes | +--------------------+--------------------+ Will be mapped to:: {'names': [{'fname': "John", 'lname': "Doe"}, {'fname': "Jane", 'lname': 'Brown'}, "Tim Smith"], 'action': {None: "save", 'option': "overwrite", 'confirm': "yes"}, } In other words, ``'a.b'`` creates a dictionary in ``'a'``, with ``'b'`` as a key (and if ``'a'`` already had a value, then that value is associated with the key ``None``). Lists are created with keys with ``'-int'``, where they are ordered by the integer (the integers are used for sorting, missing numbers in a sequence are ignored). :class:`formencode.variabledecode.NestedVariables` is a validator that decodes and encodes dictionaries using this algorithm. You can use it with a Schema's `pre_validators`_ attribute. Of course, in the example we use the data is rather eclectic -- for instance, Tim Smith doesn't have his name separated into first and last. Validators work best when you keep lists homogeneous. Also, it is hard to access the ``'action'`` key in the example; storing the options (action.option and action.confirm) under another key would be preferable. formencode-2.0.1/docs/_static/000077500000000000000000000000001412704564500162215ustar00rootroot00000000000000formencode-2.0.1/docs/_static/bitbucket.png000066400000000000000000000143651412704564500207140ustar00rootroot00000000000000PNG  IHDR(6%\tEXtSoftwareAdobe ImageReadyqe<IDATx\yWy{:ce$2fl`12>kÑB8TjPRJ-I ckKdi%VǞ9~ꙝݝ*hL^um H;JUp:" @ /%bMz"IZ7%MZ$-X{sK*Ӓc.J*F~4kI,f6J3^ynبO<1up"h-CDH8cм2~+=_~<ρ>oY}]L[w.^h\ @[,"D;Ef U`W  dȤk#b1?^:s̟~ĝg#ƒE#<mBuUKtm5nuP.[V׃ᰵx(,9ڨBI36!tXLC2l)uoR)XbܱܤNUBG;j{wv{EkӮ?_uS_scUw>5ue̴OY8wv Dk]YdI$ lfŀQ1)`|j#g896m1,&hR %f=[w[ B?p+u2Ԥ LxAZCmws[串ejߙ7u1栗[sXљ95" -U,ްk{RX2#k"8JU'b MF. D6L‘.l&ڤa& /)Có1 3V,x7Z_w䆫'[@._˳a]oUd[ũlZSϣ*R\;7GG\אR4%DTN ~i;O%W1 TJ%Q(ΕQX,aH&Ռ77,<~*lK3Nnq4}B0>ڷᕰZ}ƨ_v0ǍOy6mW_{-:.30y Ώf"ϵɭR%0y/-ԯ=ݲM "2yl9(qkAm 5]iرg:5D#^ѨL?/wwP?Uo&ܔ9ykwOMuÉ+n@̘B8>NA8%8vEMq5zX+zxd3A)`BG'\=Ma%XYt`BdM 8gpv䔓'np1pWw1&v#{]{ercS1[YfUW2 鸍֘ ](w垦 ?!pz^%3FDqމ`PuMlD5qzdǏ@r)1b+Zon-R^) EP {Em߻Y0*{:W9HwJXg8a-ӎk,N8toR3F'8:>!}bS'µhX  <iH\MrHqQ,{>y{xQ; AqO0#1fEiumZp{Z~~ Kgʩh?"@ yelA+a٨x,@)Z|blՐl5pj W>dA%zx -i6߼ "-]["miQP%d.)42".q1uL78йbF= XyCtg)6c`B!X"`nC}c^6 jEl,ޔ/zZbS@ʚr$LkpMHIQ^N#JJ?H"LQhB:Al Z;މvtҹd*yUlI/03땈 ~`=y'ʻ:bmC+H#i5kPʅ^+:1X_ 8CG3x7uYJە)~~#||vxPWn.q Ŋw&u߲,a[؜+q[./;A򨠿\#*5pAV[2y+<Ų#u"*b:[kYO? ~^ XfG"v6gm7@"Ԏ}#o]o6h! R}hb7fWb ֫B@_^w׭B8;G^oP9u׽8̫1~&5J|:q "-~ 2ӅJ |\N_ſx=t=/5G_ yvjL(UoO~˕M+IwUX\u"IR#u"X}MjFL4#D!C6Jf`]Ǖ #\M֦Ǐwܝ/` ;xy¹!RL؋qA֢p<Ι侔x>KU' ǁ(~6ϲzkbX,bƍoXMB"(Pn-a h5j\H{8;Gl5CmĐ;&~פw^~n7n)9Ќo+5$J-`5EځSYsp= $ xt&k^Jٖ,WC "ppح*z G.?vgGdv! F޶H,~Yt T)T*D-+}]9}^@`8*UM\RNa{j2ױ6T+dD SLf <5Fۼxs'=R>#WJ`7lyn; @rrWc@myz:p 2@H=d(5z&(OѱSsDr>?h͗R{ QېSՕlA^9Ecm)/-MD 4!E3l61z[s+;%Sƥ\KzM4o:NtGe,\~<8s1ģ[t2KѣZ7ύޱΛ:]`[87O!1 х2$=N#&y*^gwt鞽!0K'!D"Z4S*}G'Hx|s]>~++rN1|'˷jB;")۴Gtx/>7(JrHx/1`Wffsdlt+mb*UEpWg6WkJ*p|{?C9V$A~|M>#K{LX .`=Ί fc4f▫4ͽM͙+j#yjo~ ^p߽>J5L=4ΩqH{S8աk>Ņ9U="Px˥ xAccW"o2y!,T:}K3mxXW A6D;ӆ/|{`ON&eF CyNe *iX_6=Q[:D)^H~}+{ }sd3p]b**TT`JvW#ʙpUy 8_.ɪy s_RDz!޻Ly6G},d&9}/)n'־L>@ 1"LCS\)sS}Ќ+ghNdE~gV4X RZB᪭v-(Wf1zt?4FNO#65]5Ma#U1|uQmNT]^kxG}ᆙk_'Hj=M{UH A|@:aݯ+xb8GOBݦcʦ7f~7o=ưFۚm13>g?ß>/طx^Wy1E2z)j7=y,:BNFVm>B|߫ 13W»ƇrsWMb. PJ/'MEۀ/% A)B^-D 9 .Um&.`P۩ yd1o} BST6譞xI><$??CmM^5^|Js@y~a<5hY"az8pd_yb+kAw6Ϋ>O₈AnaTB 3{tD=ĽX\`!ۥBP(Evy{478C ׻PV^Cy_v9ӄ|[^ñ!Gi jFpv!Oqԅ6Թ]m(Όy>lFcaK"Z*[3PCOۖ~~r 5~kF? \ /U 9BEms#/ Ut^h\kBɑွ- &{^ i=aR ^5T/1EXWxJ6ȇD5WNѲJS5̅duWz$KET믿/˵DZ-^l$;'Kż;2Pi{=?JZ[˴^9]TlQĻd9S$BcE_^.7\R?DB#uv\{CKK׺H&۞%c״ G4P)J|уC?R!S. _(~1Bi}ʫW >6*VhN"wʣ?kaO)Wك[Fx3e.<kK_ 0q工IENDB`formencode-2.0.1/docs/_static/github.png000066400000000000000000000061421412704564500202140ustar00rootroot00000000000000PNG  IHDRZ( E^tIME  57H% pHYs  gAMA a IDATx[ UU^UI4_XED)BBTF>0MFZeW=>dRHt$5K@(CfqϹþ9:kZk}F$ ӤƸάG}`C轡vy879,wXpÎkp|ڊRo~wĬ Gj4}^dM8}GV^w7x@['IƸFŹhpx£i|Gׇ0/ϛ{ռvwI$n^wx{ys=m;uwwéE&nH"7J2๗& ~1f*i>Ƶ( bg&j$FmJc.𼘾$Gu4i5wіp{mocyp*Kd>:=SipK07Ix%2jfEnT'^iu9ռ teMQ:s)\D }ZaovV19|U)_C>BI[o4U"g{>D=#HԴ!&-R0_txDaIUwyѭّÖ.}Ye}OOh v>%sFh]c$ԪN_FylL Bl㞯(ɱ~Li e`y_w3zkoHдf4+x{"{qB4!:oqHo+h{vUl_+%d 6@K;D^H~-tvDi|sxAb{9{W }R8|l%pI%D(vL~09xf>sDfETK$#DMA3vZg QV9=E4n)1 ufKdBIPlPB0H+h2!7 +m#YM?( H>{EcV2/ߐ(cSC?m=>iM.bŀ,nE>tӶmȳX5mcܯVdFJv] ^τrヤ(1ĻP.b5i/fl}A5ţm[Mr lvv[ yB (U+%J(״ %\\:M] zЄڷy+ U5$=)ս!'%JΊEEݴj+bmSDJ uxVWv>瘶•?ĴU+ <)a3A<08ad6 m&bT{#G1X+Oh!fϏ8giu)Q_Ce9] }y'<#X4hQx3(ȉ"н|͐摵Ij$44i VNb[V gF:uT7c8}h"dL2ZNud9]Ըs5,'*dx(MUPdfM} VCO /z!v[s 15eOd}ԽxTڰԻ$jKZ Ivo% i~9H -mHR4GI?;۷-fIe+XerE nP:HWbk$AA -r@VhcdK(8۞ ܀/_{- +Q:d4GO~ nR[!kIV9<i=@5\a)a(& BȇuoT-kFAx83@@`7(=:lfG,Gs۝q{oEB>;IJ@[S DwۓЧ,cyM(+Ẇh/&K o8B@Գw_pr-K1K 'φAwL{Q7v@K +<Pi?hh(n@j\ AqD\JvzmymNS_\ᵡ`N|4m+*i}q[pv)RN Ӥ"x/@%"uꦞ6(w*fW~~y)q:X֝3(sRw" bDz §9*GܯyT~x)mr͈%>D)p89DeY~ʆ"Jȼ`p%̡^ウIx|B0[_ TvI1GIp$5Z۳¥D]H)*)|BbTH* &K& ~80"*z8;?`pyh{x)ߟ Z } PEYz=DكրD t'&g{4ѓ4 &F1%A.gT4Prs$KH kf9z%{ 9) ۯ%:ʾ+$Lj JxBN)K5Xh"D7{I7C;q02JsBoh[A|9ӍY7V8 _aȰVS4 5椁KGw*m.,;A1M"Tf^`N(',I(<_M{?NJN(68|488 D[AP-4֏d:TpN2#;?X7N92~l-?/,3oq`,辌p2UN+g{<:=9`K]xL:y2]D:#!Jy/|`{a]KceM\B9>j$* `p6+ZJIENDB`formencode-2.0.1/docs/_static/sourceforge.png000066400000000000000000000041071412704564500212540ustar00rootroot00000000000000PNG  IHDR(\CtIME4= pHYsiTSgAMA aCPLTE:::,,,mmmIIIVVV򫫫,,+XXX䞞ݍ%%%uuu|||ȭOONHHGfffAA@PPP333WWWFFGVVU::9]]^rrrlllɫ^^^nnm+++Ӹг趶222___qqqTTTqpoOOPeefxvvĬ浴@@?ppoݥUUUFFFBBB|{zŦxww򈇇SRRFFE{{zsrrױ``_eee}}}ΰ궶Ұݜ>IDATxW wU&5]BBiI%'djFUT(J ee%E|TXП}Vi=xsd}ܻ3wf :f!lmxJE M: hp+_mWh2J Miдa9L1[U}$ȍCRi9JP"I $ o)@$%)ݤJˮNn @ٲG )[ZQbL#ŽRi uj3FbmWIa.+Id4 ʩ/DĴJ ҖHW0.tk8Y#OVF*O2)U~)` &C21.1z`T0y1vƾ&c#}P(<#9 ufڼ8T{]Lؤ 2Id {{u9lt~ʏ@ր?yKcq s=d%Bp4? b/ơE<')( ESdxHZe|p׋,]uwƾQ:V*ux@x1ބ |GfH)qHa=Ce53;$lwwxB! U.y/̨ Nn4-3/^z!r9|e12BrrioYi2o;C~g=GfT?L,t[ x7! cE+u;AݞSB׋q Db$.wYͭt4]Іk<(\Rײtrew 7zn+aU?F(RM7CR8h'9o鍬N$^qy&h#qz\&1,AcZg8=ŔK/7ƿ/fsդ ϏDgDIENDB`formencode-2.0.1/docs/_themes/000077500000000000000000000000001412704564500162175ustar00rootroot00000000000000formencode-2.0.1/docs/_themes/old/000077500000000000000000000000001412704564500167755ustar00rootroot00000000000000formencode-2.0.1/docs/_themes/old/static/000077500000000000000000000000001412704564500202645ustar00rootroot00000000000000formencode-2.0.1/docs/_themes/old/static/old.css000066400000000000000000000137071412704564500215640ustar00rootroot00000000000000/* :Author: David Goodger, Ian Bicking, Christoph Zwerschke :Contact: ianb@colorstudy.com :date: 2011/08/30 :version: 1.4 :copyright: This stylesheet has been placed in the public domain. A modification of the default cascading style sheet (v.1.3) for the HTML output of Docutils. */ body { font-family: Arial, sans-serif; background-color: #fff; } em, i { /* Typically serif fonts have much nicer italics */ font-family: Times New Roman, Times, serif; } li { list-style-type: circle; } a.target { color: blue; } a.toc-backref, a.headerlink { text-decoration: none; color: black; } a.headerlink { padding-left: 0.4em; padding-right: 0.4em; } a.toc-backref:hover { background-color: inherit; } a:hover { background-color: #ccc; } cite { font-style: normal; font-family: monospace; font-weight: bold; } dd { margin-bottom: 0.5em; } div.abstract { margin: 2em 5em; } div.abstract p.topic-title { font-weight: bold; text-align: center; } div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning { background-color: #ccc; width: 40%; border: medium outset; padding: 3px; float: right } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: #c00; font-weight: bold; font-family: sans-serif; text-align: center; background-color: #999; display: block; margin: 0; } div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title { font-weight: bold; font-family: sans-serif; text-align: center; background-color: #999; display: block; margin: 0; } div.dedication { margin: 2em 5em; text-align: center; font-style: italic; } div.dedication p.topic-title { font-weight: bold; font-style: normal; } div.figure { margin-left: 2em; } div.footer, div.header { font-size: smaller; } div.system-messages { margin: 5em; } div.system-messages h1 { color: red; } div.system-message { border: medium outset; padding: 1em; } div.system-message p.system-message-title { color: red; font-weight: bold; } div.topic { margin: 2em; } h1, h2, h3, h4, h5, h6 { font-family: Helvetica, Arial, sans-serif; border: thin solid black; /* This makes the borders rounded on Mozilla, which pleases me */ -moz-border-radius: 8px; padding: 4px; } h1 { background-color: #449; color: #fff; border: medium solid black; } h1 a.toc-backref, h2 a.toc-backref { color: #fff; } h1 a.headerlink { color: #449; } h2 { background-color: #666; color: #fff; border: medium solid black; } h2 a.headerlink { color: #666; } h3, h4, h5, h6 { background-color: #ccc; color: #000; } h3 a.toc-backref, h4 a.toc-backref, h5 a.toc-backref, h6 a.toc-backref { color: #000; } h1.title { text-align: center; background-color: #449; color: #fff; border: thick solid black; -moz-border-radius: 20px; } h2.subtitle { text-align: center; } hr { width: 75%; } ol.simple, ul.simple { margin-bottom: 1em; } ol.arabic { list-style: decimal; } ol.loweralpha { list-style: lower-alpha; } ol.upperalpha { list-style: upper-alpha; } ol.lowerroman { list-style: lower-roman; } ol.upperroman { list-style: upper-roman; } p.caption { font-style: italic; } p.credits { font-style: italic; font-size: smaller; } p.first { margin-top: 0; } p.label { white-space: nowrap; } p.topic-title { font-weight: bold; } pre.address { margin-bottom: 0; margin-top: 0; font-family: serif; font-size: 100%; } pre.line-block { font-family: serif; font-size: 100%; } pre.literal-block, pre.doctest-block { margin-left: 2em; margin-right: 2em; background-color: #eee; border: thin black solid; padding: 5px; } span.classifier { font-family: sans-serif; font-style: oblique; } span.classifier-delimiter { font-family: sans-serif; font-weight: bold; } span.interpreted { font-family: sans-serif; } span.option-argument { font-style: italic; } span.pre { white-space: pre; } span.problematic { color: red; } table { margin-top: 0.5em; margin-bottom: 0.5em; } table.citation { border-left: solid thin gray; padding-left: 0.5ex } table.docinfo { margin: 2em 4em; } table.footnote { border-left: solid thin black; padding-left: 0.5ex; } td, th { padding-left: 0.5em; padding-right: 0.5em; vertical-align: top; } td > p:first-child, th > p:first-child { margin-top: 0em; } th.docinfo-name, th.field-name { font-weight: bold; text-align: left; white-space: nowrap; } h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt { font-size: 100%; } code, tt { color: #006; } ul.auto-toc { list-style-type: none; } /***************************************** * Doctest embedded examples *****************************************/ span.doctest-url { background-color: #eee; border-top: 2px outset #666; border-left: 2px outset #666; border-right: 2px outset #666; padding: 0.25em; } div.doctest-example { border: outset 5px #666; background-color: #eee; font-family: default; padding: 0.5em; } div.doctest-example h1 { background-color: inherit; border: none; color: inherit; font-family: default; } div.doctest-example tt { color: inherit; } div.doctest-status { background-color: #060; color: #fff; } span.doctest-header { background-color: #ccc; font-family: monospace; } pre.doctest-errors { border: none; background-color: #333; color: #600; } div.source-code { background-color: #000; border: inset #999 3px; overflow: auto; } pre.source-code { background-color: #000; border: inset #999 3px; overflow: auto; font-family: monospace; color: #fff; } span.source-filename { background-color: #000; border-top: 2px outset #999; border-left: 2px outset #999; border-right: 2px outset #999; padding: 0.25em; color: #fff } div.related h3 { display: none } div.related ul li { display: inline; } formencode-2.0.1/docs/_themes/old/theme.conf000066400000000000000000000001361412704564500207460ustar00rootroot00000000000000# Old FormEncode theme [theme] inherit = basic stylesheet = old.css pygments_style = sphinx formencode-2.0.1/docs/community.txt000066400000000000000000000015241412704564500173620ustar00rootroot00000000000000FormEncode Community ++++++++++++++++++++ Discussion takes place on the mailing list, formencode-discuss@lists.sf.net: * `Subcribe `__ * `Archives `__ Updates to the repository are emailed to the (inaccurately named) mailing list formencode-cvs@lists.sf.net: * `Subscribe `__ The repository can be checked out with:: git clone git://github.com/formencode/formencode.git Note: the SourceForge CVS repository and svn.colorstudy.com Subversion repositories and bitbucket Mercurial repositories are out of date and no longer used. Bugs can be reported in the `github bug tracker `_. formencode-2.0.1/docs/conf.py000066400000000000000000000160611412704564500160760ustar00rootroot00000000000000from __future__ import absolute_import # -*- coding: utf-8 -*- # # FormEncode documentation build configuration file, created by # sphinx-quickstart on Tue Aug 30 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage'] # Add any paths that contain templates here, relative to this directory. #templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.txt' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'FormEncode' copyright = u'2008-2012, Ian Bicking and Contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '2.0.0' from pkg_resources import get_distribution release = get_distribution('formencode').version # for example take major/minor version = '.'.join(release.split('.')[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. #html_theme = 'old' html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'FormEncode_doc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'FormEncode.tex', u'FormEncode Documentation', u'Ian Bicking', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'formencode', u'FormEncode Documentation', [u'Ian Bicking'], 1) ] formencode-2.0.1/docs/download.txt000066400000000000000000000005711412704564500171460ustar00rootroot00000000000000Downloads +++++++++ The most current downloads are always available on the `FormEncode Cheese Shop Page `_. The repository can be checked out with:: git clone git://github.com/formencode/formencode.git Or you can download the repository as a zip file from here:: https://github.com/formencode/formencode/zipball/masterformencode-2.0.1/docs/history.txt000066400000000000000000000034201412704564500170340ustar00rootroot00000000000000On Intentions And History ========================= :author: Ian Bicking I'm the author of FunFormKit_, a form generation and validation package for Webware_. I considered FunFormKit (FFK) to be a very powerful and complete package, with features that few other form validation packages for Python had (as to other languages, I haven't researched enough to know). It supported repeating and compound fields (which most packages do not), and had a very expressive validation system. However, this is not FFK. In fact, it is a deprecation of FFK and does not provide backward compatibility. Why? Probably the biggest problem was that FFK didn't support compound and repeating fields. Adding them made everything *much* more difficult -- it was a sort of clever hack (maybe not even clever), and the result was very hard for anyone else to understand. Ultimately hard for me to understand. Ontop of this was a structure that had too much coupling. Testing was difficult. I only came to like unit testing after FFK had gone through several revisions. FFK was not made with testability in mind. It can be hard to add later. Also, I wanted to use pieces of FFK without the entire framework. Validation without the form generation was the biggest one. Alternate kinds of forms also interested me -- making it easier to do highly granual templating, or non-HTML/HTTP forms. Alternate data sources, like SQL or XMLRPC, also seemed important. All of these were not easy within the interfaces that FFK used. So... FormEncode! FormEncode takes a lot of ideas from FFK, and a lot of the code is just modified FFK code. All of it is reviewed and actively inserted into FormEncode, I'm not transferring anything wholesale. .. _FunFormKit: http://funformkit.sf.net .. _Webware: http://webware.sf.net formencode-2.0.1/docs/htmlfill.txt000066400000000000000000000064111412704564500171510ustar00rootroot00000000000000.. comment (set Emacs mode) -*- doctest -*- >>> import formencode ++++++++ htmlfill ++++++++ :author: Ian Bicking .. contents:: Introduction ============ :mod:`formencode.htmlfill` is a library to fill out forms, both with default values and error messages. It's like a template library, but more limited, and it can be used with the output from other templates. It has no prerequesites, and can be used without any other parts of FormEncode. Usage ===== The basic usage is something like this:: >>> from formencode import htmlfill >>> form = '' >>> defaults = {'fname': 'Joe'} >>> htmlfill.render(form, defaults) '' The parser looks for HTML input elements (including ``select`` and ``textarea``) and fills in the defaults. The quintessential way to use this would be with a form submission that had errors -- you can return the form to the user with the values they entered, in addition to errors. See :func:`formencode.htmlfill.render` for more. Errors ------ Since errors are a common issue, this also has some features for filling the form with error messages. It defines two special tags for this purpose: ````: This tag is eliminated completely if there is no error for the named field. Otherwise the error is passed through the given formatter (``"default"`` if no ``format`` attribute is given). ``...``: If the named field doesn't have an error, everything between the tags will be eliminated. Use ``name="not field_name"`` to invert the behavior (i.e., include text only if there are no errors for the field). Formatters are functions that take the error text as a single argument. (In the future they may take extra arguments as well.) They return a string that is inserted into the template. By default, the formatter returns:: (message)
In addition to explicit error tags, any leftover errors will be placed immediately above the associated input field. The default formatters available to you: ``default``: HTML-quotes the error and wraps it in ```` ``none``: Puts the error message in with no quoting of any kind. This allows you to put HTML in the error message, but might also expose you to cross-site scripting vulnerabilities. ``escape``: HTML-quotes the error, but doesn't wrap it in anything. ``escapenl``: HTML-quotes the error, and translates newlines to ``
`` ``ignore``: Swallows the error, emitting nothing. You can use this when you never want an error for a field to display. Valid form templates -------------------- When you call ``parser.close()`` (also called by ``render()``) the parser will check that you've fully used all the defaults and errors that were given in the constructor if you pass in ``use_all_keys=True``. If there are leftover fields an ``AssertionError`` will be raised. In most cases, htmlfill tries to keep the template the way it found it, without reformatting it too much. If HTMLParser_ chokes on the code, so will htmlfill. .. _HTMLParser: http://docs.python.org/library/htmlparser.html formencode-2.0.1/docs/i18n.txt000066400000000000000000000020231412704564500161100ustar00rootroot00000000000000FormEncode Internationalization (gettext) +++++++++++++++++++++++++++++++++++++++++ :author: Gregor Horvath 2006 There are different translation options available: Domain "FormEncode" ^^^^^^^^^^^^^^^^^^^ for standalone use of FormEncode. The language to use is determined out of the local system (see gettext documentation http://docs.python.org/lib/node733.html). Optionally you can also set the language or the domain explicitly with the function. example: formencode.api.set_stdtranslation(domain="FormEncode", languages=["de"]) The mo files are located in the i18n subdirectory of the formencode installation. state._ ^^^^^^^ A custom _ gettext function provided as attribute of the state object. __builtins__._ ^^^^^^^^^^^^^^ A custom _ gettext function provided in the builtin namespace. This function is only used when: Validator.use_builtin_gettext == True (True is default) Without translation ^^^^^^^^^^^^^^^^^^^ If no translation mechanism is found a fallback returns the plain string. formencode-2.0.1/docs/index.txt000066400000000000000000000022261412704564500164450ustar00rootroot00000000000000FormEncode ========== Introduction ------------ FormEncode is a validation and form generation package. The validation can be used separately from the form generation. The validation works on compound data structures, with all parts being nestable. It is separate from HTTP or any other input mechanism. `Ian Bicking`_ is the author of FormEncode. .. _Ian Bicking: http://ianbicking.org What's New ---------- .. toctree:: :maxdepth: 1 whatsnew-2.0 whatsnew-1.3 whatsnew-1.2.5 whatsnew-0-to-1.2.4 Documentation ------------- .. toctree:: :maxdepth: 1 Validator htmlfill ToDo Design history i18n modules Other Links ----------- .. toctree:: :maxdepth: 1 community download Indices and Search ------------------ * :ref:`genindex` * :ref:`modindex` * :ref:`search` Project Hosting --------------- .. image:: _static/sourceforge.png :align: left :height: 40 :width: 150 :alt: Hosted by SourceForge .. image:: _static/bitbucket.png :align: left :height: 40 :width: 127 :alt: Hosted by Bitbucket .. image:: _static/github.png :height: 40 :width: 90 :alt: Hosted by GitHub formencode-2.0.1/docs/make.bat000066400000000000000000000111211412704564500161740ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\FormEncode.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\FormEncode.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end formencode-2.0.1/docs/modules.txt000066400000000000000000000005471412704564500170120ustar00rootroot00000000000000Reference ========= .. toctree:: modules/api modules/compound modules/declarative modules/doctest_xml_compare modules/exc modules/foreach modules/htmlrename modules/htmlfill modules/htmlfill_schemabuilder modules/htmlgen modules/national modules/schema modules/validators modules/variabledecode formencode-2.0.1/docs/modules/000077500000000000000000000000001412704564500162435ustar00rootroot00000000000000formencode-2.0.1/docs/modules/api.txt000066400000000000000000000005741412704564500175630ustar00rootroot00000000000000:mod:`formencode.api` -- Core classes for validation =========================================================================== .. automodule:: formencode.api Module Contents --------------- .. autofunction:: is_empty .. autofunction:: is_validator .. autoclass:: NoDefault .. autoclass:: Invalid .. autoclass:: Validator .. autoclass:: Identity .. autoclass:: FancyValidator formencode-2.0.1/docs/modules/compound.txt000066400000000000000000000004011412704564500206230ustar00rootroot00000000000000:mod:`formencode.compound` -- Validate with multiple validators =============================================================== .. automodule:: formencode.compound Module Contents --------------- .. autoclass:: All .. autoclass:: Any .. autoclass:: Pipe formencode-2.0.1/docs/modules/declarative.txt000066400000000000000000000004011412704564500212620ustar00rootroot00000000000000:mod:`formencode.declarative` -- Base class for Validators ========================================================== .. automodule:: formencode.declarative Module Contents --------------- .. autoclass:: Declarative .. autofunction:: classinstancemethod formencode-2.0.1/docs/modules/doctest_xml_compare.txt000066400000000000000000000004531412704564500230410ustar00rootroot00000000000000:mod:`formencode.doctest_xml_compare` -- XML-based comparison of Doctest output =============================================================================== .. automodule:: formencode.doctest_xml_compare Module Contents --------------- .. autofunction:: xml_compare .. autofunction:: install formencode-2.0.1/docs/modules/exc.txt000066400000000000000000000003321412704564500175610ustar00rootroot00000000000000:mod:`formencode.exc` -- Custom exceptions and warnings =============================================================== .. automodule:: formencode.exc Module Contents --------------- .. autoclass:: FERuntimeWarning formencode-2.0.1/docs/modules/foreach.txt000066400000000000000000000003121412704564500204070ustar00rootroot00000000000000:mod:`formencode.foreach` -- Validate items in a list ===================================================== .. automodule:: formencode.foreach Module Contents --------------- .. autoclass:: ForEach formencode-2.0.1/docs/modules/htmlfill.txt000066400000000000000000000007141412704564500206210ustar00rootroot00000000000000:mod:`formencode.htmlfill` -- Fill in HTML forms ================================================ .. automodule:: formencode.htmlfill Module Contents --------------- .. autofunction:: render .. autoclass:: htmlliteral .. autofunction:: default_formatter .. autofunction: none_formatter .. autofunction:: escape_formatter .. autofunction:: escapenl_formatter .. autofunction:: ignore_formatter .. autofunction:: ignore_formatter .. autoclass:: FillingParser formencode-2.0.1/docs/modules/htmlfill_schemabuilder.txt000066400000000000000000000004511412704564500235060ustar00rootroot00000000000000:mod:`formencode.htmlfill_schemabuilder` -- Read a Schema from an HTML Form =========================================================================== .. automodule:: formencode.htmlfill_schemabuilder Module Contents --------------- .. autofunction:: parse_schema .. autoclass:: SchemaBuilder formencode-2.0.1/docs/modules/htmlgen.txt000066400000000000000000000003771412704564500204510ustar00rootroot00000000000000:mod:`formencode.htmlgen` -- Convenient building of ElementTree nodes ===================================================================== .. automodule:: formencode.htmlgen Module Contents --------------- .. autoclass:: _HTML .. autoclass:: Element formencode-2.0.1/docs/modules/htmlrename.txt000066400000000000000000000003741412704564500211440ustar00rootroot00000000000000:mod:`formencode.htmlrename` -- Rename fields in an HTML form ============================================================= .. automodule:: formencode.htmlrename Module Contents --------------- .. autofunction:: rename .. autofunction:: add_prefix formencode-2.0.1/docs/modules/national.txt000066400000000000000000000020371412704564500206130ustar00rootroot00000000000000:mod:`formencode.national` -- Country specific validators ========================================================= .. automodule:: formencode.national .. contents:: Module Contents --------------- .. admonition:: Note To use CountryValidator and LanguageValidator, install either `pycountry `__ or `TurboGears `__ Version 1.x. Country, State, and Postal Codes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autoclass:: DelimitedDigitsPostalCode .. autofunction:: USPostalCode .. autofunction:: GermanPostalCode .. autofunction:: FourDigitsPostalCode .. autofunction:: PolishPostalCode .. autoclass:: ArgentinianPostalCode .. autoclass:: CanadianPostalCode .. autoclass:: UKPostalCode .. autoclass:: CountryValidator .. autoclass:: PostalCodeInCountryFormat .. autoclass:: USStateProvince Phones and Addresses ~~~~~~~~~~~~~~~~~~~~ .. autoclass:: USPhoneNumber .. autoclass:: InternationalPhoneNumber Language Codes and Names ~~~~~~~~~~~~~~~~~~~~~~~~ .. autoclass:: LanguageValidator formencode-2.0.1/docs/modules/schema.txt000066400000000000000000000003041412704564500202410ustar00rootroot00000000000000:mod:`formencode.schema` -- Validate complete forms =================================================== .. automodule:: formencode.schema Module Contents --------------- .. autoclass:: Schema formencode-2.0.1/docs/modules/validators.txt000066400000000000000000000027601412704564500211610ustar00rootroot00000000000000:mod:`formencode.validators` -- lots of useful validators ========================================================= .. automodule:: formencode.validators .. contents:: Module Contents --------------- Basic Types ~~~~~~~~~~~ .. autoclass:: ByteString .. autoclass:: StringBool .. autoclass:: Bool .. autoclass:: Int .. autoclass:: Number .. autoclass:: UnicodeString .. autoclass:: Set Basic Validator/Converters ~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autoclass:: ConfirmType .. autoclass:: Wrapper .. autoclass:: Constant .. autoclass:: StripField .. autoclass:: OneOf .. autoclass:: DictConverter .. autoclass:: IndexListConverter Simple Validators ~~~~~~~~~~~~~~~~~ .. autoclass:: MaxLength .. autoclass:: MinLength .. autoclass:: NotEmpty .. autoclass:: Empty .. autoclass:: Regex .. autoclass:: PlainText Dates and Times ~~~~~~~~~~~~~~~ .. autoclass:: DateValidator .. autoclass:: DateConverter .. autoclass:: TimeConverter HTML Form Helpers ~~~~~~~~~~~~~~~~~ .. autoclass:: SignedString .. autoclass:: FieldStorageUploadConverter .. autoclass:: FileUploadKeeper URLs, Email, etc. ~~~~~~~~~~~~~~~~~ .. autoclass:: Email .. autoclass:: URL .. autoclass:: IPAddress .. autoclass:: CIDR .. autoclass:: MACAddress Form-wide Validation ~~~~~~~~~~~~~~~~~~~~ .. autoclass:: FormValidator .. autoclass:: RequireIfMissing .. autoclass:: RequireIfMatching .. autoclass:: FieldsMatch Credit Cards ~~~~~~~~~~~~ .. autoclass:: CreditCardValidator .. autoclass:: CreditCardExpires .. autoclass:: CreditCardSecurityCode formencode-2.0.1/docs/modules/variabledecode.txt000066400000000000000000000005471412704564500217430ustar00rootroot00000000000000:mod:`formencode.variabledecode` -- Turn flat HTML form submissions into nested structures ========================================================================================== .. automodule:: formencode.variabledecode Module Contents --------------- .. autofunction:: variable_decode .. autofunction:: variable_encode .. autoclass:: NestedVariables formencode-2.0.1/docs/whatsnew-0-to-1.2.4.txt000066400000000000000000000326521412704564500204210ustar00rootroot00000000000000What's New In FormEncode 0 to 1.2.4 =================================== .. contents:: 1.2.4 ----- * Fix packaging issue with i18n files (from Juliusz Gonera) 1.2.3 ----- * Code repository moved to BitBucket at `ianb/formencode `_. * Allowed :class:`formencode.validators.UnicodeString` to use different encoding of input and output, or no encoding/decoding at all. * Fixes `#2666139 `_: DateValidator bug happening only in March under Windows in Germany :) * Don't let :class:`formencode.compound.Any` shortcut validation when it gets an empty value (this same change had already been made to :class:`formencode.compound.All`). * Really updated German translation * Fixes `#2799713 `_: force_defaults=False and `` tags (previously ``src`` would be overwritten, for no good reason). * In :class:`formencode.validators.Email` allow single-character domain names (like x.com). * Make :class:`formencode.validators.FieldsMatch` give a normal ``Invalid`` exception if you pass it a non-dictionary. Also treat all missing keys as the empty string (previously the first key was required and would raise KeyError). * :class:`formencode.validators.Number` works with ``inf`` float values (before it would raise a OverflowError). * The ``tw`` locale has been renamed to the more standard ``zh_TW``. * Added Japanese and Turkish translations. * Fixed some outdated translations and errors in Spanish and Greek translations. Translations now managed with `Babel `_. 1.1 --- * Fixed the ``is_empty()`` method in :class:`formencode.validators.FieldStorageUploadConverter`; previously it returned the opposite of the intended result. * Added a parameter to ``htmlfill.render()``: ``prefix_error``. If this parameter is true (the default) then errors automatically go before the input field; if false then they go after the input field. * Remove deprecated modules: ``fields``, ``formgen``, ``htmlform``, ``sqlformgen``, and ``sqlschema``. * Added ``formencode.htmlrename``, which renames HTML inputs. * In ``formencode.htmlfill``, non-string values are compared usefully (e.g., a select box with integer values). * The validators ``Int`` and ``Number`` both take min/max arguments (from Shannon Behrens). * Validators based on ``formencode.validators.FormValidator`` will not treat ``{}`` as an empty (unvalidated) value. * Some adjustments to the URL validator. * :class:`formencode.compound.All` does not handle empty values, instead relying on sub-validators to check for emptiness. * Fixed the ``if_missing`` attribute in :class:`formencode.foreach.ForEach`; previously it would be the same list instance, so if you modified it then it would effect future ``if_missing`` values (reported by Felix Schwarz). * Added formatter to :mod:`formencode.htmlfill`, so you can use ```` -- this will cause the error to be swallowed, not shown to the user. * Added :class:`formencode.validators.XRI` for validation i-names, i-numbers, URLs, etc (as used in OpenID). * Look in ``/usr/share/locale`` for locale files, in addition to the normal locations. * Quiet Python 2.6 deprecation warnings. * Fix :class:`formencode.validators.URL`, which was accepting illegal characters (like newlines) and did not accept http://domain:PORT/ 1.0.1 ----- * ``chained_validators`` were removed from Schema somehow; now replaced and working. * Put in missing ``htmlfill.render(error_class=...)`` parameter (was documented and implemented, but ``render()`` did not pass it through). 1.0 --- * Added ``formencode.schema.SimpleFormValidator``, which wraps a simple function to make it a validator. * Changed the use of ``chained_validators`` in Schemas, so that all chained validators get run even when there are previous errors (to detect all the errors). * While something like ``Int.to_python()`` worked, other methods like ``Int.message(...)`` didn't work. Now it does. * Added Italian, Finnish, and Norwegian translations. 0.9 --- Backward incompatible changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * The notion of "empty" has changed to include empty lists, dictionaries, and tuples. If you get one of these values passed into (or generated by) a validator with ``not_empty=True`` you can get exceptions where you didn't previously. Enhancements ~~~~~~~~~~~~ * Added support for Paste's MultiDict dictionary as input to Schema.to_python, by converting it to a normal dict via MultiDict.mixed. Previously MultiDicts wouldn't work with CompoundValidators (like ForEach) * Added encoding parameter to htmlfill, which will handle cases when mixed str and unicode objects are used (turning all str objects into unicode) * Include ``formencode.validators.InternationalPhoneNumber`` from W-Mark Kubacki. * ``validators.Int`` takes ``min`` and ``max`` options (from Felix Schwarz). * You can control the missing message (which by default is just "Missing Value") using the message ``"missing"`` in a validator (also from James Gardner). * Added ``validators.CADR`` (for IP addresses with an optional range) and ``validators.MACAddress`` (from Christoph Haas). Bug Fixes ~~~~~~~~~ * Be friendlier when loaded from a zip file (as with py2exe); previously only egg zip files would work. * Fixed bug in htmlfill when a document ends with no trailing text after the last tag. * Fix problem with HTMLParser's default unescaping routing, which only understood a very limited number of entities in attribute values. * Fix problem with looking up A records for email addresses. * ``validators.String`` now always returns strings. It also converts lists to comma-separated strings (no ``[...]``), and can encode unicode if an ``encoding`` parameter is given. Empty values are handled better. * ``validators.UnicodeString`` properly handles non-Unicode inputs. * Make ``validators.DateConverter`` serialize dates properly (from James Gardner). * Minor fix to setup.py to make FormEncode more friendly with zc.buildout. 0.7.1 ----- * Set ``if_missing=()`` on ``validators.Set``, as a missing value usually means empty for this value. * Fix for ``Email`` validator that searches A records in addition to MX records (from Jacob Smullyan). * Fixes for the ``es`` locale. 0.7 --- * **Backward compatibility issue**: Due to the addition of i18n (internationalization) to FormEncode, Invalid exceptions now have unicode messages. You may encounter unicode-related errors if you are mixing these messages with non-ASCII ``str`` strings. * gettext-enabled branch merged in * Fixes `#1457145: Fails on URLs with port numbers `_ * Fixes `#1559918 Schema fails to accept unicode errors `_ * ``from formencode.validators import *`` will import the ``Invalid`` exception now. * ``Invalid().unpack_errors(encode_variables=True)`` now filters out None values (which ``ForEach`` can produce even for keys with no errors). 0.6 --- * ``String(min=1)`` implies ``not_empty`` (which seems more intuitive) * Added ``list_char`` and ``dict_char`` arguments to ``Invalid.unpack_errors`` (passed through to ``variable_encode``) * Added a ``use_datetime`` option to ``TimeValidator``, which will cause it to use ``datetime.time`` objects instead of tuples. It was previously able to consume but not produce these objects. * Added ```` when you want to include text only when a field has no errors. * There was a problem installing 0.5.1 on Windows with Python 2.5, now resolved. 0.5.1 ----- * Fixed compound validators and ``not_empty`` (was breaking SQLObject's PickleCol) 0.5 --- * Added ``htmlfill.default_formatter_dict``, and you can poke new formatters in there to effective register them. * Added an ``escapenl`` formatter (nl=newline) that escapes HTML and turns newlines into ``
``. * When ``not_empty=False``, empty is assumed to be allowed. Thus ``Int().to_python(None)`` will now return ``None``. 0.4 --- * Fixed up all the documentation. * Validator ``__doc__`` attributes will include some automatically-appended information about all the message strings that validator uses. * Deprecated ``formencode.htmlform`` module, because it is dumb. * Added an ``.all_messages()`` method to all validators, primarily intended to be used for documentation purposes. * Changed preferred name of ``StringBoolean`` to ``StringBool`` (to go with ``bool`` and ``validators.Bool``). Old alias still available. * Added ``today_or_after`` option to ``validators.DateValidator``. * Added a ``validators.FileUploadKeeper`` validator for helping with file uploads in failed forms. It still requires some annoying fiddling to make work, though, since file upload fields are so weird. * Added ``text_as_default`` option to htmlfill. This treats all ```` elements as text fields. WHAT-WG adds weird input types, which can usually be usefully treated as text fields. * Make all validators accept empty values if ``not_empty`` is False (the default). "Empty" means ``""`` or ``None``, and will generally be converted None. * Added ``accept_python`` boolean to all ``FancyValidator`` validators (which is most validators). This is a fixed version of the broken ``validate_python`` boolean added in 0.3. Also, it defaults to true, which means that all validators will not validate during ``.from_python()`` calls by default. * Added ``htmlfill.render(form, defaults, errors)`` for easier rendering of forms. * Errors automatically inserted by ``htmlfill`` will go at the top of the form if there's no field associated with the error (raised an error in 0.3). * Added ``formencode.sqlschema`` for wrapping SQLObject classes/instances. See the docstring for more. * Added ``ignore_key_missing`` to ``Schema`` objects, which ignore missing keys (where fields are present) when no ``if_missing`` is provided for the field. * Renamed ``validators.StateProvince.extraStates`` to ``extra_states``, to normalize style. Bugfixes ~~~~~~~~ * When checking destinations, ``validators.URL`` now allows redirect codes, and catches socket errors and turns them into proper errors. * Fix typo in ``htmlfill`` * Made URL and email regular expressions a little more lax/correct. * A bunch of fixes to ``validators.SignedString``, which apparently was completely broken. 0.3 ----- * Allow errors to be inserted automatically into a form when using ``formencode.htmlfill``, when a ```` tag isn't found for an error. * Added ``if_key_missing`` attribute to ``schema.Schema``, which will fill in any keys that are missing and pass them to the validator. * ``FancyValidator`` has changed, adding ``if_invalid_python`` and ``validate_python`` options (which also apply to all subclasses). Also ``if_empty`` only applies to ``to_python`` conversions. * ``FancyValidator`` now has a ``strip`` option, which if true and if input is a string, will strip whitespace from the string. * Allow chained validators to validate otherwise-invalid forms, if they define a ``validate_partial`` method. The credit card validator does this. * Handle ``FieldStorage`` input (from file uploads); added a ``formencode.fieldstorage`` module to wrap those instances in something a bit nicer. Added ``validators.FieldStorageUploadConverter`` to make this conversion. * Added ``StringBoolean`` converter, which converts strings like ``"true"`` to Python booleans. Bugfixes ~~~~~~~~ * A couple fixes to ``DateConverter``, ``FieldsMatch``, ``StringBoolean``, ``CreditCardValidator``. * Added missing ``Validator.assert_string`` method. * ``formencode.htmlfill_schemabuilder`` handles checkboxes better. * Be a little more careful about how ``Invalid`` exceptions are created (catch some errors sooner). * Improved handling of non-string input in ``htmlfill``. Experiments ~~~~~~~~~~~ * Some experimental work in ``formencode.formgen``. Experimental, I say! * Added an experimental ``formencode.context`` module for dynamically-scoped variables. formencode-2.0.1/docs/whatsnew-1.2.5.txt000066400000000000000000000024421412704564500176370ustar00rootroot00000000000000What's New In FormEncode 1.2.5 ============================== This article explains the latest changes in `FormEncode` version 1.2.5 as compared to its predecessor, `FormEncode` 1.2.4. Project Changes --------------- - New official BitBucket code repository at `formencode/official-formencode `_. Feature Additions ----------------- - The method `field_is_empty` was added to :class:`formencode.validators.FormValidator` so subclasses can use the same logic for emptiness and users can override it if necessary. Backwards Incompatibilities --------------------------- - The view attribute is no longer considered special when scanning Compound validators and Schemas for validators. - The :class:`formencode.validators.RequireIfMissing` and `RequireIfPresent` form validators now use the same empty/missing logic as the `is_empty` method of :class:`formencode.api.FancyValidator`. - Validators can say if they accept containers (list, tuple, set, etc) and schema will actively refuse those values if a validator does not allow them. Documentation Enhancements -------------------------- - Superceded news with whatsnew documents that will be archived for each version. Archived all news prior to 1.2.5 in :doc:`/whatsnew-0-to-1.2.4`. formencode-2.0.1/docs/whatsnew-1.3.txt000066400000000000000000000040721412704564500174760ustar00rootroot00000000000000What's New In FormEncode 1.3 ============================== This article explains the latest changes in `FormEncode` version 1.3 compared to its predecessor, `FormEncode` 1.2.5. Feature Additions ----------------- - Support validation of email addresses with unicode domain names. Backwards Incompatibilities --------------------------- - `FormEncode` 1.3 is no longer compatible with Python 2.3, 2.4, or 2.5. The reason? We could not easily "straddle" Python 2 and 3 versions and support Python 2 versions older than Python 2.6. You will need Python 2.6 or better to run this version of FormEncode. If you need to use Python 2.5, you should use the most recent 1.2.X release of FormEncode. - `FormEncode` now also runs under Python 3.2 and 3.3. Note that under Python 3, the `String` validator is now identical to the `UnicodeString` validator. If you really want to convert to byte strings, use the `ByteString` validator instead. - Validation of email addresses using `resolve_domain` option now requires the dnspython third party library instead of pyDNS. pyDNS also does not support Python 3. - The `FancyValidator` methods `_to_python`, `_from_python`, `validate_python` and `validate_other` have been renamed to `_convert_to_python`, `_convert_from_python`, `_validate_python` and `_validate_other`, respectively. This has been done to clarify that while these methods are meant to be overridden by custom validators, they are not part of the external API. They are only helper methods that are called internally by the external methods `to_python` and `from_python`, which constitute the external API. Particularly, do not assume that `_validate_python` catches all validation errors that a call of `to_python` will catch. Please have a look at the `FancyValidator` docstring and source if you're unsure how these methods work together. For the same reason, the `CompoundValidator` method `attempt_convert` has been renamed to `_attempt_convert`. For now, the old method names will still work, but they will output deprecation warnings. - (1.3.1) Don't use universal wheel formencode-2.0.1/docs/whatsnew-2.0.txt000066400000000000000000000027721412704564500175010ustar00rootroot00000000000000What's New In FormEncode 2.0 ============================ This article explains the latest changes in `FormEncode` version 2.0.0 compared to its predecessor, `FormEncode` 1.3.0 2.0.1 ----- - Add support for 3.10 - use Pytest instead of Nose and Github Actions instead of Travis for tests - Documentation updates - Note this will be the last version to support Python 2.7. The next version will be 2.1 to signal this change. If you want to keep support for Python 2.7 update your dependencies spec to be below 2.1 2.0.0 ----- - `FormEncode` can now run on Python 3.6 and higher without needing to run 2to3 first. - `FormEncode` 2.0 is no longer compatible with Python 2.6 and 3.2 to 3.5. If you need Python 2.6 or 3.2 to 3.5 compatibility please use `FormEncode` 1.3. You might also try `FormEncode` 2.0.0a1 which supports Python 2.6 and Python 3.3-3.5. - This will be the last major version to support Python 2.7 - Add strict flag to USPostalCode to raise error on postal codes that has too many digits instead of just truncating - Various Python 3 fixes - Serbian latin translation - Changed License to MIT - Dutch, UK, Greek and South Korean postal code format fixes - Add postal code formats for Switzerland, Cyprus, Faroe Islands, San Marino, Ukraine and Vatican City. - Add ISODateTimeConverter validator - Add ability to target htmlfill to particular form or ignore a form - Fix format errors in some translations - The version of the library can be checked using formencode.__version__ formencode-2.0.1/examples/000077500000000000000000000000001412704564500154615ustar00rootroot00000000000000formencode-2.0.1/examples/WebwareExamples/000077500000000000000000000000001412704564500205545ustar00rootroot00000000000000formencode-2.0.1/examples/WebwareExamples/__init__.py000066400000000000000000000000021412704564500226550ustar00rootroot00000000000000# formencode-2.0.1/examples/WebwareExamples/index.py000066400000000000000000000053661412704564500222470ustar00rootroot00000000000000from __future__ import absolute_import from __future__ import print_function from formencode import Invalid, htmlfill, Schema, validators from WebKit.Page import Page import six page_style = ''' Tell me about yourself

Tell me about yourself

A FormEncode example

%s ''' form_template = '''

Your name:

Your age:

Your favorite color:
Red
Blue
Black
Green
Pink

''' response_template = '''

Hello, %(name)s!

You are %(age)d years old and your favorite color is %(color)s.

''' class FormSchema(Schema): name = validators.String(not_empty=True) age = validators.Int(min=13, max=99) color = validators.OneOf(['red', 'blue', 'black', 'green']) filter_extra_fields = True allow_extra_fields = True class index(Page): def awake(self, trans): Page.awake(self, trans) self.rendered_form = None def actions(self): return ['save'] def save(self): fields = self.request().fields() try: fields = FormSchema.to_python(fields, self) except Invalid as e: errors = dict((k, v.encode('utf-8')) for k, v in six.iteritems(e.unpack_errors())) print("Errors:", errors) self.rendered_form = htmlfill.render(form_template, defaults=fields, errors=errors) self.writeHTML() else: self.doAction(fields) def doAction(self, fields): print("Fields:", fields) self.rendered_form = response_template % fields self.writeHTML() def writeHTML(self): if self.rendered_form is None: self.rendered_form = htmlfill.render(form_template, defaults=self.getDefaults()) self.write(page_style % self.rendered_form) def getDefaults(self): return dict(age='enter your age', color=['blue']) def preAction(self, trans): pass postAction = preAction formencode-2.0.1/examples/webware_example.ini000066400000000000000000000006431412704564500213340ustar00rootroot00000000000000# To use this example install Paste: http://svn.pythonpaste.org # and run: # $ PYTHONPATH=path/to/examples paster serve webware_example.ini # and open: # http://localhost:9999/ [app:main] use = egg:PasteWebKit servlet_directory = WebwareExamples debug = True [server:main] use = egg:PasteScript#wsgiutils host = 127.0.0.1 port = 9999 [server:flup] use = egg:PasteScript#flup_scgi_thread host = 127.0.0.1 port = 5050 formencode-2.0.1/formencode/000077500000000000000000000000001412704564500157645ustar00rootroot00000000000000formencode-2.0.1/formencode/__init__.py000066400000000000000000000012211412704564500200710ustar00rootroot00000000000000from __future__ import absolute_import # formencode package from pkg_resources import get_distribution, DistributionNotFound from formencode.api import ( NoDefault, Invalid, Validator, Identity, FancyValidator, is_empty, is_validator) from formencode.schema import Schema from formencode.compound import CompoundValidator, Any, All, Pipe from formencode.foreach import ForEach from formencode import validators from formencode import national from formencode.variabledecode import NestedVariables try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed __version__ = 'local-test' formencode-2.0.1/formencode/api.py000066400000000000000000000473661412704564500171270ustar00rootroot00000000000000""" Core classes for validation. """ from __future__ import absolute_import from . import declarative import gettext import os import re import textwrap import warnings import six try: from pkg_resources import resource_filename except ImportError: resource_filename = None __all__ = ['NoDefault', 'Invalid', 'Validator', 'Identity', 'FancyValidator', 'is_empty', 'is_validator'] def get_localedir(): """Retrieve the location of locales. If we're built as an egg, we need to find the resource within the egg. Otherwise, we need to look for the locales on the filesystem or in the system message catalog. """ locale_dir = '' # Check the egg first if resource_filename is not None: try: locale_dir = resource_filename(__name__, "i18n") except NotImplementedError: # resource_filename doesn't work with non-egg zip files pass if not hasattr(os, 'access'): # This happens on Google App Engine return os.path.join(os.path.dirname(__file__), 'i18n') if os.access(locale_dir, os.R_OK | os.X_OK): # If the resource is present in the egg, use it return locale_dir # Otherwise, search the filesystem locale_dir = os.path.join(os.path.dirname(__file__), 'i18n') if not os.access(locale_dir, os.R_OK | os.X_OK): # Fallback on the system catalog locale_dir = os.path.normpath('/usr/share/locale') return locale_dir def set_stdtranslation(domain="FormEncode", languages=None, localedir=get_localedir()): t = gettext.translation(domain=domain, languages=languages, localedir=localedir, fallback=True) global _stdtrans try: _stdtrans = t.ugettext except AttributeError: # Python 3 _stdtrans = t.gettext set_stdtranslation() # Dummy i18n translation function, nothing is translated here. # Instead this is actually done in api.Validator.message. # The surrounding _('string') of the strings is only for extracting # the strings automatically. # If you run pygettext with this source comment this function out temporarily. _ = lambda s: s def deprecation_warning(old, new=None, stacklevel=3): """Show a deprecation warning.""" msg = '%s is deprecated' % old if new: msg += '; use %s instead' % new warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel) def deprecated(old=None, new=None): """A decorator which can be used to mark functions as deprecated.""" def outer(func): def inner(*args, **kwargs): deprecation_warning(old or func.__name__, new) return func(*args, **kwargs) return inner return outer class NoDefault(object): """A dummy value used for parameters with no default.""" def is_empty(value): """Check whether the given value should be considered "empty".""" return value is None or value == '' or value == b'' or ( isinstance(value, (list, tuple, dict)) and not value) def is_validator(obj): """Check whether obj is a Validator instance or class.""" return (isinstance(obj, Validator) or (isinstance(obj, type) and issubclass(obj, Validator))) class Invalid(Exception): """ This is raised in response to invalid input. It has several public attributes: ``msg``: The message, *without* values substituted. For instance, if you want HTML quoting of values, you can apply that. ``substituteArgs``: The arguments (a dictionary) to go with ``msg``. ``str(self)``: The message describing the error, with values substituted. ``value``: The offending (invalid) value. ``state``: The state that went with this validator. This is an application-specific object. ``error_list``: If this was a compound validator that takes a repeating value, and sub-validator(s) had errors, then this is a list of those exceptions. The list will be the same length as the number of values -- valid values will have None instead of an exception. ``error_dict``: Like ``error_list``, but for dictionary compound validators. """ def __init__(self, msg, value, state, error_list=None, error_dict=None): Exception.__init__(self, msg, value, state, error_list, error_dict) self.msg = msg self.value = value self.state = state self.error_list = error_list self.error_dict = error_dict assert (not self.error_list or not self.error_dict), ( "Errors shouldn't have both error dicts and lists " "(error %s has %s and %s)" % (self, self.error_list, self.error_dict)) def __str__(self): val = self.msg return val if six.text_type is not str: # Python 2 def __unicode__(self): if isinstance(self.msg, six.text_type): return self.msg elif isinstance(self.msg, str): return self.msg.decode('utf8') else: return six.text_type(self.msg) def unpack_errors(self, encode_variables=False, dict_char='.', list_char='-'): """ Returns the error as a simple data structure -- lists, dictionaries, and strings. If ``encode_variables`` is true, then this will return a flat dictionary, encoded with variable_encode """ if self.error_list: assert not encode_variables, ( "You can only encode dictionary errors") assert not self.error_dict return [item.unpack_errors() if item else item for item in self.error_list] if self.error_dict: result = {} for name, item in six.iteritems(self.error_dict): result[name] = item if isinstance( item, six.string_types) else item.unpack_errors() if encode_variables: from . import variabledecode result = variabledecode.variable_encode( result, add_repetitions=False, dict_char=dict_char, list_char=list_char) for key in list(result.keys()): if not result[key]: del result[key] return result assert not encode_variables, ( "You can only encode dictionary errors") return self.msg ############################################################ ## Base Classes ############################################################ class Validator(declarative.Declarative): """ The base class of most validators. See ``IValidator`` for more, and ``FancyValidator`` for the more common (and more featureful) class. """ _messages = {} if_missing = NoDefault repeating = False compound = False accept_iterator = False gettextargs = {} # In case you don't want to use __builtins__._ # although it may be defined, set use_builtins_gettext to False: use_builtins_gettext = True __singletonmethods__ = ( 'to_python', 'from_python', 'message', 'all_messages', 'subvalidators') @staticmethod def __classinit__(cls, new_attrs): if 'messages' in new_attrs: cls._messages = cls._messages.copy() cls._messages.update(cls.messages) del cls.messages cls._initialize_docstring() def __init__(self, *args, **kw): if 'messages' in kw: self._messages = self._messages.copy() self._messages.update(kw.pop('messages')) declarative.Declarative.__init__(self, *args, **kw) def to_python(self, value, state=None): return value def from_python(self, value, state=None): return value _message_vars_decode = None if six.text_type is not str: def _message_vars_decode(self, message_vars): """ Under python2, a form value in web frameworks may be encoded as UTF8 unicode. The standard error templates use a ``%(value)r`` string formatting, which will render the error as ``u"Foo"`` instead of just ``"Foo"``. This decoder, which can be overridden, will encode the value back to a python string and render ``"Foo"``. This decoder will only update the error dictionary if the unicode and string values are equal by comparison. v = message_vars.items()[0][1] """ if six.text_type is not str: for (k, v) in message_vars.items(): if isinstance(v, six.text_type): try: v2 = v.encode('utf-8') except Exception as e: v2 = v if v == v2: message_vars[k] = v2 return message_vars def message(self, msgName, state, **kw): # determine translation function try: trans = state._ except AttributeError: try: if self.use_builtins_gettext: import six.moves.builtins trans = six.moves.builtins._ else: trans = _stdtrans except AttributeError: trans = _stdtrans if not callable(trans): trans = _stdtrans msg = self._messages[msgName] msg = trans(msg, **self.gettextargs) if self._message_vars_decode: # handle custom decoding for message vars kw = self._message_vars_decode(kw) try: return msg % kw except KeyError as e: raise KeyError( "Key not found (%s) for %r=%r %% %r (from: %s)" % (e, msgName, self._messages.get(msgName), kw, ', '.join(self._messages))) def all_messages(self): """ Return a dictionary of all the messages of this validator, and any subvalidators if present. Keys are message names, values may be a message or list of messages. This is really just intended for documentation purposes, to show someone all the messages that a validator or compound validator (like Schemas) can produce. @@: Should this produce a more structured set of messages, so that messages could be unpacked into a rendered form to see the placement of all the messages? Well, probably so. """ msgs = self._messages.copy() for v in self.subvalidators(): inner = v.all_messages() for key, msg in inner: if key in msgs: if msgs[key] == msg: continue if isinstance(msgs[key], list): msgs[key].append(msg) else: msgs[key] = [msgs[key], msg] else: msgs[key] = msg return msgs def subvalidators(self): """ Return any validators that this validator contains. This is not useful for functional, except to inspect what values are available. Specifically the ``.all_messages()`` method uses this to accumulate all possible messages. """ return [] @classmethod def _initialize_docstring(cls): """ This changes the class's docstring to include information about all the messages this validator uses. """ doc = cls.__doc__ or '' doc = [textwrap.dedent(doc).rstrip()] messages = sorted(six.iteritems(cls._messages)) doc.append('\n\n**Messages**\n\n') for name, default in messages: default = re.sub(r'(%\(.*?\)[rsifcx])', r'``\1``', default) doc.append('``' + name + '``:\n') doc.append(' ' + default + '\n\n') cls.__doc__ = ''.join(doc) class _Identity(Validator): def __repr__(self): return 'validators.Identity' Identity = _Identity() class FancyValidator(Validator): """ FancyValidator is the (abstract) superclass for various validators and converters. A subclass can validate, convert, or do both. There is no formal distinction made here. Validators have two important external methods: ``.to_python(value, state)``: Attempts to convert the value. If there is a problem, or the value is not valid, an Invalid exception is raised. The argument for this exception is the (potentially HTML-formatted) error message to give the user. ``.from_python(value, state)``: Reverses ``.to_python()``. These two external methods make use of the following four important internal methods that can be overridden. However, none of these *have* to be overridden, only the ones that are appropriate for the validator. ``._convert_to_python(value, state)``: This method converts the source to a Python value. It returns the converted value, or raises an Invalid exception if the conversion cannot be done. The argument to this exception should be the error message. Contrary to ``.to_python()`` it is only meant to convert the value, not to fully validate it. ``._convert_from_python(value, state)``: Should undo ``._convert_to_python()`` in some reasonable way, returning a string. ``._validate_other(value, state)``: Validates the source, before ``._convert_to_python()``, or after ``._convert_from_python()``. It's usually more convenient to use ``._validate_python()`` however. ``._validate_python(value, state)``: Validates a Python value, either the result of ``._convert_to_python()``, or the input to ``._convert_from_python()``. You should make sure that all possible validation errors are raised in at least one these four methods, not matter which. Subclasses can also override the ``__init__()`` method if the ``declarative.Declarative`` model doesn't work for this. Validators should have no internal state besides the values given at instantiation. They should be reusable and reentrant. All subclasses can take the arguments/instance variables: ``if_empty``: If set, then this value will be returned if the input evaluates to false (empty list, empty string, None, etc), but not the 0 or False objects. This only applies to ``.to_python()``. ``not_empty``: If true, then if an empty value is given raise an error. (Both with ``.to_python()`` and also ``.from_python()`` if ``._validate_python`` is true). ``strip``: If true and the input is a string, strip it (occurs before empty tests). ``if_invalid``: If set, then when this validator would raise Invalid during ``.to_python()``, instead return this value. ``if_invalid_python``: If set, when the Python value (converted with ``.from_python()``) is invalid, this value will be returned. ``accept_python``: If True (the default), then ``._validate_python()`` and ``._validate_other()`` will not be called when ``.from_python()`` is used. These parameters are handled at the level of the external methods ``.to_python()`` and ``.from_python`` already; if you overwrite one of the internal methods, you usually don't need to care about them. """ if_invalid = NoDefault if_invalid_python = NoDefault if_empty = NoDefault not_empty = False accept_python = True strip = False messages = dict( empty=_("Please enter a value"), badType=_("The input must be a string (not a %(type)s: %(value)r)"), noneType=_("The input must be a string (not None)")) _inheritance_level = 0 _deprecated_methods = ( ('_to_python', '_convert_to_python'), ('_from_python', '_convert_from_python'), ('validate_python', '_validate_python'), ('validate_other', '_validate_other')) @staticmethod def __classinit__(cls, new_attrs): Validator.__classinit__(cls, new_attrs) # account for deprecated methods cls._inheritance_level += 1 if '_deprecated_methods' in new_attrs: cls._deprecated_methods = cls._deprecated_methods + new_attrs[ '_deprecated_methods'] for old, new in cls._deprecated_methods: if old in new_attrs: if new not in new_attrs: deprecation_warning(old, new, stacklevel=cls._inheritance_level + 2) setattr(cls, new, new_attrs[old]) elif new in new_attrs: setattr(cls, old, deprecated(old=old, new=new)( new_attrs[new])) def to_python(self, value, state=None): try: if self.strip and isinstance(value, six.string_types): value = value.strip() elif hasattr(value, 'mixed'): # Support Paste's MultiDict value = value.mixed() if self.is_empty(value): if self.not_empty: raise Invalid(self.message('empty', state), value, state) if self.if_empty is not NoDefault: return self.if_empty return self.empty_value(value) vo = self._validate_other if vo and vo is not self._validate_noop: vo(value, state) tp = self._convert_to_python if tp: value = tp(value, state) vp = self._validate_python if vp and vp is not self._validate_noop: vp(value, state) except Invalid: value = self.if_invalid if value is NoDefault: raise return value def from_python(self, value, state=None): try: if self.strip and isinstance(value, six.string_types): value = value.strip() if not self.accept_python: if self.is_empty(value): if self.not_empty: raise Invalid(self.message('empty', state), value, state) return self.empty_value(value) vp = self._validate_python if vp and vp is not self._validate_noop: vp(value, state) fp = self._convert_from_python if fp: value = fp(value, state) vo = self._validate_other if vo and vo is not self._validate_noop: vo(value, state) else: if self.is_empty(value): return self.empty_value(value) fp = self._convert_from_python if fp: value = fp(value, state) except Invalid: value = self.if_invalid_python if value is NoDefault: raise return value def is_empty(self, value): return is_empty(value) def empty_value(self, value): return None def assert_string(self, value, state): if not isinstance(value, six.string_types): raise Invalid(self.message('badType', state, type=type(value), value=value), value, state) def base64encode(self, value): """ Encode a string in base64, stripping whitespace and removing newlines. """ return value.encode('base64').strip().replace('\n', '') def _validate_noop(self, value, state=None): """ A validation method that doesn't do anything. """ pass _validate_python = _validate_other = _validate_noop _convert_to_python = _convert_from_python = None formencode-2.0.1/formencode/compound.py000066400000000000000000000214411412704564500201640ustar00rootroot00000000000000""" Validators for applying validations in sequence. """ from __future__ import absolute_import from .api import (FancyValidator, Identity, Invalid, NoDefault, Validator, is_validator) import six __all__ = ['CompoundValidator', 'Any', 'All', 'Pipe'] ############################################################ ## Compound Validators ############################################################ def to_python(validator, value, state): return validator.to_python(value, state) def from_python(validator, value, state): return validator.from_python(value, state) class CompoundValidator(FancyValidator): """Base class for all compound validators.""" if_invalid = NoDefault accept_iterator = False validators = [] __unpackargs__ = ('*', 'validatorArgs') __mutableattributes__ = ('validators',) _deprecated_methods = ( ('attempt_convert', '_attempt_convert'),) @staticmethod def __classinit__(cls, new_attrs): FancyValidator.__classinit__(cls, new_attrs) toAdd = [] for name, value in six.iteritems(new_attrs): if is_validator(value) and value is not Identity: toAdd.append((name, value)) # @@: Should we really delete too? delattr(cls, name) toAdd.sort() cls.validators.extend([value for _name, value in toAdd]) def __init__(self, *args, **kw): Validator.__init__(self, *args, **kw) self.validators = self.validators[:] self.validators.extend(self.validatorArgs) @staticmethod def _repr_vars(names): return [n for n in Validator._repr_vars(names) if n != 'validatorArgs'] def _attempt_convert(self, value, state, convertFunc): raise NotImplementedError("Subclasses must implement _attempt_convert") def _convert_to_python(self, value, state=None): return self._attempt_convert(value, state, to_python) def _convert_from_python(self, value, state=None): return self._attempt_convert(value, state, from_python) def subvalidators(self): return self.validators class Any(CompoundValidator): """Check if any of the specified validators is valid. This class is like an 'or' operator for validators. The first validator/converter in the order of evaluation that validates the value will be used. The order of evaluation differs depending on if you are validating to Python or from Python as follows: The validators are evaluated right to left when validating to Python. The validators are evaluated left to right when validating from Python. Examples:: >>> from formencode.validators import DictConverter >>> av = Any(validators=[DictConverter({2: 1}), ... DictConverter({3: 2}), DictConverter({4: 3})]) >>> av.to_python(3) 2 >>> av.from_python(2) 3 """ def _attempt_convert(self, value, state, validate): lastException = None validators = self.validators if validate is to_python: validators = reversed(validators) for validator in validators: try: return validate(validator, value, state) except Invalid as e: lastException = e if self.if_invalid is NoDefault: raise lastException return self.if_invalid @property def not_empty(self): not_empty = True for validator in self.validators: not_empty = not_empty and getattr(validator, 'not_empty', False) return not_empty def is_empty(self, value): # sub-validators should handle emptiness. return False @property def accept_iterator(self): accept_iterator = False for validator in self.validators: accept_iterator = accept_iterator or getattr( validator, 'accept_iterator', False) return accept_iterator class All(CompoundValidator): """Check if all of the specified validators are valid. This class is like an 'and' operator for validators. All validators must work, and the results are passed in turn through all validators for conversion in the order of evaluation. All is the same as `Pipe` but operates in the reverse order. The order of evaluation differs depending on if you are validating to Python or from Python as follows: The validators are evaluated right to left when validating to Python. The validators are evaluated left to right when validating from Python. `Pipe` is more intuitive when predominantly validating to Python. Examples:: >>> from formencode.validators import DictConverter >>> av = All(validators=[DictConverter({2: 1}), ... DictConverter({3: 2}), DictConverter({4: 3})]) >>> av.to_python(4) 1 >>> av.from_python(1) 4 """ def __repr__(self): return '' % self.validators def _attempt_convert(self, value, state, validate): # To preserve the order of the transformations, we do them # differently when we are converting to and from Python. validators = self.validators if validate is to_python: validators = reversed(validators) try: for validator in validators: value = validate(validator, value, state) except Invalid: if self.if_invalid is NoDefault: raise return self.if_invalid return value def with_validator(self, validator): """Add another validator. Adds the validator (or list of validators) to a copy of this validator. """ new = self.validators[:] if isinstance(validator, (list, tuple)): new.extend(validator) else: new.append(validator) return self.__class__(*new, **dict(if_invalid=self.if_invalid)) @classmethod def join(cls, *validators): """Join the specified validators. Joins several validators together as a single validator, filtering out None and trying to keep `All` validators from being nested (which isn't needed). """ validators = [v for v in validators if v and v is not Identity] if not validators: return Identity if len(validators) == 1: return validators[0] if isinstance(validators[0], All): return validators[0].with_validator(validators[1:]) return cls(*validators) @property def if_missing(self): for validator in self.validators: v = validator.if_missing if v is not NoDefault: return v return NoDefault @property def not_empty(self): not_empty = False for validator in self.validators: not_empty = not_empty or getattr(validator, 'not_empty', False) return not_empty def is_empty(self, value): # sub-validators should handle emptiness. return False @property def accept_iterator(self): accept_iterator = True for validator in self.validators: accept_iterator = accept_iterator and getattr( validator, 'accept_iterator', False) return accept_iterator class Pipe(All): """Pipe value through all specified validators. This class works like `All` but the order of evaluation is opposite. All validators must work, and the results are passed in turn through each validator for conversion in the order of evaluation. A behaviour known to Unix and GNU users as 'pipe'. The order of evaluation differs depending on if you are validating to Python or from Python as follows: The validators are evaluated left to right when validating to Python. The validators are evaluated right to left when validating from Python. Examples:: >>> from formencode.validators import DictConverter >>> pv = Pipe(validators=[DictConverter({1: 2}), ... DictConverter({2: 3}), DictConverter({3: 4})]) >>> pv.to_python(1) 4 >>> pv.from_python(4) 1 """ def __repr__(self): return '' % self.validators def _attempt_convert(self, value, state, validate): # To preserve the order of the transformations, we do them # differently when we are converting to and from Python. validators = self.validators if validate is from_python: validators = reversed(self.validators) try: for validator in validators: value = validate(validator, value, state) except Invalid: if self.if_invalid is NoDefault: raise return self.if_invalid return value formencode-2.0.1/formencode/context.py000066400000000000000000000125241412704564500200260ustar00rootroot00000000000000""" A dynamic-scope-like system, aka fluid variables. The idea behind dynamic scoped variables is for when, at one level, you want to change the behavior of something you call. Except you can't pass in any new arguments (e.g., there's some function or object inbetween you and the thing you want to change), or you can't predict exactly what you will want to change. You should use it like:: context = Context() def do_stuff(): state = context.set(inside='do_stuff') try: do stuff... finally: state.restore() Then ``context.inside`` will be set to ``'do_stuff'`` inside that try block. If a value isn't set, you'll get an attribute error. Note that all values are thread local; this means you cannot use a context object to pass information to another thread. In a single-thread environment it doesn't really matter. Typically you will create ``Context`` instances for your application, environment, etc. These should be global module-level variables, that may be imported by any interested module; each instance is a namespace of its own. Sometimes it's nice to have default values, instead of getting attribute errors. This makes it easier to put in new variables that are intended to be used elsewhere, without having to use ``getattr(context, 'var', default)`` to avoid AttributeErrors. There are two ways (that can be used together) to do this. First, when instantiating a ``Context`` object, you can give it a ``default`` value. If given, then all variables will default to that value. ``None`` is a typical value for that. Another is ``context.set_default(**vars)``, which will set only those variables to default values. This will not effect the stack of scopes, but will only add defaults. When Python 2.5 comes out, this syntax would certainly be useful:: with context(page='view'): do stuff... And ``page`` will be set to ``'view'`` only inside that ``with`` block. """ from __future__ import absolute_import import threading from itertools import count from six.moves import range __all__ = ['Context', 'ContextRestoreError'] _restore_ids = count() class NoDefault(object): """A dummy value used for parameters with no default.""" class ContextRestoreError(Exception): """Raised when something is restored out-of-order.""" class Context(object): def __init__(self, default=NoDefault): self.__dict__['_local'] = threading.local() self.__dict__['_default'] = default def __getattr__(self, attr): if attr.startswith('_'): raise AttributeError try: stack = self._local.stack except AttributeError: stack = [] for i in range(len(stack) - 1, -1, -1): if attr in stack[i][0]: return stack[i][0][attr] if self._default is NoDefault: raise AttributeError( "The attribute %s has not been set on %r" % (attr, self)) return self._default def __setattr__(self, attr, value): raise AttributeError( "You can only write attribute on context object with the .set() method") def set(self, **kw): state_id = next(_restore_ids) try: stack = self._local.stack except AttributeError: stack = self._local.stack = [({}, -1)] restorer = RestoreState(self, state_id) stack.append((kw, state_id)) return restorer def _restore(self, state_id): try: stack = self._local.stack except AttributeError: raise ContextRestoreError( "Tried to restore context %r (to state ID %s) but no variables have been set in context" % (self, state_id)) if stack[-1][1] == -1: raise ContextRestoreError( "Out of order restoration of context %r (to state ID %s); the stack state is empty" % (self, state_id)) if stack[-1][1] != state_id: raise ContextRestoreError( "Out of order restoration of context %r (to state ID %s) when last state is %s" % (self, state_id, stack[-1][1])) stack.pop() def set_default(self, **kw): try: stack = self._local.stack except AttributeError: stack = self._local.stack = [({}, -1)] stack[0][0].update(kw) def __repr__(self): try: stack = self._local.stack except AttributeError: stack = [] myid = hex(abs(id(self)))[2:] if not stack: return '<%s %s (empty)>' % (self.__class__.__name__, myid) cur = {} for kw, _state_id in stack: cur.update(kw) keys = sorted(cur) varlist = [] for key in keys: rep = repr(cur[key]) if len(rep) > 10: rep = rep[:9] + '...' + rep[-1] varlist.append('%s=%s' % (key, rep)) return '<%s %s %s>' % ( self.__class__.__name__, myid, ' '.join(varlist)) class RestoreState(object): def __init__(self, context, state_id): self.state_id = state_id self.context = context self.restored = False def restore(self): if self.restored: # @@: Should this really be allowed? return self.context._restore(self.state_id) self.restored = True formencode-2.0.1/formencode/declarative.py000066400000000000000000000175611412704564500206330ustar00rootroot00000000000000""" Declarative objects for FormEncode. Declarative objects have a simple protocol: you can use classes in lieu of instances and they are equivalent, and any keyword arguments you give to the constructor will override those instance variables. (So if a class is received, we'll simply instantiate an instance with no arguments). You can provide a variable __unpackargs__ (a list of strings), and if the constructor is called with non-keyword arguments they will be interpreted as the given keyword arguments. If __unpackargs__ is ('*', name), then all the arguments will be put in a variable by that name. Also, you can define a __classinit__(cls, new_attrs) method, which will be called when the class is created (including subclasses). """ from __future__ import absolute_import import copy import types from itertools import count import six from six.moves import map from six.moves import zip class classinstancemethod(object): """ Acts like a class method when called from a class, like an instance method when called by an instance. The method should take two arguments, 'self' and 'cls'; one of these will be None depending on how the method was called. """ def __init__(self, func): self.func = func def __get__(self, obj, cls=None): return _methodwrapper(self.func, obj=obj, cls=cls) class _methodwrapper(object): def __init__(self, func, obj, cls): self.func = func self.obj = obj self.cls = cls def __call__(self, *args, **kw): assert 'self' not in kw and 'cls' not in kw, ( "You cannot use 'self' or 'cls' arguments to a " "classinstancemethod") return self.func(*((self.obj, self.cls) + args), **kw) def __repr__(self): if self.obj is None: return ('' % (self.cls.__name__, self.func.__name__)) return ('' % (self.cls.__name__, self.func.__name__, self.obj)) class DeclarativeMeta(type): def __new__(meta, class_name, bases, new_attrs): cls = type.__new__(meta, class_name, bases, new_attrs) for name in cls.__mutableattributes__: setattr(cls, name, copy.copy(getattr(cls, name))) cls.declarative_count = next(cls.counter) if ('__classinit__' in new_attrs and not isinstance(cls.__classinit__, (staticmethod, types.FunctionType))): setattr(cls, '__classinit__', staticmethod(cls.__classinit__.__func__)) cls.__classinit__(cls, new_attrs) names = getattr(cls, '__singletonmethods__', None) if names: for name in names: meth = cls.__dict__.get(name) if meth and not isinstance(meth, singletonmethod): setattr(cls, name, singletonmethod(meth)) return cls class singletonmethod(object): """ For Declarative subclasses, this decorator will call the method on the cls.singleton() object if called as a class method (or as normal if called as an instance method). """ def __init__(self, func): self.func = func def __get__(self, obj, cls=None): if obj is None: obj = cls.singleton() return types.MethodType(self.func, obj) class Declarative(six.with_metaclass(DeclarativeMeta, object)): __unpackargs__ = () __mutableattributes__ = () __singletonmethods__ = () counter = count() @staticmethod def __classinit__(cls, new_attrs): pass def __init__(self, *args, **kw): if self.__unpackargs__ and self.__unpackargs__[0] == '*': assert len(self.__unpackargs__) == 2, ( "When using __unpackargs__ = ('*', varname)," " you must only provide a single variable name" " (you gave %r)" % self.__unpackargs__) name = self.__unpackargs__[1] if name in kw: if args: raise TypeError( "keyword parameter '%s' was given by position and name" % name) else: kw[name] = args else: if len(args) > len(self.__unpackargs__): raise TypeError( '%s() takes at most %i arguments (%i given)' % (self.__class__.__name__, len(self.__unpackargs__), len(args))) for name, arg in zip(self.__unpackargs__, args): if name in kw: raise TypeError( "keyword parameter '%s' was given by position and name" % name) kw[name] = arg for name in self.__mutableattributes__: if name not in kw: setattr(self, name, copy.copy(getattr(self, name))) for name, value in six.iteritems(kw): setattr(self, name, value) if 'declarative_count' not in kw: self.declarative_count = next(self.counter) self.__initargs__(kw) def __initargs__(self, new_attrs): pass def __call__(self, *args, **kw): current = self.__dict__.copy() current.update(kw) return self.__class__(*args, **current) @classmethod def singleton(cls): name = '_%s__singleton' % cls.__name__ if not hasattr(cls, name): try: setattr(cls, name, cls( declarative_count=cls.declarative_count)) except TypeError: # takes arguments setattr(cls, name, cls) return getattr(cls, name) def __sourcerepr__(self, source, binding=None): if binding and len(self.__dict__) > 3: return self._source_repr_class(source, binding=binding) vals = self.__dict__.copy() if 'declarative_count' in vals: del vals['declarative_count'] args = [] if (self.__unpackargs__ and self.__unpackargs__[0] == '*' and self.__unpackargs__[1] in vals): v = vals[self.__unpackargs__[1]] if isinstance(v, (list, int)): args.extend(list(map(source.makeRepr, v))) del v[self.__unpackargs__[1]] for name in self.__unpackargs__: if name in vals: args.append(source.makeRepr(vals[name])) del vals[name] else: break args.extend('%s=%s' % (name, source.makeRepr(value)) for (name, value) in six.iteritems(vals)) return '%s(%s)' % (self.__class__.__name__, ', '.join(args)) def _source_repr_class(self, source, binding=None): d = self.__dict__.copy() if 'declarative_count' in d: del d['declarative_count'] return source.makeClass(self, binding, d, (self.__class__,)) @classmethod def __classsourcerepr__(cls, source, binding=None): d = cls.__dict__.copy() del d['declarative_count'] return source.makeClass(cls, binding or cls.__name__, d, cls.__bases__) @classinstancemethod def __repr__(self, cls): if self: name = '%s object' % self.__class__.__name__ v = self.__dict__.copy() else: name = '%s class' % cls.__name__ v = cls.__dict__.copy() if 'declarative_count' in v: name = '%s %i' % (name, v.pop('declarative_count')) names = sorted(v) args = ['%s=self' % n if v[n] is self else '%s=%r' % (n, v[n]) for n in self._repr_vars(names)] if not args: return '<%s>' % name return '<%s %s>' % (name, ' '.join(args)) @staticmethod def _repr_vars(dictNames): return sorted(n for n in dictNames if not n.startswith('_') and n != 'declarative_count') formencode-2.0.1/formencode/doctest_xml_compare.py000066400000000000000000000100141412704564500223650ustar00rootroot00000000000000from __future__ import absolute_import from __future__ import print_function import doctest import xml.etree.ElementTree as ET import six from six.moves import map from six.moves import zip try: XMLParseError = ET.ParseError except AttributeError: # Python < 2.7 from xml.parsers.expat import ExpatError as XMLParseError RealOutputChecker = doctest.OutputChecker def debug(*msg): import sys print(' '.join(map(str, msg)), file=sys.stderr) class HTMLOutputChecker(RealOutputChecker): def check_output(self, want, got, optionflags): normal = RealOutputChecker.check_output(self, want, got, optionflags) if normal or not got: return normal try: want_xml = make_xml(want) except XMLParseError: pass else: try: got_xml = make_xml(got) except XMLParseError: pass else: if xml_compare(want_xml, got_xml): return True return False def output_difference(self, example, got, optionflags): actual = RealOutputChecker.output_difference( self, example, got, optionflags) want_xml = got_xml = None try: want_xml = make_xml(example.want) want_norm = make_string(want_xml) except XMLParseError as e: if example.want.startswith('<'): want_norm = '(bad XML: %s)' % e # '%s' % example.want else: return actual try: got_xml = make_xml(got) got_norm = make_string(got_xml) except XMLParseError as e: if example.want.startswith('<'): got_norm = '(bad XML: %s)' % e else: return actual s = '%s\nXML Wanted: %s\nXML Got : %s\n' % ( actual, want_norm, got_norm) if got_xml and want_xml: result = [] xml_compare(want_xml, got_xml, result.append) s += 'Difference report:\n%s\n' % '\n'.join(result) return s def xml_compare(x1, x2, reporter=None): if x1.tag != x2.tag: if reporter: reporter('Tags do not match: %s and %s' % (x1.tag, x2.tag)) return False for name, value in six.iteritems(x1.attrib): if x2.attrib.get(name) != value: if reporter: reporter('Attributes do not match: %s=%r, %s=%r' % (name, value, name, x2.attrib.get(name))) return False for name in x2.attrib: if name not in x1.attrib: if reporter: reporter('x2 has an attribute x1 is missing: %s' % name) return False if not text_compare(x1.text, x2.text): if reporter: reporter('text: %r != %r' % (x1.text, x2.text)) return False if not text_compare(x1.tail, x2.tail): if reporter: reporter('tail: %r != %r' % (x1.tail, x2.tail)) return False cl1 = list(x1) cl2 = list(x2) if len(cl1) != len(cl2): if reporter: reporter('children length differs, %i != %i' % (len(cl1), len(cl2))) return False i = 0 for c1, c2 in zip(cl1, cl2): i += 1 if not xml_compare(c1, c2, reporter=reporter): if reporter: reporter('children %i do not match: %s' % (i, c1.tag)) return False return True def text_compare(t1, t2): if not t1 and not t2: return True if t1 == '*' or t2 == '*': return True return (t1 or '').strip() == (t2 or '').strip() def make_xml(s): return ET.XML('%s' % s) def make_string(xml): if isinstance(xml, six.string_types): xml = make_xml(xml) s = ET.tostring(xml) if s == '': return '' assert s.startswith('') and s.endswith(''), repr(s) return s[5:-6] def install(): doctest.OutputChecker = HTMLOutputChecker formencode-2.0.1/formencode/exc.py000066400000000000000000000002311412704564500171110ustar00rootroot00000000000000""" Custom exceptions and warnings. """ __all__ = ['FERunTimeWarning'] class FERuntimeWarning(RuntimeWarning): """ Run time warning. """ pass formencode-2.0.1/formencode/fieldstorage.py000066400000000000000000000004371412704564500210120ustar00rootroot00000000000000## FormEncode, a Form processor ## Copyright (C) 2003, Ian Bicking """ Wrapper class for use with cgi.FieldStorage types for file uploads """ from __future__ import absolute_import import cgi def convert_fieldstorage(fs): return fs if fs.filename else None formencode-2.0.1/formencode/foreach.py000066400000000000000000000107031412704564500177460ustar00rootroot00000000000000""" Validator for repeating items. """ from __future__ import absolute_import from .api import NoDefault, Invalid from .compound import CompoundValidator, from_python import six __all__ = ['ForEach'] class ForEach(CompoundValidator): """ Use this to apply a validator/converter to each item in a list. For instance:: ForEach(Int(), OneOf([1, 2, 3])) Will take a list of values and try to convert each of them to an integer, and then check if each integer is 1, 2, or 3. Using multiple arguments is equivalent to:: ForEach(All(Int(), OneOf([1, 2, 3]))) Use convert_to_list=True if you want to force the input to be a list. This will turn non-lists into one-element lists, and None into the empty list. This tries to detect sequences by iterating over them (except strings, which aren't considered sequences). ForEach will try to convert the entire list, even if errors are encountered. If errors are encountered, they will be collected and a single Invalid exception will be raised at the end (with error_list set). If the incoming value is a set, then we return a set. """ convert_to_list = True if_empty = NoDefault accept_iterator = True repeating = True _if_missing = () def _attempt_convert(self, value, state, validate): if self.convert_to_list: value = self._convert_to_list(value) if self.if_empty is not NoDefault and not value: return self.if_empty if self.not_empty and not value: if validate is from_python and self.accept_python: return [] raise Invalid( self.message('empty', state), value, state) new_list = [] errors = [] all_good = True is_set = isinstance(value, set) if state is not None: previous_index = getattr(state, 'index', NoDefault) previous_full_list = getattr(state, 'full_list', NoDefault) index = 0 state.full_list = value try: for sub_value in value: if state: state.index = index index += 1 good_pass = True for validator in self.validators: try: sub_value = validate(validator, sub_value, state) except Invalid as e: errors.append(e) all_good = False good_pass = False break if good_pass: errors.append(None) new_list.append(sub_value) if all_good: if is_set: new_list = set(new_list) return new_list else: raise Invalid('Errors:\n%s' % '\n'.join(six.text_type(e) for e in errors if e), value, state, error_list=errors) finally: if state is not None: if previous_index is NoDefault: try: del state.index except AttributeError: pass else: state.index = previous_index if previous_full_list is NoDefault: try: del state.full_list except AttributeError: pass else: state.full_list = previous_full_list def empty_value(self, value): return [] class _IfMissing(object): def __get__(self, obj, cls=None): if obj is None: return [] elif obj._if_missing is ForEach._if_missing: return [] else: return obj._if_missing def __set__(self, obj, value): obj._if_missing = value def __delete__(self, obj): obj._if_missing = NoDefault if_missing = _IfMissing() del _IfMissing def _convert_to_list(self, value): if isinstance(value, six.string_types): return [value] elif value is None: return [] elif isinstance(value, (list, tuple)): return value try: for _n in value: break return value ## @@: Should this catch any other errors?: except TypeError: return [value] formencode-2.0.1/formencode/htmlfill.py000066400000000000000000000552421412704564500201610ustar00rootroot00000000000000""" Parser for HTML forms, that fills in defaults and errors. See ``render``. """ from __future__ import absolute_import import re from formencode.rewritingparser import RewritingParser, html_quote import six __all__ = ['render', 'htmlliteral', 'default_formatter', 'none_formatter', 'escape_formatter', 'FillingParser'] def render(form, defaults=None, errors=None, use_all_keys=False, error_formatters=None, add_attributes=None, auto_insert_errors=True, auto_error_formatter=None, text_as_default=False, checkbox_checked_if_present=False, listener=None, encoding=None, error_class='error', prefix_error=True, force_defaults=True, skip_passwords=False, data_formencode_form=None, data_formencode_ignore=None, ): """ Render the ``form`` (which should be a string) given the ``defaults`` and ``errors``. Defaults are the values that go in the input fields (overwriting any values that are there) and errors are displayed inline in the form (and also effect input classes). Returns the rendered string. If ``auto_insert_errors`` is true (the default) then any errors for which ```` tags can't be found will be put just above the associated input field, or at the top of the form if no field can be found. If ``use_all_keys`` is true, if there are any extra fields from defaults or errors that couldn't be used in the form it will be an error. ``error_formatters`` is a dictionary of formatter names to one-argument functions that format an error into HTML. Some default formatters are provided if you don't provide this. ``error_class`` is the class added to input fields when there is an error for that field. ``add_attributes`` is a dictionary of field names to a dictionary of attribute name/values. If the name starts with ``+`` then the value will be appended to any existing attribute (e.g., ``{'+class': ' important'}``). ``auto_error_formatter`` is used to create the HTML that goes above the fields. By default it wraps the error message in a span and adds a ``
``. If ``text_as_default`` is true (default false) then ```` will be treated as text inputs. If ``checkbox_checked_if_present`` is true (default false) then ```` will be set to ``checked`` if any corresponding key is found in the ``defaults`` dictionary, even a value that evaluates to False (like an empty string). This can be used to support pre-filling of checkboxes that do not have a ``value`` attribute, since browsers typically will only send the name of the checkbox in the form submission if the checkbox is checked, so simply the presence of the key would mean the box should be checked. ``listener`` can be an object that watches fields pass; the only one currently is in ``htmlfill_schemabuilder.SchemaBuilder`` ``encoding`` specifies an encoding to assume when mixing str and unicode text in the template. ``prefix_error`` specifies if the HTML created by auto_error_formatter is put before the input control (default) or after the control. ``force_defaults`` specifies if a field default is not given in the ``defaults`` dictionary then the control associated with the field should be set as an unsuccessful control. So checkboxes will be cleared, radio and select controls will have no value selected, and textareas will be emptied. This defaults to ``True``, which is appropriate the defaults are the result of a form submission. ``skip_passwords`` specifies if password fields should be skipped when rendering form-content. If disabled the password fields will not be filled with anything, which is useful when you don't want to return a user's password in plain-text source. ``data_formencode_form`` if a string is passed in (default `None`) only fields with the html attribute `data-formencode-form` that matches this string will be processed. For example: if a HTML fragment has two forms they can be differentiated to Formencode by decorating the input elements with attributes such as `data-formencode-form="a"` or `data-formencode-form="b"`, then instructing `render()` to only process the "a" or "b" fields. ``data_formencode_ignore`` if True (default `None`) fields with the html attribute `data-formencode-ignore` will not be processed. This attribute need only be present in the tag: `data-formencode-ignore="1"`, `data-formencode-ignore=""` and `data-formencode-ignore` without a value are all valid signifiers. """ if defaults is None: defaults = {} if auto_insert_errors and auto_error_formatter is None: auto_error_formatter = default_formatter p = FillingParser( defaults=defaults, errors=errors, use_all_keys=use_all_keys, error_formatters=error_formatters, add_attributes=add_attributes, auto_error_formatter=auto_error_formatter, text_as_default=text_as_default, checkbox_checked_if_present=checkbox_checked_if_present, listener=listener, encoding=encoding, prefix_error=prefix_error, error_class=error_class, force_defaults=force_defaults, skip_passwords=skip_passwords, data_formencode_form=data_formencode_form, data_formencode_ignore=data_formencode_ignore, ) p.feed(form) p.close() return p.text() class htmlliteral(object): def __init__(self, html, text=None): if text is None: text = re.sub(r'<.*?>', '', html) text = html.replace('>', '>') text = html.replace('<', '<') text = html.replace('"', '"') # @@: Not very complete self.html = html self.text = text def __str__(self): return self.text def __repr__(self): return '<%s html=%r text=%r>' % ( self.__class__.__name__, self.html, self.text) def __html__(self): return self.html def default_formatter(error): """ Formatter that escapes the error, wraps the error in a span with class ``error-message``, and adds a ``
`` """ return '%s
\n' % html_quote(error) def none_formatter(error): """ Formatter that does nothing, no escaping HTML, nothin' """ return error def escape_formatter(error): """ Formatter that escapes HTML, no more. """ return html_quote(error) def escapenl_formatter(error): """ Formatter that escapes HTML, and translates newlines to ``
`` """ error = html_quote(error) error = error.replace('\n', '
\n') return error def ignore_formatter(error): """ Formatter that emits nothing, regardless of the error. """ return '' class FillingParser(RewritingParser): r""" Fills HTML with default values, as in a form. Examples:: >>> defaults = dict(name='Bob Jones', ... occupation='Crazy Cultist', ... address='14 W. Canal\nNew Guinea', ... living='no', ... nice_guy=0) >>> parser = FillingParser(defaults) >>> parser.feed(''' ... ... ... ... ... ''') >>> parser.close() >>> print (parser.text()) # doctest: +NORMALIZE_WHITESPACE """ default_encoding = 'utf8' text_input_types = set("text hidden search tel url email datetime date" " month week time datetime-local number range color".split()) def __init__(self, defaults, errors=None, use_all_keys=False, error_formatters=None, error_class='error', add_attributes=None, listener=None, auto_error_formatter=None, text_as_default=False, checkbox_checked_if_present=False, encoding=None, prefix_error=True, force_defaults=True, skip_passwords=False, data_formencode_form=None, data_formencode_ignore=None, ): RewritingParser.__init__(self) self.source = None self.lines = None self.source_pos = None self.defaults = defaults self.in_textarea = None self.skip_textarea = False self.last_textarea_name = None self.in_select = None self.skip_next = False self.errors = errors or {} if isinstance(self.errors, six.string_types): self.errors = {None: self.errors} self.in_error = None self.skip_error = False self.use_all_keys = use_all_keys self.used_keys = set() self.used_errors = set() if error_formatters is None: self.error_formatters = default_formatter_dict else: self.error_formatters = error_formatters self.error_class = error_class self.add_attributes = add_attributes or {} self.listener = listener self.auto_error_formatter = auto_error_formatter self.text_as_default = text_as_default self.checkbox_checked_if_present = checkbox_checked_if_present self.encoding = encoding self.prefix_error = prefix_error self.force_defaults = force_defaults self.skip_passwords = skip_passwords self.data_formencode_form = data_formencode_form self.data_formencode_ignore = data_formencode_ignore def str_compare(self, str1, str2): """ Compare the two objects as strings (coercing to strings if necessary). Also uses encoding to compare the strings. """ if not isinstance(str1, six.string_types): if hasattr(str1, '__unicode__'): str1 = six.text_type(str1) else: str1 = str(str1) if type(str1) == type(str2): return str1 == str2 if isinstance(str1, six.text_type): str1 = str1.encode(self.encoding or self.default_encoding) else: str2 = str2.encode(self.encoding or self.default_encoding) return str1 == str2 def close(self): self.handle_misc(None) RewritingParser.close(self) unused_errors = self.errors.copy() for key in self.used_errors: if key in unused_errors: del unused_errors[key] if self.auto_error_formatter: for key, value in six.iteritems(unused_errors): error_message = self.auto_error_formatter(value) error_message = '\n%s' % (key, error_message) self.insert_at_marker( key, error_message) unused_errors = {} if self.use_all_keys: unused = self.defaults.copy() for key in self.used_keys: if key in unused: del unused[key] assert not unused, ( "These keys from defaults were not used in the form: %s" % ', '.join(unused)) if unused_errors: error_text = ['%s: %s' % (key, self.errors[key]) for key in sorted(unused_errors)] assert False, ( "These errors were not used in the form: %s" % ', '.join(error_text)) if self.encoding is not None: new_content = [] for item in self._content: if (six.text_type is not str # Python 2 and isinstance(item, str)): item = item.decode(self.encoding) new_content.append(item) self._content = new_content self._text = self._get_text() def skip_output(self): return (self.in_textarea and self.skip_textarea) or self.skip_error def add_key(self, key): self.used_keys.add(key) def handle_starttag(self, tag, attrs, startend=False): self.write_pos() if self.data_formencode_form: for a in attrs: if a[0] == 'data-formencode-form': if a[1] != self.data_formencode_form: return if self.data_formencode_ignore: for a in attrs: if a[0] == 'data-formencode-ignore': return if tag == 'input': self.handle_input(attrs, startend) elif tag == 'textarea': self.handle_textarea(attrs) elif tag == 'select': self.handle_select(attrs) elif tag == 'option': self.handle_option(attrs) return elif tag == 'form:error': self.handle_error(attrs) return elif tag == 'form:iferror': self.handle_iferror(attrs) return else: return if self.listener: self.listener.listen_input(self, tag, attrs) def handle_endtag(self, tag): self.write_pos() if tag == 'textarea': self.handle_end_textarea() elif tag == 'select': self.handle_end_select() elif tag == 'form:error': self.handle_end_error() elif tag == 'form:iferror': self.handle_end_iferror() def handle_startendtag(self, tag, attrs): return self.handle_starttag(tag, attrs, True) def handle_iferror(self, attrs): name = self.get_attr(attrs, 'name') assert name, ( "Name attribute in required at %i:%i" % self.getpos()) notted = name.startswith('not ') if notted: name = name.split(None, 1)[1] self.in_error = name ok = self.errors.get(name) if notted: ok = not ok if not ok: self.skip_error = True self.skip_next = True def handle_end_iferror(self): self.in_error = None self.skip_error = False self.skip_next = True def handle_error(self, attrs): name = self.get_attr(attrs, 'name') if name is None: name = self.in_error assert name is not None, ( "Name attribute in required" " if not contained in at %i:%i" % self.getpos()) formatter = self.get_attr(attrs, 'format') or 'default' error = self.errors.get(name, '') if error: error = self.error_formatters[formatter](error) self.write_text(error) self.skip_next = True self.used_errors.add(name) def handle_end_error(self): self.skip_next = True def handle_input(self, attrs, startend): t = (self.get_attr(attrs, 'type') or 'text').lower() name = self.get_attr(attrs, 'name') if self.prefix_error: self.write_marker(name) value = self.defaults.get(name) if (six.text_type is not str # Python 2 and isinstance(name, six.text_type) and isinstance(value, str)): value = value.decode(self.encoding or self.default_encoding) if name in self.add_attributes: for attr_name, attr_value in six.iteritems(self.add_attributes[name]): if attr_name.startswith('+'): attr_name = attr_name[1:] self.set_attr(attrs, attr_name, self.get_attr(attrs, attr_name, '') + attr_value) else: self.set_attr(attrs, attr_name, attr_value) if (self.error_class and self.errors.get(self.get_attr(attrs, 'name'))): self.add_class(attrs, self.error_class) if t in self.text_input_types: if value is None and not self.force_defaults: value = self.get_attr(attrs, 'value', '') self.set_attr(attrs, 'value', value) self.write_tag('input', attrs, startend) self.skip_next = True self.add_key(name) elif t == 'checkbox': if self.force_defaults: selected = False else: selected = self.get_attr(attrs, 'checked') if not self.get_attr(attrs, 'value'): if self.checkbox_checked_if_present: selected = name in self.defaults else: selected = value elif self.selected_multiple(value, self.get_attr(attrs, 'value', '')): selected = True if selected: self.set_attr(attrs, 'checked', 'checked') else: self.del_attr(attrs, 'checked') self.write_tag('input', attrs, startend) self.skip_next = True self.add_key(name) elif t == 'radio': if self.str_compare(value, self.get_attr(attrs, 'value', '')): self.set_attr(attrs, 'checked', 'checked') elif self.force_defaults or name in self.defaults: self.del_attr(attrs, 'checked') self.write_tag('input', attrs, startend) self.skip_next = True self.add_key(name) elif t == 'password': if self.skip_passwords: return if value is None and not self.force_defaults: value = value or self.get_attr(attrs, 'value', '') self.set_attr(attrs, 'value', value) self.write_tag('input', attrs, startend) self.skip_next = True self.add_key(name) elif t in ('file', 'image'): self.write_tag('input', attrs, startend) self.skip_next = True self.add_key(name) elif t in ('submit', 'reset', 'button'): self.set_attr(attrs, 'value', value or self.get_attr(attrs, 'value', '')) self.write_tag('input', attrs, startend) self.skip_next = True self.add_key(name) elif self.text_as_default: if value is None: value = self.get_attr(attrs, 'value', '') self.set_attr(attrs, 'value', value) self.write_tag('input', attrs, startend) self.skip_next = True self.add_key(name) else: assert False, ("I don't know about this kind of :" " %s at %i:%i" % ((t,) + self.getpos())) if not self.prefix_error: self.write_marker(name) def handle_textarea(self, attrs): name = self.get_attr(attrs, 'name') if self.prefix_error: self.write_marker(name) if (self.error_class and self.errors.get(name)): self.add_class(attrs, self.error_class) value = self.defaults.get(name, '') if value or self.force_defaults: self.write_tag('textarea', attrs) self.write_text(html_quote(value)) self.write_text('') self.skip_textarea = True self.in_textarea = True self.last_textarea_name = name self.add_key(name) def handle_end_textarea(self): if self.skip_textarea: self.skip_textarea = False else: self.write_text('') self.in_textarea = False self.skip_next = True if not self.prefix_error: self.write_marker(self.last_textarea_name) self.last_textarea_name = None def handle_select(self, attrs): name = self.get_attr(attrs, 'name', False) if name and self.prefix_error: self.write_marker(name) if (self.error_class and self.errors.get(name)): self.add_class(attrs, self.error_class) self.in_select = self.get_attr(attrs, 'name', False) self.write_tag('select', attrs) self.skip_next = True self.add_key(self.in_select) def handle_end_select(self): self.write_text('') self.skip_next = True if not self.prefix_error and self.in_select: self.write_marker(self.in_select) self.in_select = None def handle_option(self, attrs): assert self.in_select is not None, ( "