Example #1
0
 def __init__(self, *args, **kw):
     HTMLParser.__init__(self, *args, **kw)
     self.sami = ''
     self.line = ''
     self.styles = {}
     self.queue = deque()
     self.langs = set()
     self.last_element = ''
     self.name2codepoint = name2codepoint.copy()
     self.name2codepoint['apos'] = 0x0027
Example #2
0
 def __init__(self, *args, **kw):
     HTMLParser.__init__(self, *args, **kw)
     self.sami = ''
     self.line = ''
     self.styles = {}
     self.queue = deque()
     self.langs = set()
     self.last_element = ''
     self.name2codepoint = name2codepoint.copy()
     self.name2codepoint['apos'] = 0x0027
     self.convert_charrefs = False
Example #3
0
 def __init__(self, *args, **kw):
     # Delay expensive import as long as possible
     from cssutils import parseString, log, css
     # change cssutils default logging
     log.setLevel(FATAL)
     self.parseString = parseString
     self.ColorValue = css.ColorValue
     HTMLParser.__init__(self, *args, **kw)
     self.sami = ''
     self.line = ''
     self.styles = {}
     self.queue = deque()
     self.langs = set()
     self.last_element = ''
     self.name2codepoint = name2codepoint.copy()
     self.name2codepoint['apos'] = 0x0027
     self.convert_charrefs = False
Example #4
0
class HTMLBuilder(object):

    """Helper object for HTML generation.

    Per default there are two instances of that class.  The `html` one, and
    the `xhtml` one for those two dialects.  The class uses keyword parameters
    and positional parameters to generate small snippets of HTML.

    Keyword parameters are converted to XML/SGML attributes, positional
    arguments are used as children.  Because Python accepts positional
    arguments before keyword arguments it's a good idea to use a list with the
    star-syntax for some children:

    >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ',
    ...                        html.a('bar', href='bar.html')])
    u'<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'

    This class works around some browser limitations and can not be used for
    arbitrary SGML/XML generation.  For that purpose lxml and similar
    libraries exist.

    Calling the builder escapes the string passed:

    >>> html.p(html("<foo>"))
    u'<p>&lt;foo&gt;</p>'
    """

    _entity_re = re.compile(r'&([^;]+);')
    _entities = name2codepoint.copy()
    _entities['apos'] = 39
    _empty_elements = set([
        'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame',
        'hr', 'img', 'input', 'keygen', 'isindex', 'link', 'meta', 'param',
        'source', 'wbr'
    ])
    _boolean_attributes = set([
        'selected', 'checked', 'compact', 'declare', 'defer', 'disabled',
        'ismap', 'multiple', 'nohref', 'noresize', 'noshade', 'nowrap'
    ])
    _plaintext_elements = set(['textarea'])
    _c_like_cdata = set(['script', 'style'])

    def __init__(self, dialect):
        self._dialect = dialect

    def __call__(self, s):
        return escape(s)

    def __getattr__(self, tag):
        if tag[:2] == '__':
            raise AttributeError(tag)

        def proxy(*children, **arguments):
            buffer = '<' + tag
            for key, value in iteritems(arguments):
                if value is None:
                    continue
                if key[-1] == '_':
                    key = key[:-1]
                if key in self._boolean_attributes:
                    if not value:
                        continue
                    if self._dialect == 'xhtml':
                        value = '="' + key + '"'
                    else:
                        value = ''
                else:
                    value = '="' + escape(value) + '"'
                buffer += ' ' + key + value
            if not children and tag in self._empty_elements:
                if self._dialect == 'xhtml':
                    buffer += ' />'
                else:
                    buffer += '>'
                return buffer
            buffer += '>'

            children_as_string = ''.join([text_type(x) for x in children
                                          if x is not None])

            if children_as_string:
                if tag in self._plaintext_elements:
                    children_as_string = escape(children_as_string)
                elif tag in self._c_like_cdata and self._dialect == 'xhtml':
                    children_as_string = '/*<![CDATA[*/' + \
                                         children_as_string + '/*]]>*/'
            buffer += children_as_string + '</' + tag + '>'
            return buffer
        return proxy

    def __repr__(self):
        return '<%s for %r>' % (
            self.__class__.__name__,
            self._dialect
        )
