<s> from logging import getLogger <EOL> from functools import partial <EOL> from eventlet . event import Event <EOL> import six <EOL> from werkzeug . wrappers import Response <EOL> from werkzeug . routing import Rule <EOL> from nameko . exceptions import serialize , BadRequest <EOL> from nameko . extensions import Entrypoint <EOL> from nameko . web . server import WebServer <EOL> _log = getLogger ( __name__ ) <EOL> class HttpRequestHandler ( Entrypoint ) : <EOL> server = WebServer ( ) <EOL> def __init__ ( self , method , url , expected_exceptions = ( ) ) : <EOL> self . method = method <EOL> self . url = url <EOL> self . expected_exceptions = expected_exceptions <EOL> def get_url_rule ( self ) : <EOL> return Rule ( self . url , methods = [ self . method ] ) <EOL> def setup ( self ) : <EOL> self . server . register_provider ( self ) <EOL> def stop ( self ) : <EOL> self . server . unregister_provider ( self ) <EOL> super ( HttpRequestHandler , self ) . stop ( ) <EOL> def get_entrypoint_parameters ( self , request ) : <EOL> args = ( request , ) <EOL> kwargs = request . path_values <EOL> return args , kwargs <EOL> def handle_request ( self , request ) : <EOL> request . shallow = False <EOL> try : <EOL> context_data = self . server . context_data_from_headers ( request ) <EOL> args , kwargs = self . get_entrypoint_parameters ( request ) <EOL> self . check_signature ( args , kwargs ) <EOL> event = Event ( ) <EOL> self . container . spawn_worker ( <EOL> self , args , kwargs , context_data = context_data , <EOL> handle_result = partial ( self . handle_result , event ) ) <EOL> result = event . wait ( ) <EOL> response = self . response_from_result ( result ) <EOL> except Exception as exc : <EOL> response = self . response_from_exception ( exc ) <EOL> return response <EOL> def handle_result ( self , event , worker_ctx , result , exc_info ) : <EOL> event . send ( result , exc_info ) <EOL> return result , exc_info <EOL> def response_from_result ( self , result ) : <EOL> if isinstance ( result , Response ) : <EOL> return result <EOL> headers = None <EOL> if isinstance ( result , tuple ) : <EOL> if len ( result ) == <NUM_LIT:3> : <EOL> status , headers , payload = result <EOL> else : <EOL> status , payload = result <EOL> else : <EOL> payload = result <EOL> status = <NUM_LIT:200> <EOL> if not isinstance ( payload , six . string_types ) : <EOL> raise TypeError ( <EOL> "<STR_LIT>" . format ( payload ) <EOL> ) <EOL> return Response ( <EOL> payload , <EOL> status = status , <EOL> headers = headers , <EOL> ) <EOL> def response_from_exception ( self , exc ) : <EOL> if ( <EOL> isinstance ( exc , self . expected_exceptions ) or <EOL> isinstance ( exc , BadRequest ) <EOL> ) : <EOL> status_code = <NUM_LIT> <EOL> else : <EOL> status_code = <NUM_LIT> <EOL> error_dict = serialize ( exc ) <EOL> payload = u'<STR_LIT>' . format ( ** error_dict ) <EOL> return Response ( <EOL> payload , <EOL> status = status_code , <EOL> ) <EOL> http = HttpRequestHandler . decorator </s>
