<s> from pulsar import Http404 <EOL> from pulsar . apps . wsgi import handle_wsgi_error , WsgiResponse <EOL> from . utils import wait <EOL> class GreenWSGI : <EOL> '''<STR_LIT>''' <EOL> def __init__ ( self , middleware , pool , response_middleware = None ) : <EOL> if not isinstance ( middleware , ( list , tuple ) ) : <EOL> middleware = [ middleware ] <EOL> self . middleware = list ( middleware ) <EOL> self . response_middleware = response_middleware or [ ] <EOL> self . pool = pool <EOL> def __call__ ( self , environ , start_response ) : <EOL> if self . pool . in_green_worker : <EOL> return self . _call ( environ , start_response ) <EOL> else : <EOL> return self . pool . submit ( self . _call , environ , start_response ) <EOL> def _call ( self , environ , start_response ) : <EOL> if environ [ '<STR_LIT>' ] : <EOL> environ [ '<STR_LIT>' ] = GreenStream ( environ [ '<STR_LIT>' ] ) <EOL> response = None <EOL> try : <EOL> for middleware in self . middleware : <EOL> response = wait ( middleware ( environ , start_response ) ) <EOL> if response is not None : <EOL> break <EOL> if response is None : <EOL> raise Http404 <EOL> except Exception as exc : <EOL> response = wait ( handle_wsgi_error ( environ , exc ) ) <EOL> if isinstance ( response , WsgiResponse ) and not response . started : <EOL> for middleware in self . response_middleware : <EOL> response = wait ( middleware ( environ , response ) ) or response <EOL> response . start ( start_response ) <EOL> return response <EOL> class GreenStream : <EOL> __slots__ = ( '<STR_LIT>' , ) <EOL> def __init__ ( self , stream ) : <EOL> self . stream = stream <EOL> def __getattr__ ( self , name ) : <EOL> value = getattr ( self . stream , name ) <EOL> if getattr ( value , '<STR_LIT>' , None ) is self . stream : <EOL> return _green ( value ) <EOL> return value <EOL> class _green : <EOL> __slots__ = ( '<STR_LIT:value>' , ) <EOL> def __init__ ( self , value ) : <EOL> self . value = value <EOL> def __getattr__ ( self , name ) : <EOL> return getattr ( self . value , name ) <EOL> def __call__ ( self , * args , ** kwargs ) : <EOL> return wait ( self . value ( * args , ** kwargs ) ) </s>