Example #5
0
class HTMLBuilder:
    """Helper object for HTML generation.

    Per default there are two instances of that class.  The `html` one, and
    the `xhtml` one for those two dialects.  The class uses keyword parameters
    and positional parameters to generate small snippets of HTML.

    Keyword parameters are converted to XML/SGML attributes, positional
    arguments are used as children.  Because Python accepts positional
    arguments before keyword arguments it's a good idea to use a list with the
    star-syntax for some children:

    >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ',
    ...                        html.a('bar', href='bar.html')])
    '<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'

    This class works around some browser limitations and can not be used for
    arbitrary SGML/XML generation.  For that purpose lxml and similar
    libraries exist.

    Calling the builder escapes the string passed:

    >>> html.p(html("<foo>"))
    '<p>&lt;foo&gt;</p>'

    .. deprecated:: 2.0
        Will be removed in Werkzeug 2.1.
    """

    _entity_re = re.compile(r"&([^;]+);")
    _entities = name2codepoint.copy()
    _entities["apos"] = 39
    _empty_elements = {
        "area",
        "base",
        "basefont",
        "br",
        "col",
        "command",
        "embed",
        "frame",
        "hr",
        "img",
        "input",
        "keygen",
        "isindex",
        "link",
        "meta",
        "param",
        "source",
        "wbr",
    }
    _boolean_attributes = {
        "selected",
        "checked",
        "compact",
        "declare",
        "defer",
        "disabled",
        "ismap",
        "multiple",
        "nohref",
        "noresize",
        "noshade",
        "nowrap",
    }
    _plaintext_elements = {"textarea"}
    _c_like_cdata = {"script", "style"}

    def __init__(self, dialect):  # type: ignore
        self._dialect = dialect

    def __call__(self, s):  # type: ignore
        import html

        warnings.warn(
            "'utils.HTMLBuilder' is deprecated and will be removed in Werkzeug 2.1.",
            DeprecationWarning,
            stacklevel=2,
        )
        return html.escape(s)

    def __getattr__(self, tag):  # type: ignore
        import html

        warnings.warn(
            "'utils.HTMLBuilder' is deprecated and will be removed in Werkzeug 2.1.",
            DeprecationWarning,
            stacklevel=2,
        )
        if tag[:2] == "__":
            raise AttributeError(tag)

        def proxy(*children, **arguments):  # type: ignore
            buffer = f"<{tag}"
            for key, value in arguments.items():
                if value is None:
                    continue
                if key[-1] == "_":
                    key = key[:-1]
                if key in self._boolean_attributes:
                    if not value:
                        continue
                    if self._dialect == "xhtml":
                        value = f'="{key}"'
                    else:
                        value = ""
                else:
                    value = f'="{html.escape(value)}"'
                buffer += f" {key}{value}"
            if not children and tag in self._empty_elements:
                if self._dialect == "xhtml":
                    buffer += " />"
                else:
                    buffer += ">"
                return buffer
            buffer += ">"

            children_as_string = "".join(
                [str(x) for x in children if x is not None])

            if children_as_string:
                if tag in self._plaintext_elements:
                    children_as_string = html.escape(children_as_string)
                elif tag in self._c_like_cdata and self._dialect == "xhtml":
                    children_as_string = f"/*<![CDATA[*/{children_as_string}/*]]>*/"
            buffer += children_as_string + f"</{tag}>"
            return buffer

        return proxy

    def __repr__(self) -> str:
        return f"<{type(self).__name__} for {self._dialect!r}>"
Example #6
0
# let's use jinja for templates this time
template_path = path.join(path.dirname(__file__), "templates")
jinja_env = Environment(loader=FileSystemLoader(template_path))

# the collected url patterns
url_map = Map([Rule("/shared/<path:file>", endpoint="shared")])
endpoints = {}

_par_re = re.compile(r"\n{2,}")
_entity_re = re.compile(r"&([^;]+);")
_striptags_re = re.compile(r"(<!--.*-->|<[^>]*>)")

from html.entities import name2codepoint

