FormEncode-1.3.0/0000775000000000000000000000000012617165271012244 5ustar rootrootFormEncode-1.3.0/setup.py0000666000000000000000000000336112465411770013762 0ustar rootroot"""FormEncode validates and converts nested structures. It allows for a declarative form of defining the validation, and decoupled processes for filling and generating forms. The official repo is at GitHub: https://github.com/formencode/formencode """ import sys from setuptools import setup, find_packages version = '1.3.0' if not '2.6' <= sys.version < '3.0' and not '3.2' <= sys.version: raise ImportError('Python version not supported') tests_require = ['nose', 'pycountry', 'dnspython' if sys.version < '3.0' else 'dnspython3'] doctests = ['docs/htmlfill.txt', 'docs/Validator.txt', 'formencode/tests/non_empty.txt'] setup(name='FormEncode', version=version, # requires_python='>=2.6,!=3.0,!=3.1', # PEP345 description="HTML form validation, generation, and conversion package", long_description=__doc__, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Python Software Foundation License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", ], author='Ian Bicking', author_email='ianb@colorstudy.com', url='http://formencode.org', license='PSF', zip_safe=False, packages=find_packages(), include_package_data=True, package_data={'formencode': ['../docs/*.txt']}, test_suite='formencode.tests', tests_require=tests_require, extras_require={'testing': tests_require}, use_2to3=True, convert_2to3_doctests=doctests, ) FormEncode-1.3.0/MANIFEST.in0000666000000000000000000000046212117455122013776 0ustar rootrootrecursive-include . *.py recursive-include docs *.html *.txt *.css recursive-include formencode/javascript *.js recursive-include formencode/i18n *.py *.pot *.po *.mo recursive-include formencode/tests *.txt recursive-exclude . *.pyc *.pyo *~ prune docs/_build prune **/.svn prune .hg prune .git FormEncode-1.3.0/PKG-INFO0000666000000000000000000000165712465412710013346 0ustar rootrootMetadata-Version: 1.1 Name: FormEncode Version: 1.3.0 Summary: HTML form validation, generation, and conversion package Home-page: http://formencode.org Author: Ian Bicking Author-email: ianb@colorstudy.com License: PSF Description: FormEncode validates and converts nested structures. It allows for a declarative form of defining the validation, and decoupled processes for filling and generating forms. The official repo is at GitHub: https://github.com/formencode/formencode Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Python Software Foundation License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Software Development :: Libraries :: Python Modules FormEncode-1.3.0/docs/0000775000000000000000000000000012617165271013174 5ustar rootrootFormEncode-1.3.0/docs/index.txt0000666000000000000000000000232612117455122015041 0ustar rootrootFormEncode ========== 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-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-1.3.0/docs/modules.txt0000666000000000000000000000057411767074160015416 0ustar rootrootReference ========= .. 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-1.3.0/docs/ToDo.txt0000666000000000000000000000211311767074160014602 0ustar rootroot++++++++++++ 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-1.3.0/docs/whatsnew-1.2.5.txt0000666000000000000000000000250712117455122016234 0ustar rootrootWhat'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-1.3.0/docs/_themes/0000775000000000000000000000000012617165271014620 5ustar rootrootFormEncode-1.3.0/docs/_themes/old/0000775000000000000000000000000012617165271015376 5ustar rootrootFormEncode-1.3.0/docs/_themes/old/static/0000775000000000000000000000000012617165271016665 5ustar rootrootFormEncode-1.3.0/docs/_themes/old/static/old.css0000666000000000000000000001454111767074160020165 0ustar rootroot/* :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-1.3.0/docs/history.txt0000666000000000000000000000347111767074160015446 0ustar rootrootOn 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-1.3.0/docs/Design.txt0000666000000000000000000002044311767074160015154 0ustar rootroot+++++++++++++++++ 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-1.3.0/docs/htmlfill.txt0000666000000000000000000000655711767074160015570 0ustar rootroot.. 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-1.3.0/docs/modules/0000775000000000000000000000000012617165271014644 5ustar rootrootFormEncode-1.3.0/docs/modules/variabledecode.txt0000666000000000000000000000056311767074160020345 0ustar rootroot: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-1.3.0/docs/modules/validators.txt0000666000000000000000000000310012465407010017540 0ustar rootroot: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-1.3.0/docs/modules/schema.txt0000666000000000000000000000031611767074160016650 0ustar rootroot:mod:`formencode.schema` -- Validate complete forms =================================================== .. automodule:: formencode.schema Module Contents --------------- .. autoclass:: Schema FormEncode-1.3.0/docs/modules/htmlrename.txt0000666000000000000000000000040711767074160017545 0ustar rootroot:mod:`formencode.htmlrename` -- Rename fields in an HTML form ============================================================= .. automodule:: formencode.htmlrename Module Contents --------------- .. autofunction:: rename .. autofunction:: add_prefix FormEncode-1.3.0/docs/modules/htmlfill_schemabuilder.txt0000666000000000000000000000046311767074160022115 0ustar rootroot:mod:`formencode.htmlfill_schemabuilder` -- Read a Schema from an HTML Form =========================================================================== .. automodule:: formencode.htmlfill_schemabuilder Module Contents --------------- .. autofunction:: parse_schema .. autoclass:: SchemaBuilder FormEncode-1.3.0/docs/modules/declarative.txt0000666000000000000000000000041311767074160017671 0ustar rootroot:mod:`formencode.declarative` -- Base class for Validators ========================================================== .. automodule:: formencode.declarative Module Contents --------------- .. autoclass:: Declarative .. autofunction:: classinstancemethod FormEncode-1.3.0/docs/modules/doctest_xml_compare.txt0000666000000000000000000000046611767074160021451 0ustar rootroot:mod:`formencode.doctest_xml_compare` -- XML-based comparison of Doctest output =============================================================================== .. automodule:: formencode.doctest_xml_compare Module Contents --------------- .. autofunction:: xml_compare .. autofunction:: install FormEncode-1.3.0/docs/modules/htmlfill.txt0000666000000000000000000000073511767074160017230 0ustar rootroot: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-1.3.0/docs/modules/compound.txt0000666000000000000000000000041411767074160017233 0ustar rootroot:mod:`formencode.compound` -- Validate with multiple validators =============================================================== .. automodule:: formencode.compound Module Contents --------------- .. autoclass:: All .. autoclass:: Any .. autoclass:: Pipe FormEncode-1.3.0/docs/modules/exc.txt0000666000000000000000000000034311767074160016167 0ustar rootroot:mod:`formencode.exc` -- Custom exceptions and warnings =============================================================== .. automodule:: formencode.exc Module Contents --------------- .. autoclass:: FERuntimeWarning FormEncode-1.3.0/docs/modules/htmlgen.txt0000666000000000000000000000041211767074160017043 0ustar rootroot:mod:`formencode.htmlgen` -- Convenient building of ElementTree nodes ===================================================================== .. automodule:: formencode.htmlgen Module Contents --------------- .. autoclass:: _HTML .. autoclass:: Element FormEncode-1.3.0/docs/modules/national.txt0000666000000000000000000000211012117455062017201 0ustar rootroot: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-1.3.0/docs/modules/api.txt0000666000000000000000000000061311767074160016161 0ustar rootroot: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-1.3.0/docs/modules/foreach.txt0000666000000000000000000000032411767074160017016 0ustar rootroot:mod:`formencode.foreach` -- Validate items in a list ===================================================== .. automodule:: formencode.foreach Module Contents --------------- .. autoclass:: ForEach FormEncode-1.3.0/docs/community.txt0000666000000000000000000000156012023317120015744 0ustar rootrootFormEncode 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-1.3.0/docs/Validator.txt0000666000000000000000000006370312465407010015664 0ustar rootroot.. 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']) >>> if unicode is str: # 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, 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, 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 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 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 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 appropirate 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-1.3.0/docs/whatsnew-1.3.txt0000666000000000000000000000415412465407010016071 0ustar rootrootWhat'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. Documentation Enhancements -------------------------- FormEncode-1.3.0/docs/whatsnew-0-to-1.2.4.txt0000666000000000000000000003351211767074160017021 0ustar rootrootWhat'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-1.3.0/docs/download.txt0000666000000000000000000000060512023317120015526 0ustar rootrootDownloads +++++++++ 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-1.3.0/docs/i18n.txt0000666000000000000000000000206611767074160014523 0ustar rootrootFormEncode 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-1.3.0/setup.cfg0000666000000000000000000000120312465412710014055 0ustar rootroot[nosetests] detailed-errors = 1 [compile_catalog] domain = FormEncode directory = formencode/i18n statistics = true [extract_messages] add_comments = TRANSLATORS: output_file = formencode/i18n/FormEncode.pot charset = utf-8 msgid_bugs_address = formencode-discuss@lists.sf.net width = 80 [init_catalog] domain = FormEncode input_file = formencode/i18n/FormEncode.pot output_dir = formencode/i18n [update_catalog] domain = FormEncode input_file = formencode/i18n/FormEncode.pot output_dir = formencode/i18n previous = true [wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 FormEncode-1.3.0/README.rst0000666000000000000000000000164412465407010013731 0ustar rootrootFormEncode ========== .. image:: https://secure.travis-ci.org/formencode/formencode.png?branch=master :target: https://travis-ci.org/formencode/formencode :alt: Travis CI continuous integration 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/ Changes ------- Added a validator that can require one or more fields based on the value of another field. A german howto can be found here: http://techblog.auf-nach-mallorca.info/2014/08/19/dynamische_formulare_validieren_mit_formencode/ Courtesy of the developers of http://www.auf-nach-mallorca.info FormEncode-1.3.0/FormEncode.egg-info/0000775000000000000000000000000012617165271015757 5ustar rootrootFormEncode-1.3.0/FormEncode.egg-info/SOURCES.txt0000666000000000000000000001111112465412710017632 0ustar rootrootMANIFEST.in README.rst setup.cfg setup.py FormEncode.egg-info/PKG-INFO FormEncode.egg-info/SOURCES.txt FormEncode.egg-info/dependency_links.txt FormEncode.egg-info/not-zip-safe FormEncode.egg-info/requires.txt FormEncode.egg-info/top_level.txt docs/Design.txt docs/ToDo.txt docs/Validator.txt docs/community.txt docs/download.txt docs/history.txt docs/htmlfill.txt docs/i18n.txt docs/index.txt docs/modules.txt docs/whatsnew-0-to-1.2.4.txt docs/whatsnew-1.2.5.txt docs/whatsnew-1.3.txt docs/_themes/old/static/old.css docs/modules/api.txt docs/modules/compound.txt docs/modules/declarative.txt docs/modules/doctest_xml_compare.txt docs/modules/exc.txt docs/modules/foreach.txt docs/modules/htmlfill.txt docs/modules/htmlfill_schemabuilder.txt docs/modules/htmlgen.txt docs/modules/htmlrename.txt docs/modules/national.txt docs/modules/schema.txt docs/modules/validators.txt docs/modules/variabledecode.txt formencode/__init__.py formencode/api.py formencode/compound.py formencode/context.py formencode/declarative.py formencode/doctest_xml_compare.py formencode/exc.py formencode/fieldstorage.py formencode/foreach.py formencode/htmlfill.py formencode/htmlfill_schemabuilder.py formencode/htmlgen.py formencode/htmlrename.py formencode/interfaces.py formencode/national.py formencode/rewritingparser.py formencode/schema.py formencode/validators.py formencode/variabledecode.py formencode/i18n/FormEncode.pot formencode/i18n/cs/LC_MESSAGES/FormEncode.mo formencode/i18n/cs/LC_MESSAGES/FormEncode.po formencode/i18n/da/LC_MESSAGES/FormEncode.mo formencode/i18n/da/LC_MESSAGES/FormEncode.po formencode/i18n/de/LC_MESSAGES/FormEncode.mo formencode/i18n/de/LC_MESSAGES/FormEncode.po formencode/i18n/el/LC_MESSAGES/FormEncode.mo formencode/i18n/el/LC_MESSAGES/FormEncode.po formencode/i18n/es/LC_MESSAGES/FormEncode.mo formencode/i18n/es/LC_MESSAGES/FormEncode.po formencode/i18n/et/LC_MESSAGES/FormEncode.mo formencode/i18n/et/LC_MESSAGES/FormEncode.po formencode/i18n/fi/LC_MESSAGES/FormEncode.mo formencode/i18n/fi/LC_MESSAGES/FormEncode.po formencode/i18n/fr/LC_MESSAGES/FormEncode.mo formencode/i18n/fr/LC_MESSAGES/FormEncode.po formencode/i18n/it/LC_MESSAGES/FormEncode.mo formencode/i18n/it/LC_MESSAGES/FormEncode.po formencode/i18n/ja/LC_MESSAGES/FormEncode.mo formencode/i18n/ja/LC_MESSAGES/FormEncode.po formencode/i18n/ko/LC_MESSAGES/FormEncode.mo formencode/i18n/ko/LC_MESSAGES/FormEncode.po formencode/i18n/lt/LC_MESSAGES/FormEncode.mo formencode/i18n/lt/LC_MESSAGES/FormEncode.po formencode/i18n/nb_NO/LC_MESSAGES/FormEncode.mo formencode/i18n/nb_NO/LC_MESSAGES/FormEncode.po formencode/i18n/nl/LC_MESSAGES/FormEncode.mo formencode/i18n/nl/LC_MESSAGES/FormEncode.po formencode/i18n/pl/LC_MESSAGES/FormEncode.mo formencode/i18n/pl/LC_MESSAGES/FormEncode.po formencode/i18n/pt_BR/LC_MESSAGES/FormEncode.mo formencode/i18n/pt_BR/LC_MESSAGES/FormEncode.po formencode/i18n/pt_PT/LC_MESSAGES/FormEncode.mo formencode/i18n/pt_PT/LC_MESSAGES/FormEncode.po formencode/i18n/ru/LC_MESSAGES/FormEncode.mo formencode/i18n/ru/LC_MESSAGES/FormEncode.po formencode/i18n/sk/LC_MESSAGES/FormEncode.mo formencode/i18n/sk/LC_MESSAGES/FormEncode.po formencode/i18n/sl/LC_MESSAGES/FormEncode.mo formencode/i18n/sl/LC_MESSAGES/FormEncode.po formencode/i18n/sr/LC_MESSAGES/FormEncode.mo formencode/i18n/sr/LC_MESSAGES/FormEncode.po formencode/i18n/sv/LC_MESSAGES/FormEncode.mo formencode/i18n/sv/LC_MESSAGES/FormEncode.po formencode/i18n/tr/LC_MESSAGES/FormEncode.mo formencode/i18n/tr/LC_MESSAGES/FormEncode.po formencode/i18n/zh_CN/LC_MESSAGES/FormEncode.mo formencode/i18n/zh_CN/LC_MESSAGES/FormEncode.po formencode/i18n/zh_TW/LC_MESSAGES/FormEncode.mo formencode/i18n/zh_TW/LC_MESSAGES/FormEncode.po formencode/javascript/ordering.js formencode/tests/__init__.py formencode/tests/non_empty.txt formencode/tests/test_cc.py formencode/tests/test_compound.py formencode/tests/test_context.py formencode/tests/test_declarative.py formencode/tests/test_doctest_xml_compare.py formencode/tests/test_doctests.py formencode/tests/test_email.py formencode/tests/test_htmlfill.py formencode/tests/test_htmlgen.py formencode/tests/test_htmlrename.py formencode/tests/test_i18n.py formencode/tests/test_schema.py formencode/tests/test_subclassing.py formencode/tests/test_subclassing_old.py formencode/tests/test_validators.py formencode/tests/test_variabledecode.py formencode/tests/htmlfill_data/data-error1.txt formencode/tests/htmlfill_data/data-fill1.txt formencode/tests/htmlfill_data/data-fill2.txt formencode/tests/htmlfill_data/data-fill3.txt formencode/tests/htmlfill_data/data-fill4.txt formencode/tests/htmlfill_data/data-form-last-element.txt formencode/tests/htmlfill_data/data-schema1.txtFormEncode-1.3.0/FormEncode.egg-info/requires.txt0000666000000000000000000000004412465412710020351 0ustar rootroot [testing] nose pycountry dnspython FormEncode-1.3.0/FormEncode.egg-info/PKG-INFO0000666000000000000000000000165712465412710017061 0ustar rootrootMetadata-Version: 1.1 Name: FormEncode Version: 1.3.0 Summary: HTML form validation, generation, and conversion package Home-page: http://formencode.org Author: Ian Bicking Author-email: ianb@colorstudy.com License: PSF Description: FormEncode validates and converts nested structures. It allows for a declarative form of defining the validation, and decoupled processes for filling and generating forms. The official repo is at GitHub: https://github.com/formencode/formencode Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Python Software Foundation License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Software Development :: Libraries :: Python Modules FormEncode-1.3.0/FormEncode.egg-info/top_level.txt0000666000000000000000000000001312465412710020477 0ustar rootrootformencode FormEncode-1.3.0/FormEncode.egg-info/not-zip-safe0000666000000000000000000000000111767074220020205 0ustar rootroot FormEncode-1.3.0/FormEncode.egg-info/dependency_links.txt0000666000000000000000000000000112465412710022021 0ustar rootroot FormEncode-1.3.0/formencode/0000775000000000000000000000000012617165271014365 5ustar rootrootFormEncode-1.3.0/formencode/compound.py0000666000000000000000000002201212141700570016547 0ustar rootroot""" Validators for applying validations in sequence. """ from .api import (FancyValidator, Identity, Invalid, NoDefault, Validator, is_validator) __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 new_attrs.iteritems(): 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 = filter(lambda v: v and v is not Identity, validators) 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-1.3.0/formencode/variabledecode.py0000666000000000000000000001263212465407010017665 0ustar rootroot""" Takes GET/POST variable dictionary, as might be returned by ``cgi``, and turns them into lists and dictionaries. Keys (variable names) can have subkeys, with a ``.`` and can be numbered with ``-``, like ``a.b-3=something`` means that the value ``a`` is a dictionary with a key ``b``, and ``b`` is a list, the third(-ish) element with the value ``something``. Numbers are used to sort, missing numbers are ignored. This doesn't deal with multiple keys, like in a query string of ``id=10&id=20``, which returns something like ``{'id': ['10', '20']}``. That's left to someplace else to interpret. If you want to represent lists in this model, you use indexes, and the lists are explicitly ordered. If you want to change the character that determines when to split for a dict or list, both variable_decode and variable_encode take dict_char and list_char keyword args. For example, to have the GET/POST variables, ``a_1=something`` as a list, you would use a ``list_char='_'``. """ from .api import FancyValidator __all__ = ['variable_decode', 'variable_encode', 'NestedVariables'] def variable_decode(d, dict_char='.', list_char='-'): """ Decode the flat dictionary d into a nested structure. """ result = {} dicts_to_sort = set() known_lengths = {} for key, value in d.iteritems(): keys = key.split(dict_char) new_keys = [] was_repetition_count = False for key in keys: if key.endswith('--repetitions'): key = key[:-len('--repetitions')] new_keys.append(key) known_lengths[tuple(new_keys)] = int(value) was_repetition_count = True break elif list_char in key: maybe_key, index = key.split(list_char, 1) if not index.isdigit(): new_keys.append(key) else: key = maybe_key new_keys.append(key) dicts_to_sort.add(tuple(new_keys)) new_keys.append(int(index)) else: new_keys.append(key) if was_repetition_count: continue place = result for i in range(len(new_keys) - 1): try: if not isinstance(place[new_keys[i]], dict): place[new_keys[i]] = {None: place[new_keys[i]]} place = place[new_keys[i]] except KeyError: place[new_keys[i]] = {} place = place[new_keys[i]] if new_keys[-1] in place: if isinstance(place[new_keys[-1]], dict): place[new_keys[-1]][None] = value elif isinstance(place[new_keys[-1]], list): if isinstance(value, list): place[new_keys[-1]].extend(value) else: place[new_keys[-1]].append(value) else: if isinstance(value, list): place[new_keys[-1]] = [place[new_keys[-1]]] place[new_keys[-1]].extend(value) else: place[new_keys[-1]] = [place[new_keys[-1]], value] else: place[new_keys[-1]] = value to_sort_list = sorted(dicts_to_sort, key=len, reverse=True) for key in to_sort_list: to_sort = result source = None last_key = None for sub_key in key: source = to_sort last_key = sub_key to_sort = to_sort[sub_key] if None in to_sort: noneVals = [(0, x) for x in to_sort.pop(None)] noneVals.extend(to_sort.iteritems()) to_sort = noneVals else: to_sort = to_sort.iteritems() to_sort = [x[1] for x in sorted(to_sort)] if key in known_lengths: if len(to_sort) < known_lengths[key]: to_sort.extend([''] * (known_lengths[key] - len(to_sort))) source[last_key] = to_sort return result def variable_encode(d, prepend='', result=None, add_repetitions=True, dict_char='.', list_char='-'): """ Encode a nested structure into a flat dictionary. """ if result is None: result = {} if isinstance(d, dict): for key, value in d.iteritems(): if key is None: name = prepend elif not prepend: name = key else: name = "%s%s%s" % (prepend, dict_char, key) variable_encode(value, name, result, add_repetitions, dict_char=dict_char, list_char=list_char) elif isinstance(d, list): for i, value in enumerate(d): variable_encode(value, "%s%s%i" % (prepend, list_char, i), result, add_repetitions, dict_char=dict_char, list_char=list_char) if add_repetitions: repName = ('%s--repetitions' % prepend if prepend else '__repetitions__') result[repName] = str(len(d)) else: result[prepend] = d return result class NestedVariables(FancyValidator): def _convert_to_python(self, value, state): return variable_decode(value) def _convert_from_python(self, value, state): return variable_encode(value) def empty_value(self, value): return {} FormEncode-1.3.0/formencode/rewritingparser.py0000666000000000000000000001230712141700570020160 0ustar rootroot import HTMLParser import re try: from html import escape except ImportError: # Python < 3.2 from cgi import escape from htmlentitydefs import name2codepoint def html_quote(v): if v is None: return '' if hasattr(v, '__html__'): return v.__html__() if isinstance(v, basestring): return escape(v, True) if hasattr(v, '__unicode__'): v = unicode(v) else: v = str(v) return escape(v, True) class RewritingParser(HTMLParser.HTMLParser): listener = None skip_next = False def __init__(self): self._content = [] HTMLParser.HTMLParser.__init__(self) def feed(self, data): self.data_is_str = isinstance(data, str) self.source = data self.lines = data.split('\n') self.source_pos = 1, 0 if self.listener: self.listener.reset() HTMLParser.HTMLParser.feed(self, data) _entityref_re = re.compile('&([a-zA-Z][-.a-zA-Z\d]*);') _charref_re = re.compile('&#(\d+|[xX][a-fA-F\d]+);') def unescape(self, s): s = self._entityref_re.sub(self._sub_entityref, s) s = self._charref_re.sub(self._sub_charref, s) return s def _sub_entityref(self, match): name = match.group(1) if name not in name2codepoint: # If we don't recognize it, pass it through as though it # wasn't an entity ref at all return match.group(0) return unichr(name2codepoint[name]) def _sub_charref(self, match): num = match.group(1) if num.lower().startswith('x'): num = int(num[1:], 16) else: num = int(num) return unichr(num) def handle_misc(self, whatever): self.write_pos() handle_charref = handle_misc handle_entityref = handle_misc handle_data = handle_misc handle_comment = handle_misc handle_decl = handle_misc handle_pi = handle_misc unknown_decl = handle_misc handle_endtag = handle_misc def write_tag(self, tag, attrs, startend=False): attr_text = ''.join(' %s="%s"' % (n, html_quote(v)) for (n, v) in attrs if not n.startswith('form:')) if startend: attr_text += " /" self.write_text('<%s%s>' % (tag, attr_text)) def skip_output(self): return False def write_pos(self): cur_line, cur_offset = self.getpos() if self.skip_output(): self.source_pos = self.getpos() return if self.skip_next: self.skip_next = False self.source_pos = self.getpos() return if cur_line == self.source_pos[0]: self.write_text( self.lines[cur_line - 1][self.source_pos[1]:cur_offset]) else: self.write_text( self.lines[self.source_pos[0] - 1][self.source_pos[1]:]) self.write_text('\n') for i in range(self.source_pos[0] + 1, cur_line): self.write_text(self.lines[i - 1]) self.write_text('\n') self.write_text(self.lines[cur_line - 1][:cur_offset]) self.source_pos = self.getpos() def write_text(self, text): self._content.append(text) def has_attr(self, attr, name): for a in attr: if a[0].lower() == name: return True return False def get_attr(self, attr, name, default=None): for a in attr: if a[0].lower() == name: return a[1] return default def set_attr(self, attr, name, value): for i, a in enumerate(attr): if a[0].lower() == name: attr[i] = (name, value) return attr.append((name, value)) def del_attr(self, attr, name): for i, a in enumerate(attr): if a[0].lower() == name: del attr[i] break def add_class(self, attr, class_name): current = self.get_attr(attr, 'class', '') new = current + ' ' + class_name self.set_attr(attr, 'class', new.strip()) def text(self): try: return self._text except AttributeError: raise Exception( "You must .close() a parser instance before getting " "the text from it") def _get_text(self): try: return ''.join( t for t in self._content if not isinstance(t, tuple)) except UnicodeDecodeError as e: if self.data_is_str: e.reason += ( " the form was passed in as an encoded string, but" " some data or error messages were unicode strings;" " the form should be passed in as a unicode string") else: e.reason += ( " the form was passed in as an unicode string, but" " some data or error message was an encoded string;" " the data and error messages should be passed in as" " unicode strings") raise FormEncode-1.3.0/formencode/__init__.py0000666000000000000000000000063512117455122016474 0ustar rootroot# formencode package 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 FormEncode-1.3.0/formencode/htmlfill.py0000666000000000000000000005315512465407010016554 0ustar rootroot""" Parser for HTML forms, that fills in defaults and errors. See ``render``. """ import re from formencode.rewritingparser import RewritingParser, html_quote __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): """ 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. """ 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, ) 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): 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, basestring): 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 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, basestring): if hasattr(str1, '__unicode__'): str1 = unicode(str1) else: str1 = str(str1) if type(str1) == type(str2): return str1 == str2 if isinstance(str1, unicode): 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 unused_errors.iteritems(): 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 (unicode 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 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 (unicode is not str # Python 2 and isinstance(name, unicode) 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 self.add_attributes[name].iteritems(): 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, ( "