source: publico/il.spdo/trunk/Paste-1.7.5.1-py2.6.egg/paste/debug/wdg_validate.py @ 5327

Última Alteração nesse arquivo desde 5327 foi 5327, incluída por fabianosantos, 8 anos atrás

Import inicial.

File size: 4.2 KB
Linha 
1# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
2# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
3"""
4Middleware that tests the validity of all generated HTML using the
5`WDG HTML Validator <http://www.htmlhelp.com/tools/validator/>`_
6"""
7
8from cStringIO import StringIO
9try:
10    import subprocess
11except ImportError:
12    from paste.util import subprocess24 as subprocess
13from paste.response import header_value
14import re
15import cgi
16
17__all__ = ['WDGValidateMiddleware']
18
19class WDGValidateMiddleware(object):
20
21    """
22    Middleware that checks HTML and appends messages about the validity of
23    the HTML.  Uses: http://www.htmlhelp.com/tools/validator/ -- interacts
24    with the command line client.  Use the configuration ``wdg_path`` to
25    override the path (default: looks for ``validate`` in $PATH).
26
27    To install, in your web context's __init__.py::
28
29        def urlparser_wrap(environ, start_response, app):
30            return wdg_validate.WDGValidateMiddleware(app)(
31                environ, start_response)
32
33    Or in your configuration::
34
35        middleware.append('paste.wdg_validate.WDGValidateMiddleware')
36    """
37
38    _end_body_regex = re.compile(r'</body>', re.I)
39
40    def __init__(self, app, global_conf=None, wdg_path='validate'):
41        self.app = app
42        self.wdg_path = wdg_path
43
44    def __call__(self, environ, start_response):
45        output = StringIO()
46        response = []
47
48        def writer_start_response(status, headers, exc_info=None):
49            response.extend((status, headers))
50            start_response(status, headers, exc_info)
51            return output.write
52
53        app_iter = self.app(environ, writer_start_response)
54        try:
55            for s in app_iter:
56                output.write(s)
57        finally:
58            if hasattr(app_iter, 'close'):
59                app_iter.close()
60        page = output.getvalue()
61        status, headers = response
62        v = header_value(headers, 'content-type') or ''
63        if (not v.startswith('text/html')
64            and not v.startswith('text/xhtml')
65            and not v.startswith('application/xhtml')):
66            # Can't validate
67            # @@: Should validate CSS too... but using what?
68            return [page]
69        ops = []
70        if v.startswith('text/xhtml+xml'):
71            ops.append('--xml')
72        # @@: Should capture encoding too
73        html_errors = self.call_wdg_validate(
74            self.wdg_path, ops, page)
75        if html_errors:
76            page = self.add_error(page, html_errors)[0]
77            headers.remove(
78                     ('Content-Length',
79                      str(header_value(headers, 'content-length'))))
80            headers.append(('Content-Length', str(len(page))))
81        return [page]
82
83    def call_wdg_validate(self, wdg_path, ops, page):
84        if subprocess is None:
85            raise ValueError(
86                "This middleware requires the subprocess module from "
87                "Python 2.4")
88        proc = subprocess.Popen([wdg_path] + ops,
89                                shell=False,
90                                close_fds=True,
91                                stdout=subprocess.PIPE,
92                                stdin=subprocess.PIPE,
93                                stderr=subprocess.STDOUT)
94        stdout = proc.communicate(page)[0]
95        proc.wait()
96        return stdout
97
98    def add_error(self, html_page, html_errors):
99        add_text = ('<pre style="background-color: #ffd; color: #600; '
100                    'border: 1px solid #000;">%s</pre>'
101                    % cgi.escape(html_errors))
102        match = self._end_body_regex.search(html_page)
103        if match:
104            return [html_page[:match.start()]
105                    + add_text
106                    + html_page[match.start():]]
107        else:
108            return [html_page + add_text]
109
110def make_wdg_validate_middleware(
111    app, global_conf, wdg_path='validate'):
112    """
113    Wraps the application in the WDG validator from
114    http://www.htmlhelp.com/tools/validator/
115
116    Validation errors are appended to the text of each page.
117    You can configure this by giving the path to the validate
118    executable (by default picked up from $PATH)
119    """
120    return WDGValidateMiddleware(
121        app, global_conf, wdg_path=wdg_path)
Note: Veja TracBrowser para ajuda no uso do navegador do trac.
 

The contents and data of this website are published under license:
Creative Commons 4.0 Brasil - Atribuir Fonte - Compartilhar Igual.