<s> """<STR_LIT>""" <EOL> from cStringIO import StringIO <EOL> import subprocess <EOL> from paste . response import header_value <EOL> import re <EOL> import cgi <EOL> __all__ = [ '<STR_LIT>' ] <EOL> class WDGValidateMiddleware ( object ) : <EOL> """<STR_LIT>""" <EOL> _end_body_regex = re . compile ( r'<STR_LIT>' , re . I ) <EOL> def __init__ ( self , app , global_conf = None , wdg_path = '<STR_LIT>' ) : <EOL> self . app = app <EOL> self . wdg_path = wdg_path <EOL> def __call__ ( self , environ , start_response ) : <EOL> output = StringIO ( ) <EOL> response = [ ] <EOL> def writer_start_response ( status , headers , exc_info = None ) : <EOL> response . extend ( ( status , headers ) ) <EOL> start_response ( status , headers , exc_info ) <EOL> return output . write <EOL> app_iter = self . app ( environ , writer_start_response ) <EOL> try : <EOL> for s in app_iter : <EOL> output . write ( s ) <EOL> finally : <EOL> if hasattr ( app_iter , '<STR_LIT>' ) : <EOL> app_iter . close ( ) <EOL> page = output . getvalue ( ) <EOL> status , headers = response <EOL> v = header_value ( headers , '<STR_LIT>' ) or '<STR_LIT>' <EOL> if ( not v . startswith ( '<STR_LIT>' ) <EOL> and not v . startswith ( '<STR_LIT>' ) <EOL> and not v . startswith ( '<STR_LIT>' ) ) : <EOL> return [ page ] <EOL> ops = [ ] <EOL> if v . startswith ( '<STR_LIT>' ) : <EOL> ops . append ( '<STR_LIT>' ) <EOL> html_errors = self . call_wdg_validate ( <EOL> self . wdg_path , ops , page ) <EOL> if html_errors : <EOL> page = self . add_error ( page , html_errors ) [ <NUM_LIT:0> ] <EOL> headers . remove ( <EOL> ( '<STR_LIT>' , <EOL> str ( header_value ( headers , '<STR_LIT>' ) ) ) ) <EOL> headers . append ( ( '<STR_LIT>' , str ( len ( page ) ) ) ) <EOL> return [ page ] <EOL> def call_wdg_validate ( self , wdg_path , ops , page ) : <EOL> if subprocess is None : <EOL> raise ValueError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" ) <EOL> proc = subprocess . Popen ( [ wdg_path ] + ops , <EOL> shell = False , <EOL> close_fds = True , <EOL> stdout = subprocess . PIPE , <EOL> stdin = subprocess . PIPE , <EOL> stderr = subprocess . STDOUT ) <EOL> stdout = proc . communicate ( page ) [ <NUM_LIT:0> ] <EOL> proc . wait ( ) <EOL> return stdout <EOL> def add_error ( self , html_page , html_errors ) : <EOL> add_text = ( '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> % cgi . escape ( html_errors ) ) <EOL> match = self . _end_body_regex . search ( html_page ) <EOL> if match : <EOL> return [ html_page [ : match . start ( ) ] <EOL> + add_text <EOL> + html_page [ match . start ( ) : ] ] <EOL> else : <EOL> return [ html_page + add_text ] <EOL> def make_wdg_validate_middleware ( <EOL> app , global_conf , wdg_path = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> return WDGValidateMiddleware ( <EOL> app , global_conf , wdg_path = wdg_path ) </s>
