Merge pull request #396 from niphlod/docs/html

sphinx-compatible docstrings
This commit is contained in:
mdipierro
2014-03-11 10:51:31 -05:00
+303 -233
View File
@@ -2,9 +2,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
This file is part of the web2py Web Framework | This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> | Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) | License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Template helpers
--------------------------------------------
""" """
import cgi import cgi
@@ -109,10 +112,11 @@ __all__ = [
def xmlescape(data, quote=True): def xmlescape(data, quote=True):
""" """
returns an escaped string of the provided data Returns an escaped string of the provided data
:param data: the data to be escaped Args:
:param quote: optional (default False) data: the data to be escaped
quote: optional (default False)
""" """
# first try the xml function # first try the xml function
@@ -164,80 +168,92 @@ def URL(
language=None, language=None,
): ):
""" """
generate a URL
example::
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':1, 'q':2}, anchor='1'))
'/a/c/f/x/y/z?p=1&q=2#1'
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':(1,3), 'q':2}, anchor='1'))
'/a/c/f/x/y/z?p=1&p=3&q=2#1'
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':(3,1), 'q':2}, anchor='1'))
'/a/c/f/x/y/z?p=3&p=1&q=2#1'
>>> str(URL(a='a', c='c', f='f', anchor='1+2'))
'/a/c/f#1%2B2'
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':(1,3), 'q':2}, anchor='1', hmac_key='key'))
'/a/c/f/x/y/z?p=1&p=3&q=2&_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f#1'
>>> str(URL(a='a', c='c', f='f', args=['w/x', 'y/z']))
'/a/c/f/w/x/y/z'
>>> str(URL(a='a', c='c', f='f', args=['w/x', 'y/z'], encode_embedded_slash=True))
'/a/c/f/w%2Fx/y%2Fz'
>>> str(URL(a='a', c='c', f='f', args=['%(id)d'], url_encode=False))
'/a/c/f/%(id)d'
>>> str(URL(a='a', c='c', f='f', args=['%(id)d'], url_encode=True))
'/a/c/f/%25%28id%29d'
>>> str(URL(a='a', c='c', f='f', vars={'id' : '%(id)d' }, url_encode=False))
'/a/c/f?id=%(id)d'
>>> str(URL(a='a', c='c', f='f', vars={'id' : '%(id)d' }, url_encode=True))
'/a/c/f?id=%25%28id%29d'
>>> str(URL(a='a', c='c', f='f', anchor='%(id)d', url_encode=False))
'/a/c/f#%(id)d'
>>> str(URL(a='a', c='c', f='f', anchor='%(id)d', url_encode=True))
'/a/c/f#%25%28id%29d'
generates a url '/a/c/f' corresponding to application a, controller c generates a url '/a/c/f' corresponding to application a, controller c
and function f. If r=request is passed, a, c, f are set, respectively, and function f. If r=request is passed, a, c, f are set, respectively,
to r.application, r.controller, r.function. to r.application, r.controller, r.function.
The more typical usage is: The more typical usage is:
URL(r=request, f='index') that generates a url for the index function URL('index')
that generates a url for the index function
within the present application and controller. within the present application and controller.
:param a: application (default to current if r is given) Args:
:param c: controller (default to current if r is given) a: application (default to current if r is given)
:param f: function (default to current if r is given) c: controller (default to current if r is given)
:param r: request (optional) f: function (default to current if r is given)
:param args: any arguments (optional) r: request (optional)
:param vars: any variables (optional) args: any arguments (optional). Additional "path" elements
:param anchor: anchorname, without # (optional) vars: any variables (optional). Querystring elements
:param hmac_key: key to use when generating hmac signature (optional) anchor: anchorname, without # (optional)
:param hash_vars: which of the vars to include in our hmac signature extension: force an extension
True (default) - hash all vars, False - hash none of the vars, hmac_key: key to use when generating hmac signature (optional)
iterable - hash only the included vars ['key1','key2'] hash_vars: which of the vars to include in our hmac signature
:param scheme: URI scheme (True, 'http' or 'https', etc); forces absolute URL (optional) True (default) - hash all vars, False - hash none of the vars,
:param host: string to force absolute URL with host (True means http_host) iterable - hash only the included vars ['key1','key2']
:param port: optional port number (forces absolute URL) salt: salt hashing with this string
user_signature: signs automatically the URL in such way that only the
user can access the URL (use with `URL.verify` or
`auth.requires_signature()`)
scheme: URI scheme (True, 'http' or 'https', etc); forces absolute URL (optional)
host: string to force absolute URL with host (True means http_host)
port: optional port number (forces absolute URL)
encode_embedded_slash: encode slash characters included in args
url_encode: encode characters included in vars
Raises:
SyntaxError: when no application, controller or function is available
or when a CRLF is found in the generated url
Examples:
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':1, 'q':2}, anchor='1'))
'/a/c/f/x/y/z?p=1&q=2#1'
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':(1,3), 'q':2}, anchor='1'))
'/a/c/f/x/y/z?p=1&p=3&q=2#1'
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':(3,1), 'q':2}, anchor='1'))
'/a/c/f/x/y/z?p=3&p=1&q=2#1'
>>> str(URL(a='a', c='c', f='f', anchor='1+2'))
'/a/c/f#1%2B2'
>>> str(URL(a='a', c='c', f='f', args=['x', 'y', 'z'],
... vars={'p':(1,3), 'q':2}, anchor='1', hmac_key='key'))
'/a/c/f/x/y/z?p=1&p=3&q=2&_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f#1'
>>> str(URL(a='a', c='c', f='f', args=['w/x', 'y/z']))
'/a/c/f/w/x/y/z'
>>> str(URL(a='a', c='c', f='f', args=['w/x', 'y/z'], encode_embedded_slash=True))
'/a/c/f/w%2Fx/y%2Fz'
>>> str(URL(a='a', c='c', f='f', args=['%(id)d'], url_encode=False))
'/a/c/f/%(id)d'
>>> str(URL(a='a', c='c', f='f', args=['%(id)d'], url_encode=True))
'/a/c/f/%25%28id%29d'
>>> str(URL(a='a', c='c', f='f', vars={'id' : '%(id)d' }, url_encode=False))
'/a/c/f?id=%(id)d'
>>> str(URL(a='a', c='c', f='f', vars={'id' : '%(id)d' }, url_encode=True))
'/a/c/f?id=%25%28id%29d'
>>> str(URL(a='a', c='c', f='f', anchor='%(id)d', url_encode=False))
'/a/c/f#%(id)d'
>>> str(URL(a='a', c='c', f='f', anchor='%(id)d', url_encode=True))
'/a/c/f#%25%28id%29d'
:raises SyntaxError: when no application, controller or function is
available
:raises SyntaxError: when a CRLF is found in the generated url
""" """
from rewrite import url_out # done here in case used not-in web2py from rewrite import url_out # done here in case used not-in web2py
@@ -528,7 +544,7 @@ class XML(XmlComponent):
use it to wrap a string that contains XML/HTML so that it will not be use it to wrap a string that contains XML/HTML so that it will not be
escaped by the template escaped by the template
example: Examples:
>>> XML('<h1>Hello</h1>').xml() >>> XML('<h1>Hello</h1>').xml()
'<h1>Hello</h1>' '<h1>Hello</h1>'
@@ -564,19 +580,19 @@ class XML(XmlComponent):
}, },
): ):
""" """
:param text: the XML text Args:
:param sanitize: sanitize text using the permitted tags and allowed text: the XML text
attributes (default False) sanitize: sanitize text using the permitted tags and allowed
:param permitted_tags: list of permitted tags (default: simple list of attributes (default False)
tags) permitted_tags: list of permitted tags (default: simple list of
:param allowed_attributes: dictionary of allowed attributed (default tags)
for A, IMG and BlockQuote). allowed_attributes: dictionary of allowed attributed (default
The key is the tag; the value is a list of allowed attributes. for A, IMG and BlockQuote).
The key is the tag; the value is a list of allowed attributes.
""" """
if sanitize: if sanitize:
text = sanitizer.sanitize(text, permitted_tags, text = sanitizer.sanitize(text, permitted_tags, allowed_attributes)
allowed_attributes)
if isinstance(text, unicode): if isinstance(text, unicode):
text = text.encode('utf8', 'xmlcharrefreplace') text = text.encode('utf8', 'xmlcharrefreplace')
elif not isinstance(text, str): elif not isinstance(text, str):
@@ -620,7 +636,8 @@ class XML(XmlComponent):
def flatten(self, render=None): def flatten(self, render=None):
""" """
return the text stored by the XML object rendered by the render function returns the text stored by the XML object rendered
by the `render` function
""" """
if render: if render:
return render(self.text, None, {}) return render(self.text, None, {})
@@ -628,8 +645,9 @@ class XML(XmlComponent):
def elements(self, *args, **kargs): def elements(self, *args, **kargs):
""" """
to be considered experimental since the behavior of this method is questionable to be considered experimental since the behavior of this method
another options could be TAG(self.text).elements(*args,**kargs) is questionable
another option could be `TAG(self.text).elements(*args,**kwargs)`
""" """
return [] return []
@@ -653,15 +671,15 @@ class DIV(XmlComponent):
Behaves like a dictionary regarding updating of attributes. Behaves like a dictionary regarding updating of attributes.
Behaves like a list regarding inserting/appending components. Behaves like a list regarding inserting/appending components.
example:: Examples:
>>> DIV('hello', 'world', _style='color:red;').xml() >>> DIV('hello', 'world', _style='color:red;').xml()
'<div style=\"color:red;\">helloworld</div>' '<div style=\"color:red;\">helloworld</div>'
all other HTML helpers are derived from DIV. All other HTML helpers are derived from `DIV`.
_something=\"value\" attributes are transparently translated into `_something="value"` attributes are transparently translated into
something=\"value\" HTML attributes `something="value"` HTML attributes
""" """
# name of the tag, subclasses should update this # name of the tag, subclasses should update this
@@ -671,10 +689,12 @@ class DIV(XmlComponent):
def __init__(self, *components, **attributes): def __init__(self, *components, **attributes):
""" """
:param *components: any components that should be nested in this element Args:
:param **attributes: any attributes you want to give to this element components: any components that should be nested in this element
attributes: any attributes you want to give to this element
:raises SyntaxError: when a stand alone tag receives components Raises:
SyntaxError: when a stand alone tag receives components
""" """
if self.tag[-1:] == '/' and components: if self.tag[-1:] == '/' and components:
@@ -705,6 +725,8 @@ class DIV(XmlComponent):
""" """
list style appending of components list style appending of components
Examples:
>>> a=DIV() >>> a=DIV()
>>> a.append(SPAN('x')) >>> a.append(SPAN('x'))
>>> print a >>> print a
@@ -717,7 +739,9 @@ class DIV(XmlComponent):
def insert(self, i, value): def insert(self, i, value):
""" """
list style inserting of components List-style inserting of components
Examples:
>>> a=DIV() >>> a=DIV()
>>> a.insert(0,SPAN('x')) >>> a.insert(0,SPAN('x'))
@@ -731,12 +755,12 @@ class DIV(XmlComponent):
def __getitem__(self, i): def __getitem__(self, i):
""" """
gets attribute with name 'i' or component #i. Gets attribute with name 'i' or component #i.
If attribute 'i' is not found returns None If attribute 'i' is not found returns None
:param i: index Args:
if i is a string: the name of the attribute i: index. If i is a string: the name of the attribute
otherwise references to number of the component otherwise references to number of the component
""" """
if isinstance(i, str): if isinstance(i, str):
@@ -749,12 +773,12 @@ class DIV(XmlComponent):
def __setitem__(self, i, value): def __setitem__(self, i, value):
""" """
sets attribute with name 'i' or component #i. Sets attribute with name 'i' or component #i.
:param i: index Args:
if i is a string: the name of the attribute i: index. If i is a string: the name of the attribute
otherwise references to number of the component otherwise references to number of the component
:param value: the new value value: the new value
""" """
self._setnode(value) self._setnode(value)
if isinstance(i, (str, unicode)): if isinstance(i, (str, unicode)):
@@ -764,11 +788,11 @@ class DIV(XmlComponent):
def __delitem__(self, i): def __delitem__(self, i):
""" """
deletes attribute with name 'i' or component #i. Deletes attribute with name 'i' or component #i.
:param i: index Args:
if i is a string: the name of the attribute i: index. If i is a string: the name of the attribute
otherwise references to number of the component otherwise references to number of the component
""" """
if isinstance(i, str): if isinstance(i, str):
@@ -778,13 +802,13 @@ class DIV(XmlComponent):
def __len__(self): def __len__(self):
""" """
returns the number of included components Returns the number of included components
""" """
return len(self.components) return len(self.components)
def __nonzero__(self): def __nonzero__(self):
""" """
always return True Always returns True
""" """
return True return True
@@ -804,10 +828,11 @@ class DIV(XmlComponent):
helper for _fixup. Checks if a component is in allowed_parents, helper for _fixup. Checks if a component is in allowed_parents,
otherwise wraps it in wrap_parent otherwise wraps it in wrap_parent
:param allowed_parents: (tuple) classes that the component should be an Args:
instance of allowed_parents: (tuple) classes that the component should be an
:param wrap_parent: the class to wrap the component in, if needed instance of
:param wrap_lambda: lambda to use for wrapping, if needed wrap_parent: the class to wrap the component in, if needed
wrap_lambda: lambda to use for wrapping, if needed
""" """
components = [] components = []
@@ -875,7 +900,7 @@ class DIV(XmlComponent):
def _xml(self): def _xml(self):
""" """
helper for xml generation. Returns separately: Helper for xml generation. Returns separately:
- the component attributes - the component attributes
- the generated xml of the inner components - the generated xml of the inner components
@@ -883,7 +908,8 @@ class DIV(XmlComponent):
do not have a False or None value. The underscore is removed. do not have a False or None value. The underscore is removed.
A value of True is replaced with the attribute name. A value of True is replaced with the attribute name.
:returns: tuple: (attributes, components) Returns:
tuple: (attributes, components)
""" """
# get the attributes for this component # get the attributes for this component
@@ -932,16 +958,18 @@ class DIV(XmlComponent):
def __str__(self): def __str__(self):
""" """
str(COMPONENT) returns equals COMPONENT.xml() str(COMPONENT) returns COMPONENT.xml()
""" """
return self.xml() return self.xml()
def flatten(self, render=None): def flatten(self, render=None):
""" """
return the text stored by the DIV object rendered by the render function Returns the text stored by the DIV object rendered by the render function
the render function must take text, tagname, and attributes the render function must take text, tagname, and attributes
render=None is equivalent to render=lambda text, tag, attr: text `render=None` is equivalent to `render=lambda text, tag, attr: text`
Examples:
>>> markdown = lambda text,tag=None,attributes={}: \ >>> markdown = lambda text,tag=None,attributes={}: \
{None: re.sub('\s+',' ',text), \ {None: re.sub('\s+',' ',text), \
@@ -972,11 +1000,13 @@ class DIV(XmlComponent):
def elements(self, *args, **kargs): def elements(self, *args, **kargs):
""" """
find all component that match the supplied attribute dictionary, Find all components that match the supplied attribute dictionary,
or None if nothing could be found or None if nothing could be found
All components of the components are searched. All components of the components are searched.
Examples:
>>> a = DIV(DIV(SPAN('x'),3,DIV(SPAN('y')))) >>> a = DIV(DIV(SPAN('x'),3,DIV(SPAN('y'))))
>>> for c in a.elements('span',first_only=True): c[0]='z' >>> for c in a.elements('span',first_only=True): c[0]='z'
>>> print a >>> print a
@@ -987,6 +1017,8 @@ class DIV(XmlComponent):
It also supports a syntax compatible with jQuery It also supports a syntax compatible with jQuery
Examples:
>>> a=TAG('<div><span><a id="1-1" u:v=$>hello</a></span><p class="this is a test">world</p></div>') >>> a=TAG('<div><span><a id="1-1" u:v=$>hello</a></span><p class="this is a test">world</p></div>')
>>> for e in a.elements('div a#1-1, p.is'): print e.flatten() >>> for e in a.elements('div a#1-1, p.is'): print e.flatten()
hello hello
@@ -995,7 +1027,6 @@ class DIV(XmlComponent):
hello hello
>>> a.elements('a[u:v=$]')[0].xml() >>> a.elements('a[u:v=$]')[0].xml()
'<a id="1-1" u:v="$">hello</a>' '<a id="1-1" u:v="$">hello</a>'
>>> a=FORM( INPUT(_type='text'), SELECT(range(1)), TEXTAREA() ) >>> a=FORM( INPUT(_type='text'), SELECT(range(1)), TEXTAREA() )
>>> for c in a.elements('input, select, textarea'): c['_disabled'] = 'disabled' >>> for c in a.elements('input, select, textarea'): c['_disabled'] = 'disabled'
>>> a.xml() >>> a.xml()
@@ -1005,6 +1036,8 @@ class DIV(XmlComponent):
a "replace" argument (note, a list of the original matching elements a "replace" argument (note, a list of the original matching elements
is still returned as usual). is still returned as usual).
Examples:
>>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc')))) >>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc'))))
>>> b = a.elements('span.abc', replace=P('x', _class='xyz')) >>> b = a.elements('span.abc', replace=P('x', _class='xyz'))
>>> print a >>> print a
@@ -1013,6 +1046,8 @@ class DIV(XmlComponent):
"replace" can be a callable, which will be passed the original element and "replace" can be a callable, which will be passed the original element and
should return a new element to replace it. should return a new element to replace it.
Examples:
>>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc')))) >>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc'))))
>>> b = a.elements('span.abc', replace=lambda el: P(el[0], _class='xyz')) >>> b = a.elements('span.abc', replace=lambda el: P(el[0], _class='xyz'))
>>> print a >>> print a
@@ -1020,6 +1055,8 @@ class DIV(XmlComponent):
If replace=None, matching elements will be removed completely. If replace=None, matching elements will be removed completely.
Examples:
>>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc')))) >>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc'))))
>>> b = a.elements('span', find='y', replace=None) >>> b = a.elements('span', find='y', replace=None)
>>> print a >>> print a
@@ -1030,6 +1067,8 @@ class DIV(XmlComponent):
replaced (find_text is ignored if "replace" is not also specified). replaced (find_text is ignored if "replace" is not also specified).
Like the "find" argument, "find_text" can be a string or a compiled regex. Like the "find" argument, "find_text" can be a string or a compiled regex.
Examples:
>>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc')))) >>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='abc'), SPAN('z', _class='abc'))))
>>> b = a.elements(find_text=re.compile('x|y|z'), replace='hello') >>> b = a.elements(find_text=re.compile('x|y|z'), replace='hello')
>>> print a >>> print a
@@ -1038,6 +1077,8 @@ class DIV(XmlComponent):
If other attributes are specified along with find_text, then only components If other attributes are specified along with find_text, then only components
that match the specified attributes will be searched for find_text. that match the specified attributes will be searched for find_text.
Examples:
>>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='efg'), SPAN('z', _class='abc')))) >>> a = DIV(DIV(SPAN('x', _class='abc'), DIV(SPAN('y', _class='efg'), SPAN('z', _class='abc'))))
>>> b = a.elements('span.efg', find_text=re.compile('x|y|z'), replace='hello') >>> b = a.elements('span.efg', find_text=re.compile('x|y|z'), replace='hello')
>>> print a >>> print a
@@ -1134,7 +1175,7 @@ class DIV(XmlComponent):
def element(self, *args, **kargs): def element(self, *args, **kargs):
""" """
find the first component that matches the supplied attribute dictionary, Finds the first component that matches the supplied attribute dictionary,
or None if nothing could be found or None if nothing could be found
Also the components of the components are searched. Also the components of the components are searched.
@@ -1148,7 +1189,7 @@ class DIV(XmlComponent):
def siblings(self, *args, **kargs): def siblings(self, *args, **kargs):
""" """
find all sibling components that match the supplied argument list Finds all sibling components that match the supplied argument list
and attribute dictionary, or None if nothing could be found and attribute dictionary, or None if nothing could be found
""" """
sibs = [s for s in self.parent.components if not s == self] sibs = [s for s in self.parent.components if not s == self]
@@ -1175,7 +1216,7 @@ class DIV(XmlComponent):
def sibling(self, *args, **kargs): def sibling(self, *args, **kargs):
""" """
find the first sibling component that match the supplied argument list Finds the first sibling component that match the supplied argument list
and attribute dictionary, or None if nothing could be found and attribute dictionary, or None if nothing could be found
""" """
kargs['first_only'] = True kargs['first_only'] = True
@@ -1211,10 +1252,12 @@ copy_reg.pickle(__tag_div__, TAG_pickler, TAG_unpickler)
class __TAG__(XmlComponent): class __TAG__(XmlComponent):
""" """
TAG factory example:: TAG factory
>>> print TAG.first(TAG.second('test'), _key = 3) Examples:
<first key=\"3\"><second>test</second></first>
>>> print TAG.first(TAG.second('test'), _key = 3)
<first key=\"3\"><second>test</second></first>
""" """
@@ -1239,16 +1282,16 @@ class HTML(DIV):
There are four predefined document type definitions. There are four predefined document type definitions.
They can be specified in the 'doctype' parameter: They can be specified in the 'doctype' parameter:
-'strict' enables strict doctype - 'strict' enables strict doctype
-'transitional' enables transitional doctype (default) - 'transitional' enables transitional doctype (default)
-'frameset' enables frameset doctype - 'frameset' enables frameset doctype
-'html5' enables HTML 5 doctype - 'html5' enables HTML 5 doctype
-any other string will be treated as user's own doctype - any other string will be treated as user's own doctype
'lang' parameter specifies the language of the document. 'lang' parameter specifies the language of the document.
Defaults to 'en'. Defaults to 'en'.
See also :class:`DIV` See also `DIV`
""" """
tag = 'html' tag = 'html'
@@ -1289,10 +1332,10 @@ class XHTML(DIV):
There are three predefined document type definitions. There are three predefined document type definitions.
They can be specified in the 'doctype' parameter: They can be specified in the 'doctype' parameter:
-'strict' enables strict doctype - 'strict' enables strict doctype
-'transitional' enables transitional doctype (default) - 'transitional' enables transitional doctype (default)
-'frameset' enables frameset doctype - 'frameset' enables frameset doctype
-any other string will be treated as user's own doctype - any other string will be treated as user's own doctype
'lang' parameter specifies the language of the document and the xml document. 'lang' parameter specifies the language of the document and the xml document.
Defaults to 'en'. Defaults to 'en'.
@@ -1300,7 +1343,7 @@ class XHTML(DIV):
'xmlns' parameter specifies the xml namespace. 'xmlns' parameter specifies the xml namespace.
Defaults to 'http://www.w3.org/1999/xhtml'. Defaults to 'http://www.w3.org/1999/xhtml'.
See also :class:`DIV` See also `DIV`
""" """
tag = 'html' tag = 'html'
@@ -1443,7 +1486,7 @@ class P(DIV):
""" """
Will replace ``\\n`` by ``<br />`` if the `cr2br` attribute is provided. Will replace ``\\n`` by ``<br />`` if the `cr2br` attribute is provided.
see also :class:`DIV` see also `DIV`
""" """
tag = 'p' tag = 'p'
@@ -1476,6 +1519,23 @@ class HR(DIV):
class A(DIV): class A(DIV):
"""
Generates an A() link.
A() in web2py is really important and with the included web2py.js
allows lots of Ajax interactions in the page
On top of "usual" `_attributes`, it takes
Args:
callback: an url to call but not redirect to
cid: if you want to load the _href into an element of the page (component)
pass its id (without the #) here
delete: element to delete after calling callback
target: same thing as cid
confirm: text to display upon a callback with a delete
noconfirm: don't display alert upon a callback with delete
"""
tag = 'a' tag = 'a'
@@ -1546,24 +1606,25 @@ class CENTER(DIV):
class CODE(DIV): class CODE(DIV):
""" """
displays code in HTML with syntax highlighting. Displays code in HTML with syntax highlighting.
:param attributes: optional attributes: Args:
language: indicates the language, otherwise PYTHON is assumed
link: can provide a link
styles: for styles
- language: indicates the language, otherwise PYTHON is assumed Examples:
- link: can provide a link
- styles: for styles
Example:: {{=CODE(\"print 'hello world'\", language='python', link=None,
counter=1, styles={}, highlight_line=None)}}
{{=CODE(\"print 'hello world'\", language='python', link=None,
counter=1, styles={}, highlight_line=None)}}
supported languages are \"python\", \"html_plain\", \"c\", \"cpp\", supported languages are
\"web2py\", \"html\".
The \"html\" language interprets {{ and }} tags as \"web2py\" code, "python", "html_plain", "c", "cpp", "web2py", "html"
\"html_plain\" doesn't.
The "html" language interprets {{ and }} tags as "web2py" code,
"html_plain" doesn't.
if a link='/examples/global/vars/' is provided web2py keywords are linked to if a link='/examples/global/vars/' is provided web2py keywords are linked to
the online docs. the online docs.
@@ -1607,7 +1668,6 @@ class UL(DIV):
If subcomponents are not LI-components they will be wrapped in a LI If subcomponents are not LI-components they will be wrapped in a LI
see also :class:`DIV`
""" """
tag = 'ul' tag = 'ul'
@@ -1637,7 +1697,6 @@ class TR(DIV):
If subcomponents are not TD/TH-components they will be wrapped in a TD If subcomponents are not TD/TH-components they will be wrapped in a TD
see also :class:`DIV`
""" """
tag = 'tr' tag = 'tr'
@@ -1652,7 +1711,6 @@ class __TRHEAD__(DIV):
If subcomponents are not TD/TH-components they will be wrapped in a TH If subcomponents are not TD/TH-components they will be wrapped in a TH
see also :class:`DIV`
""" """
tag = 'tr' tag = 'tr'
@@ -1702,7 +1760,6 @@ class TABLE(DIV):
If subcomponents are not TR/TBODY/THEAD/TFOOT-components If subcomponents are not TR/TBODY/THEAD/TFOOT-components
they will be wrapped in a TR they will be wrapped in a TR
see also :class:`DIV`
""" """
tag = 'table' tag = 'table'
@@ -1724,34 +1781,36 @@ class IFRAME(DIV):
class INPUT(DIV): class INPUT(DIV):
""" """
INPUT Component INPUT Component
examples:: Takes two special attributes value= and requires=.
>>> INPUT(_type='text', _name='name', value='Max').xml() Args:
'<input name=\"name\" type=\"text\" value=\"Max\" />' value: used to pass the initial value for the input field.
>>> INPUT(_type='checkbox', _name='checkbox', value='on').xml()
'<input checked=\"checked\" name=\"checkbox\" type=\"checkbox\" value=\"on\" />'
>>> INPUT(_type='radio', _name='radio', _value='yes', value='yes').xml()
'<input checked=\"checked\" name=\"radio\" type=\"radio\" value=\"yes\" />'
>>> INPUT(_type='radio', _name='radio', _value='no', value='yes').xml()
'<input name=\"radio\" type=\"radio\" value=\"no\" />'
the input helper takes two special attributes value= and requires=.
:param value: used to pass the initial value for the input field.
value differs from _value because it works for checkboxes, radio, value differs from _value because it works for checkboxes, radio,
textarea and select/option too. textarea and select/option too.
For a checkbox value should be '' or 'on'.
For a radio or select/option value should be the _value
of the checked/selected item.
- for a checkbox value should be '' or 'on'. requires: should be None, or a validator or a list of validators
- for a radio or select/option value should be the _value
of the checked/selected item.
:param requires: should be None, or a validator or a list of validators
for the value of the field. for the value of the field.
Examples:
>>> INPUT(_type='text', _name='name', value='Max').xml()
'<input name=\"name\" type=\"text\" value=\"Max\" />'
>>> INPUT(_type='checkbox', _name='checkbox', value='on').xml()
'<input checked=\"checked\" name=\"checkbox\" type=\"checkbox\" value=\"on\" />'
>>> INPUT(_type='radio', _name='radio', _value='yes', value='yes').xml()
'<input checked=\"checked\" name=\"radio\" type=\"radio\" value=\"yes\" />'
>>> INPUT(_type='radio', _name='radio', _value='no', value='yes').xml()
'<input name=\"radio\" type=\"radio\" value=\"no\" />'
""" """
tag = 'input/' tag = 'input/'
@@ -1847,11 +1906,12 @@ class INPUT(DIV):
class TEXTAREA(INPUT): class TEXTAREA(INPUT):
""" """
example:: Examples::
TEXTAREA(_name='sometext', value='blah '*100, requires=IS_NOT_EMPTY()) TEXTAREA(_name='sometext', value='blah ' * 100, requires=IS_NOT_EMPTY())
'blah blah blah ...' will be the content of the textarea field. 'blah blah blah ...' will be the content of the textarea field.
""" """
tag = 'textarea' tag = 'textarea'
@@ -1898,12 +1958,12 @@ class OPTGROUP(DIV):
class SELECT(INPUT): class SELECT(INPUT):
""" """
example:: Examples:
>>> from validators import IS_IN_SET >>> from validators import IS_IN_SET
>>> SELECT('yes', 'no', _name='selector', value='yes', >>> SELECT('yes', 'no', _name='selector', value='yes',
... requires=IS_IN_SET(['yes', 'no'])).xml() ... requires=IS_IN_SET(['yes', 'no'])).xml()
'<select name=\"selector\"><option selected=\"selected\" value=\"yes\">yes</option><option value=\"no\">no</option></select>' '<select name=\"selector\"><option selected=\"selected\" value=\"yes\">yes</option><option value=\"no\">no</option></select>'
""" """
@@ -1962,12 +2022,13 @@ class LEGEND(DIV):
class FORM(DIV): class FORM(DIV):
""" """
example:: Examples:
>>> from validators import IS_NOT_EMPTY
>>> form=FORM(INPUT(_name="test", requires=IS_NOT_EMPTY()))
>>> form.xml()
'<form action=\"#\" enctype=\"multipart/form-data\" method=\"post\"><input name=\"test\" type=\"text\" /></form>'
>>> from validators import IS_NOT_EMPTY
>>> form=FORM(INPUT(_name="test", requires=IS_NOT_EMPTY()))
>>> form.xml()
'<form action=\"#\" enctype=\"multipart/form-data\" method=\"post\"><input name=\"test\" type=\"text\" /></form>'
a FORM is container for INPUT, TEXTAREA, SELECT and other helpers a FORM is container for INPUT, TEXTAREA, SELECT and other helpers
@@ -2107,12 +2168,12 @@ class FORM(DIV):
you can use it instead of directly form.accepts. you can use it instead of directly form.accepts.
Usage: Usage:
In controller In controller::
def action(): def action():
form=FORM(INPUT(_name=\"test\", requires=IS_NOT_EMPTY())) form=FORM(INPUT(_name=\"test\", requires=IS_NOT_EMPTY()))
form.validate() #you can pass some args here - see below form.validate() #you can pass some args here - see below
return dict(form=form) return dict(form=form)
This can receive a bunch of arguments This can receive a bunch of arguments
@@ -2190,29 +2251,31 @@ class FORM(DIV):
""" """
Perform the .validate() method but returns the form Perform the .validate() method but returns the form
Usage in controllers: Usage in controllers::
# directly on return
def action():
#some code here
return dict(form=FORM(...).process(...))
You can use it with FORM, SQLFORM or FORM based plugins # directly on return
def action():
#some code here
return dict(form=FORM(...).process(...))
Examples: You can use it with FORM, SQLFORM or FORM based plugins::
#response.flash messages
def action(): # response.flash messages
form = SQLFORM(db.table).process(message_onsuccess='Sucess!') def action():
retutn dict(form=form) form = SQLFORM(db.table).process(message_onsuccess='Sucess!')
return dict(form=form)
# callback function
# callback receives True or False as first arg, and a list of args.
def my_callback(status, msg):
response.flash = "Success! "+msg if status else "Errors occured"
# after argument can be 'flash' to response.flash messages
# or a function name to use as callback or None to do nothing.
def action():
return dict(form=SQLFORM(db.table).process(onsuccess=my_callback)
# callback function
# callback receives True or False as first arg, and a list of args.
def my_callback(status, msg):
response.flash = "Success! "+msg if status else "Errors occured"
# after argument can be 'flash' to response.flash messages
# or a function name to use as callback or None to do nothing.
def action():
return dict(form=SQLFORM(db.table).process(onsuccess=my_callback)
""" """
kwargs['dbio'] = kwargs.get('dbio', True) kwargs['dbio'] = kwargs.get('dbio', True)
# necessary for SQLHTML forms # necessary for SQLHTML forms
@@ -2223,7 +2286,7 @@ class FORM(DIV):
def add_button(self, value, url, _class=None): def add_button(self, value, url, _class=None):
submit = self.element(_type='submit') submit = self.element(_type='submit')
_class = "%s w2p-form-button" % _class if _class else "w2p-form-button" _class = "%s w2p-form-button" % _class if _class else "w2p-form-button"
submit.parent.append( submit.parent.append(
TAG['button'](value, _class=_class, TAG['button'](value, _class=_class,
_onclick=url if url.startswith('javascript:') else _onclick=url if url.startswith('javascript:') else
@@ -2313,16 +2376,20 @@ class FORM(DIV):
class BEAUTIFY(DIV): class BEAUTIFY(DIV):
""" """
example:: Turns any list, dictionary, etc into decent looking html.
>>> BEAUTIFY(['a', 'b', {'hello': 'world'}]).xml()
'<div><table><tr><td><div>a</div></td></tr><tr><td><div>b</div></td></tr><tr><td><div><table><tr><td style="font-weight:bold;vertical-align:top;">hello</td><td style="vertical-align:top;">:</td><td><div>world</div></td></tr></table></div></td></tr></table></div>'
turns any list, dictionary, etc into decent looking html.
Two special attributes are Two special attributes are
:sorted: a function that takes the dict and returned sorted keys
:keyfilter: a funciton that takes a key and returns its representation - sorted: a function that takes the dict and returned sorted keys
or None if the key is to be skipped. By default key[:1]=='_' is skipped. - keyfilter: a function that takes a key and returns its representation or
None if the key is to be skipped.
By default key[:1]=='_' is skipped.
Examples:
>>> BEAUTIFY(['a', 'b', {'hello': 'world'}]).xml()
'<div><table><tr><td><div>a</div></td></tr><tr><td><div>b</div></td></tr><tr><td><div><table><tr><td style="font-weight:bold;vertical-align:top;">hello</td><td style="vertical-align:top;">:</td><td><div>world</div></td></tr></table></div></td></tr></table></div>'
""" """
tag = 'div' tag = 'div'
@@ -2394,16 +2461,18 @@ class MENU(DIV):
""" """
Used to build menus Used to build menus
Optional arguments Args:
_class: defaults to 'web2py-menu web2py-menu-vertical' _class: defaults to 'web2py-menu web2py-menu-vertical'
ul_class: defaults to 'web2py-menu-vertical' ul_class: defaults to 'web2py-menu-vertical'
li_class: defaults to 'web2py-menu-expand' li_class: defaults to 'web2py-menu-expand'
li_first: defaults to 'web2py-menu-first' li_first: defaults to 'web2py-menu-first'
li_last: defaults to 'web2py-menu-last' li_last: defaults to 'web2py-menu-last'
Use like::
Example:
menu = MENU([['name', False, URL(...), [submenu]], ...]) menu = MENU([['name', False, URL(...), [submenu]], ...])
{{=menu}} {{=menu}}
""" """
tag = 'ul' tag = 'ul'
@@ -2503,9 +2572,10 @@ def embed64(
""" """
helper to encode the provided (binary) data into base64. helper to encode the provided (binary) data into base64.
:param filename: if provided, opens and reads this file in 'rb' mode Args:
:param file: if provided, reads this file filename: if provided, opens and reads this file in 'rb' mode
:param data: if provided, uses the provided data file: if provided, reads this file
data: if provided, uses the provided data
""" """
if filename and os.path.exists(file): if filename and os.path.exists(file):