• 1675 views
  • 0 comments
  • loading...

XML is an object used to encapsulate text that should not be escaped. The text may or may not contain valid XML. For example, it could contain JavaScript.

Sometimes you want to render HTML stored in a variable, but the HTML may contain unsafe tags such as scripts.

Un-escaped executable input such as this (for example, entered in the body of a comment in a blog) is unsafe, because it can be used to generate Cross Site Scripting (XSS) attacks against other visitors to the page.

The web2py XML helper can sanitize our text to prevent injections and escape all tags except those that you explicitly allow.

The XML constructors, by default, consider the content of some tags and some of their attributes safe. You can override the defaults using the optional permitted_tags and allowed_attributes arguments. Here are the default values of the optional arguments of the XML helper.
























# The text in this example is escaped:


>>> print DIV("<b>hello</b>")
&
lt;b&gt;hello&lt;/b&gt;



# by using XML you can prevent escaping:
>>> print DIV(XML("<b>hello</b>"))
<
b>hello</b>

>>>
print XML('<script>alert("unsafe!")</script>')
<
script>alert("unsafe!")</script>

>>>
print XML('<script>alert("unsafe!")</script>', sanitize=True)
&
lt;script&gt;alert(&quot;unsafe!&quot;)&lt;/script&gt;


XML(text, sanitize=False,
permitted_tags=['a', 'b', 'blockquote', 'br/', 'i', 'li',
'ol', 'ul', 'p', 'cite', 'code', 'pre', 'img/'],
allowed_attributes={'a':['href', 'title'],
'img':['src', 'alt'], 'blockquote':['type']})

Attributes / Arguments

Text to be encapsulated

XML('text')

XML(record.text)


XML(text, sanitize=False)

Set which html tags are permited.

XML(text,  
        permitted_tags=
            ['a', 'b', 'blockquote', 'br/', 'i', 'li', 'ol', 'ul', 'p', 'cite', 'code', 'pre', 'img/'])


XML(text, sanitize=False,
    permitted_tags=['a', 'b', 'blockquote', 'br/', 'i', 'li', 'ol', 'ul', 'p', 'cite', 'code', 'pre', 'img/'],
    allowed_attributes=
        {'a':['href', 'title'],'img':['src', 'alt'], 'blockquote':['type']})


Examples

loading...


Comments

loading...

Powered by
Web2py

Hosted on
www.pythonanywhere.com
(affiliated link)