pax_global_header 0000666 0000000 0000000 00000000064 14226614013 0014511 g ustar 00root root 0000000 0000000 52 comment=2320f8bb2537869721abf4103a5b4e672fd3049c
wtforms-json-0.3.5/ 0000775 0000000 0000000 00000000000 14226614013 0014166 5 ustar 00root root 0000000 0000000 wtforms-json-0.3.5/.gitignore 0000664 0000000 0000000 00000000403 14226614013 0016153 0 ustar 00root root 0000000 0000000 *.py[co]
# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
#Translations
*.mo
#Mr Developer
.mr.developer.cfg
# Built docs
docs/_build/
wtforms-json-0.3.5/.gitmodules 0000664 0000000 0000000 00000000162 14226614013 0016342 0 ustar 00root root 0000000 0000000 [submodule "docs/_themes"]
path = docs/_themes
url = https://github.com/mitsuhiko/flask-sphinx-themes.git
wtforms-json-0.3.5/.isort.cfg 0000664 0000000 0000000 00000000174 14226614013 0016067 0 ustar 00root root 0000000 0000000 [settings]
known_first_party=wtforms_json,tests
line_length=79
multi_line_output=3
not_skip=__init__.py
order_by_type=false
wtforms-json-0.3.5/.travis.yml 0000664 0000000 0000000 00000000411 14226614013 0016273 0 ustar 00root root 0000000 0000000 language: python
python:
- 2.7
- 3.3
- 3.4
- 3.5
- 3.6
env:
matrix:
- WTFORMS=WTForms==1.0.5
- WTFORMS=WTForms==2.1
install:
- "pip install $WTFORMS"
- pip install -e ".[test]"
script:
- flake8 wtforms_json tests
- python setup.py test
wtforms-json-0.3.5/CHANGES.rst 0000664 0000000 0000000 00000004420 14226614013 0015770 0 ustar 00root root 0000000 0000000 Changelog
---------
Here you can see the full list of changes between each WTForms-JSON release.
0.3.5 (2022-04-16)
^^^^^^^^^^^^^^^^^^
- Added support for arbitrary kwargs when monkey patching Field.process (#60, pull request courtesy alanhamlett)
0.3.4 (2022-02-22)
^^^^^^^^^^^^^^^^^^
- Added Python 3.10 support (#61, pull request courtesy keaysma)
0.3.3 (2017-07-07)
^^^^^^^^^^^^^^^^^^
- Update WTForms requirement (#51, pull request courtesy quantus)
0.3.2 (2017-07-05)
^^^^^^^^^^^^^^^^^^
- Use wtforms_alchemy for importing QuerySelectField if it is installed (#50, pull request courtesy Lee-W)
0.3.1 (2017-03-05)
^^^^^^^^^^^^^^^^^^
- Fixed default value handling for StringField (#49, pull request courtesy noirbizarre)
- Added py36 to test matrix
0.3.0 (2016-08-30)
^^^^^^^^^^^^^^^^^^
- Added support for WTForms 3.0
- Dropped Python 2.6 support
0.2.10 (2015-03-28)
^^^^^^^^^^^^^^^^^^
- Fixed process_formdata support for python3
- Added flake8 and isort checks
0.2.9 (2015-02-28)
^^^^^^^^^^^^^^^^^^
- Fixed inheritance handling with FieldLists and FormFields
0.2.8 (2014-09-21)
^^^^^^^^^^^^^^^^^^
- Fixed falsy boolean value handling
0.2.7 (2014-09-01)
^^^^^^^^^^^^^^^^^^
- Only flatten dict if field is an instance of FormField
0.2.6 (2014-05-24)
^^^^^^^^^^^^^^^^^^
- Made ``skip_unknown_keys=True`` prevent raising errors from keys that exist in
form class but are not form fields
0.2.5 (2013-12-16)
^^^^^^^^^^^^^^^^^^
- Fixed ``skip_unknown_keys`` option passing from ``from_json`` to
``flatten_json`` (#17)
0.2.4 (2013-11-17)
^^^^^^^^^^^^^^^^^^
- Fixed object value setting in ``from_json``
- Prepared support for WTForms 2.0
0.2.3 (2013-11-11)
^^^^^^^^^^^^^^^^^^
- Added support for ``QuerySelectField`` and ``QuerySelectMultipleField``
0.2.2 (2013-08-30)
^^^^^^^^^^^^^^^^^^
- Configurable unknown json key handling
0.2.1 (2013-08-19)
^^^^^^^^^^^^^^^^^^
- Custom ``SelectField`` support
0.2.0 (2013-07-26)
^^^^^^^^^^^^^^^^^^
- Rewritten ``flatten_json`` (now supports ``SelectMultipleField``s)
0.1.5 (2013-07-25)
^^^^^^^^^^^^^^^^^^
- Added enhanced unicode coercion
- Package six added to requirements
0.1.4 (2013-03-16)
^^^^^^^^^^^^^^^^^^
- Updated WTForms requirements
0.1.3 (2013-03-01)
^^^^^^^^^^^^^^^^^^
- Fixed 'First example' in docs
wtforms-json-0.3.5/LICENSE 0000664 0000000 0000000 00000002642 14226614013 0015177 0 ustar 00root root 0000000 0000000 Copyright (c) 2012-2014, Konsta Vesterinen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The names of the contributors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
wtforms-json-0.3.5/MANIFEST.in 0000664 0000000 0000000 00000000232 14226614013 0015721 0 ustar 00root root 0000000 0000000 include CHANGES.rst LICENSE README.rst
include tests.py
recursive-include docs *
recursive-exclude docs *.pyc
prune docs/_build
exclude docs/_themes/.git
wtforms-json-0.3.5/README.rst 0000664 0000000 0000000 00000000570 14226614013 0015657 0 ustar 00root root 0000000 0000000 wtforms-json
============
Adds smart json support for `WTForms`_. Useful for when using WTForms with
RESTful APIs.
.. _WTForms: https://wtforms.readthedocs.org/en/latest/
Resources
---------
- `Documentation `_
- `Issue Tracker `_
- `Code `_
wtforms-json-0.3.5/docs/ 0000775 0000000 0000000 00000000000 14226614013 0015116 5 ustar 00root root 0000000 0000000 wtforms-json-0.3.5/docs/Makefile 0000664 0000000 0000000 00000012724 14226614013 0016564 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/wtforms-json.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/wtforms-json.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/wtforms-json"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/wtforms-json"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
wtforms-json-0.3.5/docs/conf.py 0000664 0000000 0000000 00000017651 14226614013 0016427 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# wtforms-json documentation build configuration file, created by
# sphinx-quickstart on Wed Aug 29 09:55:11 2012.
#
# 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('..'))
from wtforms_json import __version__
# -- 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.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'wtforms-json'
copyright = u'2012-2014, Konsta Vesterinen'
# 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 = __version__
# The full version, including alpha/beta/rc tags.
release = version
# 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 = '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 = []
# 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 = 'wtforms-jsondoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'wtforms-json.tex', u'wtforms-json Documentation',
u'Konsta Vesterinen', '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
# 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', 'wtforms-json', u'wtforms-json Documentation',
[u'Konsta Vesterinen'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'wtforms-json', u'wtforms-json Documentation',
u'Konsta Vesterinen', 'wtforms-json', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'wtforms': ('http://wtforms.readthedocs.org/en/latest/', None)
}
wtforms-json-0.3.5/docs/index.rst 0000664 0000000 0000000 00000007173 14226614013 0016767 0 ustar 00root root 0000000 0000000 WTForms-JSON
============
WTForms-JSON is a `WTForms`_ extension for JSON data handling.
.. _WTForms: https://wtforms.readthedocs.org/en/latest/
What does it do?
----------------
- Adds support for booleans (WTForms doesn't know how to handle `False` boolean
values)
- Adds support for ``None`` type :class:`~wtforms.fields.FormField` values
- Adds support for ``None`` type :class:`~wtforms.fields.Field` values
- Support for patch data requests with :attr:`patch_data`
:class:`~wtforms.form.Form` property
- Function for converting JSON data into dict that WTForms understands
(:func:`flatten_json` function)
Quickstart
----------
In order to start using WTForms-JSON, you need to first initialize the
extension. This monkey patches some classes and methods within WTForms and adds
JSON handling support::
import wtforms_json
wtforms_json.init()
First Example
-------------
After the extension has been initialized we can create an ordinary WTForms form.
Notice how we are initalizing the form using :meth:`from_json` class method::
from wtforms import Form
from wtforms.fields import BooleanField, FormField, TextField
class LocationForm(Form):
name = TextField()
address = TextField()
class EventForm(Form):
name = TextField()
is_public = BooleanField()
location = FormField(LocationForm)
json = {
'name': 'First Event',
'location': {'name': 'some location'},
}
form = EventForm.from_json(json)
Here :meth:`from_json` takes exactly the same parameters as
:meth:`Form.__init__ `.
If you want WTForms-JSON to throw errors when unknown json keys are encountered
just pass ``skip_unknown_keys=False`` to :meth:`from_json`::
json = {
'some_unknown_key': 'some_value'
}
# Throws exception
form = EventForm.from_json(json, skip_unknown_keys=False)
Using patch_data
----------------
The way forms usually work on websites is that they post all the data within
their fields. When working with APIs and JSON data it makes sense to not
actually post all the data that hasn't changed -- rather make so called patch
request which only post the data that the user actually changed.
You can get access to the patch data (data that only contains the actually set
fields or fields that have defaults and are required) with form's
:attr:`patch_data` property.
Now lets use the forms from the previous example::
>>> form.data
{
'name': 'First Event',
'is_public': False,
'location': {
'name': 'some location',
'address': None
}
}
>>> form.patch_data
{
'name': 'First Event',
'location': {
'name': 'some location'
}
}
Internals
---------
WTForm uses special flattened dict as a data parameter for forms. WTForms-JSON
provides a method for converting JSON into this format.
Note this is done automatically internally::
from wtforms import Form
from wtforms.fields import FormField, StringField
from wtforms_json import flatten_json
class FormB(Form):
b = TextField('B')
class FormA(Form):
a = FormField(FormB)
assert flatten_json({'a': {'b': 'c'}}) == {'a-b': 'c'}
This neat little function understands nested lists and dicts as well::
from wtforms_json import flatten_json
class FormC(Form):
c = IntegerField('C')
class FormB(Form):
b = FormField(FormC)
class FormA(Form):
a = FieldList(FormField(FormB))
deep_dict = {
'a': [{'b': {'c': 1}}]
}
assert flatten_json(deep_dict) == {'a-0-b-c': 1}
wtforms-json-0.3.5/docs/make.bat 0000664 0000000 0000000 00000011764 14226614013 0016534 0 ustar 00root root 0000000 0000000 @ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^` where ^ is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\wtforms-json.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\wtforms-json.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end
wtforms-json-0.3.5/setup.py 0000664 0000000 0000000 00000005046 14226614013 0015705 0 ustar 00root root 0000000 0000000 """
WTForms-JSON
------------
Adds smart json support for WTForms. Useful for when using WTForms with RESTful
APIs.
"""
from setuptools import setup, Command
import os
import re
import subprocess
HERE = os.path.dirname(os.path.abspath(__file__))
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call(['py.test'])
raise SystemExit(errno)
def get_version():
filename = os.path.join(HERE, 'wtforms_json', '__init__.py')
with open(filename) as f:
contents = f.read()
pattern = r"^__version__ = '(.*?)'$"
return re.search(pattern, contents, re.MULTILINE).group(1)
extras_require = {
'test': [
'pytest>=2.2.3',
'WTForms-Alchemy>=0.8.6',
'flake8>=2.4.0',
'isort>=3.9.6'
],
}
setup(
name='WTForms-JSON',
version=get_version(),
url='https://github.com/kvesteri/wtforms-json',
license='BSD',
author='Konsta Vesterinen',
author_email='konsta@fastmonkeys.com',
description=(
'Adds smart json support for WTForms. Useful for when using'
' WTForms with RESTful APIs.'
),
long_description=__doc__,
packages=['wtforms_json'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'WTForms>=1.0.5',
'six>=1.3.0'
],
extras_require=extras_require,
cmdclass={'test': PyTest},
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
wtforms-json-0.3.5/tests/ 0000775 0000000 0000000 00000000000 14226614013 0015330 5 ustar 00root root 0000000 0000000 wtforms-json-0.3.5/tests/__init__.py 0000664 0000000 0000000 00000000046 14226614013 0017441 0 ustar 00root root 0000000 0000000 from wtforms_json import init
init()
wtforms-json-0.3.5/tests/test_boolean_field.py 0000664 0000000 0000000 00000000464 14226614013 0021527 0 ustar 00root root 0000000 0000000 import pytest
from wtforms import BooleanField, Form
class TestBooleanField(object):
@pytest.mark.parametrize('value', ('', 'false', False))
def test_falsy_value(self, value):
class MyForm(Form):
a = BooleanField()
assert MyForm.from_json({'a': value}).a.data is False
wtforms-json-0.3.5/tests/test_errors.py 0000664 0000000 0000000 00000000363 14226614013 0020257 0 ustar 00root root 0000000 0000000 from wtforms import Form, IntegerField
class MyForm(Form):
a = IntegerField()
def test_errors():
form = MyForm.from_json({'a': 'not an integer!'})
form.validate()
assert form.errors == {'a': [u'Not a valid integer value']}
wtforms-json-0.3.5/tests/test_field_type_coercion.py 0000664 0000000 0000000 00000004636 14226614013 0022757 0 ustar 00root root 0000000 0000000 import six # noqa
from pytest import mark
from wtforms import Form, IntegerField, SelectMultipleField, StringField
try:
from wtforms.ext.sqlalchemy.fields import QuerySelectField
HAS_SQLALCHEMY_SUPPORT = False
except ImportError:
HAS_SQLALCHEMY_SUPPORT = False
from wtforms.validators import IPAddress
sa = None
try:
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
except ImportError:
pass
class TestFieldTypeCoercion(object):
def test_integer_to_unicode_coercion(self):
class NetworkForm(Form):
address = StringField('Address', [IPAddress()])
network = dict(address=123)
form = NetworkForm.from_json(network)
assert not form.validate()
def test_integer_coercion(self):
class UserForm(Form):
age = IntegerField('age')
network = dict(age=123)
form = UserForm.from_json(network)
assert form.validate()
class FooForm(Form):
items = SelectMultipleField(
choices=(
(1, 'a'),
(2, 'b'),
(3, 'c'),
),
coerce=int
)
@mark.skipif('sa is None or six.PY3 or not HAS_SQLALCHEMY_SUPPORT')
class TestQuerySelectField(object):
def setup_method(self, method):
self.Base = declarative_base()
class Team(self.Base):
__tablename__ = 'team'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(255))
class Match(self.Base):
__tablename__ = 'match'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(255))
team_id = sa.Column(sa.BigInteger, sa.ForeignKey(Team.id))
team = sa.orm.relationship(Team)
self.Team = Team
self.Match = Match
def test_integer_coercion(self):
class MatchForm(Form):
team = QuerySelectField(
query_factory=lambda: [
self.Team(id=1, name='Manchester United'),
self.Team(id=2, name='FC Barcelona')
]
)
data = {'team': 1}
form = MatchForm.from_json(data)
assert form.validate()
assert form.team.data
class TestSelectMultipleField(object):
def test_from_json(self):
data = {'items': [1, 3]}
form = FooForm.from_json(data)
assert form.validate()
assert form.items.data
wtforms-json-0.3.5/tests/test_json_decoder.py 0000664 0000000 0000000 00000013135 14226614013 0021402 0 ustar 00root root 0000000 0000000 from pytest import raises
from wtforms import (
BooleanField,
Field,
FieldList,
Form,
FormField,
IntegerField,
SelectMultipleField,
StringField,
)
from wtforms_json import flatten_json, InvalidData
class TestJsonDecoder(object):
def test_raises_error_if_given_data_not_dict_like(self):
class MyForm(Form):
pass
with raises(InvalidData):
flatten_json(MyForm, [])
def test_unknown_attribute(self):
class MyForm(Form):
a = BooleanField()
flatten_json(MyForm, {'b': 123})
def test_unknown_attribute_without_skip_unknown_keys(self):
class MyForm(Form):
a = BooleanField()
with raises(InvalidData):
flatten_json(MyForm, {'b': 123}, skip_unknown_keys=False)
def test_sharing_class_property(self):
""" When an unknown attribute has the same name as a property on
the Form class, the attribute is mistakenly seen as known because
getattr can retrieve the property, but when property.field_class
is accessed an error is raised. This tests that the error is not
raised when skip_unknown_keys is True.
"""
class MyForm(Form):
a = BooleanField()
flatten_json(MyForm, {'data': 13})
def test_sharing_class_property_without_skip_unknown_keys(self):
""" When an unknown attribute has the same name as a property on
the Form class, the attribute is mistakenly seen as known because
getattr can retrieve the property, but when property.field_class
is accessed an error is raised. This tests that the error IS
raised when skip_unknown_keys is False.
"""
class MyForm(Form):
a = BooleanField()
with raises(InvalidData):
flatten_json(MyForm, {'data': 123}, skip_unknown_keys=False)
def test_supports_dicts(self):
class MyForm(Form):
a = BooleanField()
b = IntegerField()
assert (
flatten_json(MyForm, {'a': False, 'b': 123}) ==
{'a': False, 'b': 123}
)
def test_supports_select_multiple_field_decoding(self):
class MyForm(Form):
a = SelectMultipleField()
assert flatten_json(MyForm, {'a': [1, 2, 3]}) == {'a': [1, 2, 3]}
def test_supports_field_list_decoding(self):
class MyForm(Form):
a = FieldList(StringField())
assert flatten_json(MyForm, {'a': [1, 2, 3]}) == {
'a-0': 1,
'a-1': 2,
'a-2': 3
}
def test_supports_nested_dicts_and_lists(self):
class OtherForm(Form):
b = BooleanField()
class MyForm(Form):
a = FieldList(FormField(OtherForm))
data = {
'a': [{'b': True}]
}
assert flatten_json(MyForm, data) == {'a-0-b': True}
def test_flatten_dict(self):
class DeeplyNestedForm(Form):
c = StringField()
class NestedForm(Form):
b = FormField(DeeplyNestedForm)
class MyForm(Form):
a = FormField(NestedForm)
assert flatten_json(MyForm, {'a': {'b': {'c': 'd'}}}) == {
'a-b-c': 'd'
}
def test_only_flatten_on_form_field(self):
class DictField(Field):
def process_formdata(self, valuelist):
if valuelist:
data = valuelist[0]
if isinstance(data, dict):
self.data = data
else:
raise 'Unsupported datatype'
else:
self.data = {}
class MyForm(Form):
a = IntegerField()
b = DictField()
assert (
flatten_json(MyForm, {'a': False, 'b': {'key': 'value'}}) ==
{'a': False, 'b': {'key': 'value'}}
)
def test_flatten_formfield_inheritance(self):
class NestedForm(Form):
b = StringField()
class SpecialField(FormField):
def __init__(self, *args, **kwargs):
super(SpecialField, self).__init__(NestedForm, *args, **kwargs)
class MyForm(Form):
a = SpecialField()
assert flatten_json(MyForm, {'a': {'b': 'c'}}) == {
'a-b': 'c'
}
def test_flatten_listfield_inheritance(self):
class SpecialField(FieldList):
def __init__(self, *args, **kwargs):
super(SpecialField, self).__init__(
StringField(),
*args,
**kwargs
)
class MyForm(Form):
a = SpecialField()
assert flatten_json(MyForm, {'a': [1, 2, 3]}) == {
'a-0': 1,
'a-1': 2,
'a-2': 3
}
def test_flatten_nested_listfield_and_formfield_inheritance(self):
class NestedForm(Form):
b = StringField()
class SpecialNestedField(FormField):
def __init__(self, *args, **kwargs):
super(SpecialNestedField, self).__init__(
NestedForm,
*args,
**kwargs
)
class SpecialField(FieldList):
def __init__(self, *args, **kwargs):
super(SpecialField, self).__init__(
SpecialNestedField(),
*args,
**kwargs
)
class MyForm(Form):
a = SpecialField()
assert flatten_json(MyForm, {'a': [{'b': 1}, {'b': 2}, {'b': 3}]}) == {
'a-0-b': 1,
'a-1-b': 2,
'a-2-b': 3
}
wtforms-json-0.3.5/tests/test_object_defaults.py 0000664 0000000 0000000 00000001502 14226614013 0022074 0 ustar 00root root 0000000 0000000 import pytest
from wtforms import Form, IntegerField, StringField
from wtforms.validators import Optional
class MyForm(Form):
a = IntegerField(validators=[Optional()])
b = StringField()
c = StringField(default='c')
class MyCallableForm(Form):
a = IntegerField(validators=[Optional()])
b = StringField()
c = StringField(default=lambda: 'c')
@pytest.mark.parametrize('cls', [MyForm, MyCallableForm])
def test_object_defaults(cls):
class SomeClass(object):
a = 1
b = 'someone'
form = cls.from_json(obj=SomeClass())
assert form.data == {'a': 1, 'b': 'someone', 'c': 'c'}
@pytest.mark.parametrize('cls', [MyForm, MyCallableForm])
def test_formdata_defaults(cls):
form = cls.from_json({'a': 1, 'b': 'something'})
assert form.data == {'a': 1, 'b': 'something', 'c': 'c'}
wtforms-json-0.3.5/tests/test_patch_data.py 0000664 0000000 0000000 00000005374 14226614013 0021042 0 ustar 00root root 0000000 0000000 from pytest import raises
from wtforms import (
BooleanField,
FieldList,
Form,
FormField,
IntegerField,
StringField,
)
from wtforms.validators import Optional, DataRequired
from wtforms_json import InvalidData, MultiDict
class BooleanTestForm(Form):
is_active = BooleanField(default=False, validators=[Optional()])
is_confirmed = BooleanField(default=True, validators=[DataRequired()])
is_private = BooleanField(default=False, validators=[DataRequired()])
class TestPatchedBooleans(object):
def test_supports_false_values(self):
form = BooleanTestForm.from_json(
{'is_active': False, 'is_confirmed': True}
)
assert form.patch_data == {
'is_active': False,
'is_confirmed': True,
'is_private': False
}
class LocationForm(Form):
name = StringField()
longitude = IntegerField()
latitude = IntegerField()
class EventForm(Form):
name = StringField()
location = FormField(LocationForm)
attendees = IntegerField()
attendee_names = FieldList(StringField())
class TestSkipUnknownKeys(object):
def test_skips_unknown_keys(self):
json = {
'name': 'some patched name',
'unknown': 'something'
}
with raises(InvalidData):
EventForm.from_json(json, skip_unknown_keys=False)
class TestFormProcessAfterMonkeyPatch(object):
def test_supports_webob_input_wrapper(self):
json = {
'name': 'some patched name'
}
form = EventForm(formdata=MultiDict(json))
assert form.data
class TestFormPatchData(object):
def test_patch_data_with_missing_form_fields(self):
json = {
'name': 'some patched name'
}
form = EventForm.from_json(json)
assert form.patch_data == json
def test_patch_data_for_form_fields(self):
json = {
'name': 'some name',
'location': {
'name': 'some location'
}
}
form = EventForm.from_json(json)
assert form.patch_data == json
def test_supports_field_lists(self):
json = {
'name': 'some name',
'attendee_names': ['Something']
}
form = EventForm.from_json(json)
assert form.patch_data == json
def test_supports_null_values_for_form_fields(self):
json = {
'name': 'some name',
'location': None
}
form = EventForm.from_json(json)
assert form.patch_data == json
def test_supports_null_values_for_regular_fields(self):
json = {
'name': 'some name',
'attendees': None
}
form = EventForm.from_json(json)
assert form.patch_data == json
wtforms-json-0.3.5/tests/test_select_multiple_field.py 0000664 0000000 0000000 00000006237 14226614013 0023306 0 ustar 00root root 0000000 0000000 from wtforms import (
Form,
SelectField,
SelectFieldBase,
SelectMultipleField,
StringField,
validators,
widgets,
)
def test_select_field():
fixtures = [
{'name': 'Scarlet Witch', 'childs': 3, '__result': True},
{'name': 'Black Cat', 'childs': 0, '__result': False},
{'name': 'Tigra', 'childs': 1, '__result': True},
]
class MomForm(Form):
name = StringField()
childs = SelectField(choices=((1, 1), (2, 2), (3, 3)), coerce=int)
for fixture in fixtures:
result = fixture.pop('__result')
assert MomForm.from_json(fixture).validate() == result
def test_select_multiple_field():
fixtures = [
{'name': 'Juggernaut', 'gadgets': [1, 2, 3, 4], '__result': True},
{'name': 'Wolverine', 'gadgets': [], '__result': False},
{'name': 'Beast', 'gadgets': [4], '__result': True},
]
class AppleFanBoyForm(Form):
name = StringField()
gadgets = SelectMultipleField(
choices=(
(1, 'Macbook Pro'),
(2, 'Macbook Air'),
(3, 'iPhone'),
(4, 'iPad')
),
validators=[validators.DataRequired()],
coerce=int
)
for fixture in fixtures:
result = fixture.pop('__result')
assert AppleFanBoyForm.from_json(fixture).validate() == result
def test_custom_field():
# a custom field that returns a list
# it doesn't inherits from SelectMultipleField
class SuperPowersField(SelectFieldBase):
POWERS = [
('fly', ''),
('super strength', ''),
('regeneration', ''),
('stamina', ''),
('agility', ''),
]
widget = widgets.Select(multiple=True)
def iter_choices(self):
if self.allow_blank:
yield (u'__None', self.blank_text, self.data is None)
for item in self.POWERS:
selected = item[0] in self.data
yield (item[0], item[1], selected)
def process_formdata(self, valuelist):
if valuelist:
if valuelist[0] == '__None':
self.data = None
else:
self.data = [
item[0] for item in self.POWERS
if str(item[0]) in valuelist]
if not len(self.data):
self.data = None
def _is_selected(self, item):
return item in self.data
class SuperHeroForm(Form):
name = StringField()
powers = SuperPowersField(
validators=[validators.DataRequired()]
)
fixtures = [
{'name': 'Juggernaut', 'powers': ['super strength'], '__result': True},
{
'name': 'Wolverine',
'powers': ['stamina', 'agility', 'regeneration'],
'__result': True
},
{'name': 'Beast', 'powers': ['agility'], '__result': True},
{'name': 'Rocket Rackoon', 'powers': [], '__result': False}
]
for fixture in fixtures:
result = fixture.pop('__result')
assert SuperHeroForm.from_json(fixture).validate() == result
wtforms-json-0.3.5/tests/test_wtforms_alchemy.py 0000664 0000000 0000000 00000003113 14226614013 0022142 0 ustar 00root root 0000000 0000000 import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from wtforms_alchemy import ModelForm
engine = create_engine('sqlite:///:memory:')
Base = declarative_base(engine)
Session = sessionmaker(bind=engine)
session = Session()
class Fake(Base):
__tablename__ = 'fake'
id = sa.Column(sa.BigInteger, autoincrement=True, primary_key=True)
a = sa.Column(sa.Unicode(100), nullable=True)
b = sa.Column(sa.Unicode(255), nullable=True)
c = sa.Column(sa.Unicode(100), nullable=True)
d = sa.Column(sa.Unicode(255), nullable=True)
class FakeForm(ModelForm):
class Meta:
model = Fake
Base.metadata.create_all(engine)
# Example
def create_form_from_json(**kwargs):
if not kwargs.get('json'):
kwargs['json'] = {
'a': u'First Event',
'b': u'Second',
'c': u'Third',
'd': u'Fourth'
}
return FakeForm.from_json(kwargs['json'])
def create_populated_obj_from_json_form():
form = create_form_from_json()
obj = Fake()
form.populate_obj(obj)
return obj
def test_init_formdata():
json = {
'a': u'First Event',
'b': u'Second',
'c': u'Third',
'd': u'Fourth'
}
form = create_form_from_json(json=json)
assert form.data == json
def test_populate_form_from_object():
obj = create_populated_obj_from_json_form()
form = FakeForm(obj=obj)
assert len(form.data) == 4
for key in form.data:
assert form.data[key] == obj.__dict__[key]
wtforms-json-0.3.5/tox.ini 0000664 0000000 0000000 00000000240 14226614013 0015475 0 ustar 00root root 0000000 0000000 [tox]
envlist = {py27,py33,py34,py35,py36}-{wtf,wtf2}
[testenv]
commands =
py.test tests
deps =
.[test]
wtf: WTForms==1.0.5
wtf2: WTForms==2.1
wtforms-json-0.3.5/wtforms_json/ 0000775 0000000 0000000 00000000000 14226614013 0016720 5 ustar 00root root 0000000 0000000 wtforms-json-0.3.5/wtforms_json/__init__.py 0000664 0000000 0000000 00000020075 14226614013 0021035 0 ustar 00root root 0000000 0000000 try:
from collections.abc import Mapping, MutableMapping
except:
from collections import Mapping, MutableMapping
import six
from wtforms import Form
try:
from wtforms_sqlalchemy.fields import (
QuerySelectField,
QuerySelectMultipleField
)
HAS_SQLALCHEMY_SUPPORT = True
except ImportError:
try:
from wtforms.ext.sqlalchemy.fields import (
QuerySelectField,
QuerySelectMultipleField
)
HAS_SQLALCHEMY_SUPPORT = True
except ImportError:
HAS_SQLALCHEMY_SUPPORT = False
from wtforms.fields import (
_unset_value,
BooleanField,
Field,
FieldList,
FileField,
FormField,
StringField
)
from wtforms.validators import DataRequired, Optional
__version__ = '0.3.5'
class InvalidData(Exception):
pass
def flatten_json(
form,
json,
parent_key='',
separator='-',
skip_unknown_keys=True
):
"""Flattens given JSON dict to cope with WTForms dict structure.
:form form: WTForms Form object
:param json: json to be converted into flat WTForms style dict
:param parent_key: this argument is used internally be recursive calls
:param separator: default separator
:param skip_unknown_keys:
if True unknown keys will be skipped, if False throws InvalidData
exception whenever unknown key is encountered
Examples::
>>> flatten_json(MyForm, {'a': {'b': 'c'}})
{'a-b': 'c'}
"""
if not isinstance(json, Mapping):
raise InvalidData(
u'This function only accepts dict-like data structures.'
)
items = []
for key, value in json.items():
try:
unbound_field = getattr(form, key)
except AttributeError:
if skip_unknown_keys:
continue
else:
raise InvalidData(u"Unknown field name '%s'." % key)
try:
field_class = unbound_field.field_class
except AttributeError:
if skip_unknown_keys:
continue
else:
raise InvalidData(u"Key '%s' is not valid field class." % key)
new_key = parent_key + separator + key if parent_key else key
if isinstance(value, MutableMapping):
if issubclass(field_class, FormField):
nested_form_class = unbound_field.bind(Form(), '').form_class
items.extend(
flatten_json(nested_form_class, value, new_key)
.items()
)
else:
items.append((new_key, value))
elif isinstance(value, list):
if issubclass(field_class, FieldList):
nested_unbound_field = unbound_field.bind(
Form(),
''
).unbound_field
items.extend(
flatten_json_list(
nested_unbound_field,
value,
new_key,
separator
)
)
else:
items.append((new_key, value))
else:
items.append((new_key, value))
return dict(items)
def flatten_json_list(field, json, parent_key='', separator='-'):
items = []
for i, item in enumerate(json):
new_key = parent_key + separator + str(i)
if (
isinstance(item, dict) and
issubclass(getattr(field, 'field_class'), FormField)
):
nested_class = field.field_class(
*field.args,
**field.kwargs
).bind(Form(), '').form_class
items.extend(
flatten_json(nested_class, item, new_key)
.items()
)
else:
items.append((new_key, item))
return items
@property
def patch_data(self):
if hasattr(self, '_patch_data'):
return self._patch_data
data = {}
def is_optional(field):
return Optional in [v.__class__ for v in field.validators]
def is_required(field):
return DataRequired in [v.__class__ for v in field.validators]
for name, f in six.iteritems(self._fields):
if f.is_missing:
if is_optional(f):
continue
elif not is_required(f) and f.default is None:
continue
elif isinstance(f, FieldList) and f.min_entries == 0:
continue
if isinstance(f, FormField):
data[name] = f.patch_data
elif isinstance(f, FieldList):
if issubclass(f.unbound_field.field_class, FormField):
data[name] = [i.patch_data for i in f.entries]
else:
data[name] = [i.data for i in f.entries]
else:
data[name] = f.data
return data
def monkey_patch_field_process(func):
"""
Monkey patches Field.process method to better understand missing values.
"""
def process(self, formdata, data=_unset_value, **kwargs):
call_original_func = True
if not isinstance(self, FormField):
if formdata and self.name in formdata:
if (
len(formdata.getlist(self.name)) == 1 and
formdata.getlist(self.name) == [None]
):
call_original_func = False
self.data = None
self.is_missing = not bool(formdata.getlist(self.name))
else:
self.is_missing = True
if call_original_func:
func(self, formdata, data=data, **kwargs)
if (
formdata and self.name in formdata and
formdata.getlist(self.name) == [None] and
isinstance(self, FormField)
):
self.form._is_missing = False
self.form._patch_data = None
if isinstance(self, StringField) and not isinstance(self, FileField):
if not self.data:
try:
self.data = self.default()
except TypeError:
self.data = self.default
else:
self.data = six.text_type(self.data)
return process
class MultiDict(dict):
def getlist(self, key):
val = self[key]
if not isinstance(val, list):
val = [val]
return val
def getall(self, key):
return [self[key]]
@classmethod
def from_json(
cls,
formdata=None,
obj=None,
prefix='',
data=None,
meta=None,
skip_unknown_keys=True,
**kwargs
):
form = cls(
formdata=MultiDict(
flatten_json(cls, formdata, skip_unknown_keys=skip_unknown_keys)
) if formdata else None,
obj=obj,
prefix=prefix,
data=data,
meta=meta,
**kwargs
)
return form
@property
def is_missing(self):
if hasattr(self, '_is_missing'):
return self._is_missing
for name, field in self._fields.items():
if not field.is_missing:
return False
return True
@property
def field_list_is_missing(self):
if hasattr(self, '_is_missing'):
return self._is_missing
return all([field.is_missing for field in self.entries])
def monkey_patch_process_formdata(func):
def process_formdata(self, valuelist):
valuelist = list(map(six.text_type, valuelist))
return func(self, valuelist)
return process_formdata
def init():
Form.is_missing = is_missing
FieldList.is_missing = field_list_is_missing
Form.from_json = from_json
Form.patch_data = patch_data
FieldList.patch_data = patch_data
if HAS_SQLALCHEMY_SUPPORT:
QuerySelectField.process_formdata = monkey_patch_process_formdata(
QuerySelectField.process_formdata
)
QuerySelectMultipleField.process_formdata = \
monkey_patch_process_formdata(
QuerySelectMultipleField.process_formdata
)
Field.process = monkey_patch_field_process(Field.process)
FormField.process = monkey_patch_field_process(FormField.process)
BooleanField.false_values = BooleanField.false_values + (False,)