launchpad-dev team mailing list archive
-
launchpad-dev team
-
Mailing list archive
-
Message #03618
Did you know about form_ng?
While fixing bug 595163[1] I found out that there is a provision for this type
of errors in LaunchpadBrowserRequest. I pasted the documentation for it below
for your convenience.
I am wondering, though, why we could not give BrowserFormNG a full dict
interface (it already implements __contains__ and __iter__) and let it replace
the normal 'form' attribute completely. Saves at least three characters in
line length ... ;-)
Cheers,
Henning
[1] https://bugs.launchpad.net/rosetta/+bug/595163
== Handling form data using IBrowserFormNG ==
Submitted form data is available in the form_ng request attribute. This
is an object providing the IBrowserFormNG interface which offers two
methods to obtain form data. (Form data is also available through the
regular Zope3 form attribute using the dictionary interface.)
>>> from canonical.launchpad.webapp.interfaces import IBrowserFormNG
>>> verifyObject(IBrowserFormNG, request.form_ng)
True
You can check the presence of an uploaded field using the regular
python 'in' operator.
>>> from canonical.launchpad.webapp.servers import (
... LaunchpadBrowserRequest)
>>> from urllib import urlencode
>>> environment = {'QUERY_STRING': urlencode({
... 'a_field': 'a_value',
... 'items_field': [1, 2, 3]}, doseq=True)}
>>> request = LaunchpadBrowserRequest('', environment)
>>> request.processInputs()
>>> 'a_field' in request.form_ng
True
>>> 'another_field' in request.form_ng
False
The advantage of the IBrowserFormNG API is that it offers methods that
checks the number of values you are expecting. The getOne() method
should be used when you expect only one value for the field.
>>> request.form_ng.getOne('a_field')
u'a_value'
UnexpectedFormData is raised if more than one value was submitted for
the field:
>>> request.form_ng.getOne('items_field')
Traceback (most recent call last):
...
UnexpectedFormData:...
None is returned if the field wasn't submitted:
>>> request.form_ng.getOne('another_field') is None
True
You can provide a default value that is returned if the field wasn't
submitted:
>>> request.form_ng.getOne('another_field', u'default')
u'default'
The getAll() method should be used when you are expecting a list of
values.
>>> request.form_ng.getAll('items_field')
[u'1', u'2', u'3']
If only one value was submitted, it will still be returned as part of
a list:
>>> request.form_ng.getAll('a_field')
[u'a_value']
An empty list is returned when no value was submitted for the field:
>>> request.form_ng.getAll('another_field')
[]
That method also accepts a default value that is to be returned when
no value was submitted with the field.
>>> request.form_ng.getAll('another_field', [u'default'])
[u'default']
All the submitted field names can be iterated over:
>>> for name in sorted(request.form_ng):
... print name
a_field
items_field