html_entities = name2codepoint.copy()
html_entities["apos"] = 39
del name2codepoint


def expose(url_rule, endpoint=None, **kwargs):
    """Expose this function to the web layer."""
    def decorate(f):
        e = endpoint or f.__name__
        endpoints[e] = f
        url_map.add(Rule(url_rule, endpoint=e, **kwargs))
        return f

    return decorate

Example #7
0
class HTMLBuilder(object):
    """Helper object for HTML generation.

    Per default there are two instances of that class.  The `html` one, and
    the `xhtml` one for those two dialects.  The class uses keyword parameters
    and positional parameters to generate small snippets of HTML.

    Keyword parameters are converted to XML/SGML attributes, positional
    arguments are used as children.  Because Python accepts positional
    arguments before keyword arguments it's a good idea to use a list with the
    star-syntax for some children:

    >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ',
    ...                        html.a('bar', href='bar.html')])
    u'<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'

    This class works around some browser limitations and can not be used for
    arbitrary SGML/XML generation.  For that purpose lxml and similar
    libraries exist.

    Calling the builder escapes the string passed:

    >>> html.p(html("<foo>"))
    u'<p>&lt;foo&gt;</p>'
    """

    _entity_re = re.compile(r"&([^;]+);")
    _entities = name2codepoint.copy()
    _entities["apos"] = 39
    _empty_elements = {
        "area",
        "base",
        "basefont",
        "br",
        "col",
        "command",
        "embed",
        "frame",
        "hr",
        "img",
        "input",
        "keygen",
        "isindex",
        "link",
        "meta",
        "param",
        "source",
        "wbr",
    }
    _boolean_attributes = {
        "selected",
        "checked",
        "compact",
        "declare",
        "defer",
        "disabled",
        "ismap",
        "multiple",
        "nohref",
        "noresize",
        "noshade",
        "nowrap",
    }
    _plaintext_elements = {"textarea"}
    _c_like_cdata = {"script", "style"}

    def __init__(self, dialect):
        self._dialect = dialect

    def __call__(self, s):
        return escape(s)

    def __getattr__(self, tag):
        if tag[:2] == "__":
            raise AttributeError(tag)

        def proxy(*children, **arguments):
            buffer = "<" + tag
            for key, value in iteritems(arguments):
                if value is None:
                    continue
                if key[-1] == "_":
                    key = key[:-1]
                if key in self._boolean_attributes:
                    if not value:
                        continue
                    if self._dialect == "xhtml":
                        value = '="' + key + '"'
                    else:
                        value = ""
                else:
                    value = '="' + escape(value) + '"'
                buffer += " " + key + value
            if not children and tag in self._empty_elements:
                if self._dialect == "xhtml":
                    buffer += " />"
                else:
                    buffer += ">"
                return buffer
            buffer += ">"

            children_as_string = "".join(
                [text_type(x) for x in children if x is not None]
            )

            if children_as_string:
                if tag in self._plaintext_elements:
                    children_as_string = escape(children_as_string)
                elif tag in self._c_like_cdata and self._dialect == "xhtml":
                    children_as_string = (
                        "/*<![CDATA[*/" + children_as_string + "/*]]>*/"
                    )
            buffer += children_as_string + "</" + tag + ">"
            return buffer

        return proxy

    def __repr__(self):
        return "<%s for %r>" % (self.__class__.__name__, self._dialect)
Example #8
0
# the collected url patterns
url_map = Map([Rule("/shared/<path:file>", endpoint="shared")])
endpoints = {}


_par_re = re.compile(r"\n{2,}")
_entity_re = re.compile(r"&([^;]+);")
_striptags_re = re.compile(r"(<!--.*-->|<[^>]*>)")

try:
    from html.entities import name2codepoint
except ImportError:
    from htmlentitydefs import name2codepoint

html_entities = name2codepoint.copy()
html_entities["apos"] = 39
del name2codepoint


def expose(url_rule, endpoint=None, **kwargs):
    """Expose this function to the web layer."""

    def decorate(f):
        e = endpoint or f.__name__
        endpoints[e] = f
        url_map.add(Rule(url_rule, endpoint=e, **kwargs))
        return f

    return decorate