diff --git a/.gitignore b/.gitignore index e3970e6a..130f6aeb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,11 +4,13 @@ docs/_build dist/ *.tox -# PyCharm users, please keep your data locally. +# IDE users, please keep your data locally .idea/ +.project +.pydevproject # When you run ``python setup.py [test|nosetests]`` -# from project's root tree, the script checks [and downloads, if necessary] +# from project's root tree, the script checks [and downloads, if necessary] # packages which are specified in setup.py -> tests_require. # Therefore we must explicitly ignore all downloaded *.egg packages. *.egg diff --git a/docs/conf.py b/docs/conf.py index cbee49ee..6a520e78 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,217 +1,217 @@ -# -*- coding: utf-8 -*- -# -# FormEncode documentation build configuration file, created by -# sphinx-quickstart on Tue Aug 30 08:48:54 2011. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -import sys, os - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) - -# -- General configuration ----------------------------------------------------- - -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage'] - -# Add any paths that contain templates here, relative to this directory. -#templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.txt' - -# The encoding of source files. -#source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'FormEncode' -copyright = u'2008-2011, Ian Bicking and Contributors' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = '1.2' -# The full version, including alpha/beta/rc tags. -release = '1.2.4' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -#html_theme = 'old' -html_theme = 'default' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -html_theme_path = ['_themes'] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - -# Output file base name for HTML help builder. -htmlhelp_basename = 'FormEncode_doc' - - -# -- Options for LaTeX output -------------------------------------------------- - -# The paper size ('letter' or 'a4'). -#latex_paper_size = 'letter' - -# The font size ('10pt', '11pt' or '12pt'). -#latex_font_size = '10pt' - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). -latex_documents = [ - ('index', 'FormEncode.tex', u'FormEncode Documentation', - u'Ian Bicking', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Additional stuff for the LaTeX preamble. -#latex_preamble = '' - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - - -# -- Options for manual page output -------------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'formencode', u'FormEncode Documentation', - [u'Ian Bicking'], 1) -] +# -*- coding: utf-8 -*- +# +# FormEncode documentation build configuration file, created by +# sphinx-quickstart on Tue Aug 30 08:48:54 2011. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath('..')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage'] + +# Add any paths that contain templates here, relative to this directory. +#templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.txt' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'FormEncode' +copyright = u'2008-2012, Ian Bicking and Contributors' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '1.2' +# The full version, including alpha/beta/rc tags. +release = '1.2.4' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +#html_theme = 'old' +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +html_theme_path = ['_themes'] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'FormEncode_doc' + + +# -- Options for LaTeX output -------------------------------------------------- + +# The paper size ('letter' or 'a4'). +#latex_paper_size = 'letter' + +# The font size ('10pt', '11pt' or '12pt'). +#latex_font_size = '10pt' + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'FormEncode.tex', u'FormEncode Documentation', + u'Ian Bicking', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Additional stuff for the LaTeX preamble. +#latex_preamble = '' + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'formencode', u'FormEncode Documentation', + [u'Ian Bicking'], 1) +] diff --git a/formencode/api.py b/formencode/api.py index 7b2bb6f4..0275e183 100644 --- a/formencode/api.py +++ b/formencode/api.py @@ -90,25 +90,25 @@ class Invalid(Exception): This is raised in response to invalid input. It has several public attributes: - msg: + ``msg``: The message, *without* values substituted. For instance, if you want HTML quoting of values, you can apply that. - substituteArgs: - The arguments (a dictionary) to go with `msg`. - str(self): + ``substituteArgs``: + The arguments (a dictionary) to go with ``msg``. + ``str(self)``: The message describing the error, with values substituted. - value: + ``value``: The offending (invalid) value. - state: + ``state``: The state that went with this validator. This is an application-specific object. - error_list: + ``error_list``: If this was a compound validator that takes a repeating value, and sub-validator(s) had errors, then this is a list of those exceptions. The list will be the same length as the number of values -- valid values will have None instead of an exception. - error_dict: - Like `error_list`, but for dictionary compound validators. + ``error_dict``: + Like ``error_list``, but for dictionary compound validators. """ def __init__(self, msg, @@ -167,9 +167,9 @@ def unpack_errors(self, encode_variables=False, dict_char='.', result[name] = item.unpack_errors() if encode_variables: import variabledecode - result = variabledecode.variable_encode(result, add_repetitions=False, - dict_char=dict_char, - list_char=list_char) + result = variabledecode.variable_encode( + result, add_repetitions=False, + dict_char=dict_char, list_char=list_char) for key in result.keys(): if not result[key]: del result[key] @@ -187,8 +187,8 @@ def unpack_errors(self, encode_variables=False, dict_char='.', class Validator(declarative.Declarative): """ - The base class of most validators. See `IValidator` for more, and - `FancyValidator` for the more common (and more featureful) class. + The base class of most validators. See ``IValidator`` for more, and + ``FancyValidator`` for the more common (and more featureful) class. """ _messages = {} @@ -299,8 +299,8 @@ def _initialize_docstring(cls): doc.append('\n\n**Messages**\n\n') for name, default in messages: default = re.sub(r'(%\(.*?\)[rsifcx])', r'``\1``', default) - doc.append('``'+name+'``:\n') - doc.append(' '+default+'\n\n') + doc.append('``' + name + '``:\n') + doc.append(' ' + default + '\n\n') cls.__doc__ = ''.join(doc) _initialize_docstring = classmethod(_initialize_docstring) @@ -322,39 +322,45 @@ class FancyValidator(Validator): Validators have two important external methods: - * .to_python(value, state): + ``.to_python(value, state)``: Attempts to convert the value. If there is a problem, or the value is not valid, an Invalid exception is raised. The argument for this exception is the (potentially HTML-formatted) error message to give the user. - * .from_python(value, state): - Reverses to_python. + ``.from_python(value, state)``: + Reverses ``.to_python()``. - There are five important methods for subclasses to override, - however none of these *have* to be overridden, only the ones that - are appropriate for the validator: + These two external methods make use of the following four + important internal methods that can be overridden. However, + none of these *have* to be overridden, only the ones that + are appropriate for the validator. - * __init__(): - if the `declarative.Declarative` model doesn't work for this. + ``._to_python(value, state)``: + This method converts the source to a Python value. It returns + the converted value, or raises an Invalid exception if the + conversion cannot be done. The argument to this exception + should be the error message. Contrary to ``.to_python()`` it is + only meant to convert the value, not to fully validate it. - * .validate_python(value, state): - This should raise an error if necessary. The value is a Python - object, either the result of to_python, or the input to - from_python. + ``._from_python(value, state)``: + Should undo ``._to_python()`` in some reasonable way, returning + a string. - * .validate_other(value, state): - Validates the source, before to_python, or after from_python. - It's more common to use `.validate_python()` however. + ``.validate_other(value, state)``: + Validates the source, before ``._to_python()``, or after + ``._from_python()``. It's usually more convenient to use + ``.validate_python()`` however. - * ._to_python(value, state): - This returns the converted value, or raises an Invalid - exception if there is an error. The argument to this exception - should be the error message. + ``.validate_python(value, state)``: + Validates a Python value, either the result of ``._to_python()``, + or the input to ``._from_python()``. - * ._from_python(value, state): - Should undo .to_python() in some reasonable way, returning - a string. + You should make sure that all possible validation errors are + raised in at least one these four methods, not matter which. + + Subclasses can also override the ``__init__()`` method + if the ``declarative.Declarative`` model doesn't work for this. Validators should have no internal state besides the values given at instantiation. They should be reusable and @@ -362,32 +368,38 @@ class FancyValidator(Validator): All subclasses can take the arguments/instance variables: - * if_empty: + ``if_empty``: If set, then this value will be returned if the input evaluates to false (empty list, empty string, None, etc), but not the 0 or False objects. This only applies to ``.to_python()``. - * not_empty: + ``not_empty``: If true, then if an empty value is given raise an error. (Both with ``.to_python()`` and also ``.from_python()`` if ``.validate_python`` is true). - * strip: + ``strip``: If true and the input is a string, strip it (occurs before empty tests). - * if_invalid: + ``if_invalid``: If set, then when this validator would raise Invalid during ``.to_python()``, instead return this value. - * if_invalid_python: + ``if_invalid_python``: If set, when the Python value (converted with ``.from_python()``) is invalid, this value will be returned. - * accept_python: + ``accept_python``: If True (the default), then ``.validate_python()`` and ``.validate_other()`` will not be called when ``.from_python()`` is used. + + These parameters are handled at the level of the external + methods ``.to_python()`` and ``.from_python`` already; + if you overwrite one of the internal methods, you usually + don't need to care about them. + """ if_invalid = NoDefault @@ -496,4 +508,3 @@ def _validate_noop(self, value, state=None): validate_python = validate_other = _validate_noop _to_python = None _from_python = None -