An AWS Lambda function which parses specific API Gateway input into a
        WSGI request, feeds it to our WSGI app, procceses the response, and returns
        that back to the API Gateway.
196195
def handler(self, event, context):
        
        settings = self.settings

        # If in DEBUG mode, log all raw incoming events.
        if settings.DEBUG:
            logger.debug('Zappa Event: {}'.format(event))

        # Set any API Gateway defined Stage Variables
        # as env vars
        if event.get('stageVariables'):
            for key in event['stageVariables'].keys():
                os.environ[str(key)] = event['stageVariables'][key]

        # This is the result of a keep alive, recertify
        # or scheduled event.
        if event.get('detail-type') == u'Scheduled Event':

            whole_function = event['resources'][0].split('/')[-1].split('-')[-1]

            # This is a scheduled function.
            if '.' in whole_function:
                app_function = self.import_module_and_get_function(whole_function)

                # Execute the function!
                return self.run_function(app_function, event, context)

            # Else, let this execute as it were.

        # This is a direct command invocation.
        elif event.get('command', None):

            whole_function = event['command']
            app_function = self.import_module_and_get_function(whole_function)
            result = self.run_function(app_function, event, context)
            print("Result of %s:" % whole_function)
            print(result)
            return result

        # This is a direct, raw python invocation.
        # It's _extremely_ important we don't allow this event source
        # to be overridden by unsanitized, non-admin user input.
        elif event.get('raw_command', None):

            raw_command = event['raw_command']
            exec(raw_command)
            return

        # This is a Django management command invocation.
        elif event.get('manage', None):

            from django.core import management

            try:  # Support both for tests
                from zappa.ext.django_zappa import get_django_wsgi
            except ImportError as e:  # pragma: no cover
                from django_zappa_app import get_django_wsgi

            # Get the Django WSGI app from our extension
            # We don't actually need the function,
            # but we do need to do all of the required setup for it.
            app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS)

            # Couldn't figure out how to get the value into stdout with StringIO..
            # Read the log for now. :[]
            management.call_command(*event['manage'].split(' '))
            return {}

        # This is an AWS-event triggered invocation.
        elif event.get('Records', None):

            records = event.get('Records')
            result = None
            whole_function = self.get_function_for_aws_event(records[0])
            if whole_function:
                app_function = self.import_module_and_get_function(whole_function)
                result = self.run_function(app_function, event, context)
                logger.debug(result)
            else:
                logger.error("Cannot find a function to process the triggered event.")
            return result

        # this is an AWS-event triggered from Lex bot's intent
        elif event.get('bot'):
            result = None
            whole_function = self.get_function_from_bot_intent_trigger(event)
            if whole_function:
                app_function = self.import_module_and_get_function(whole_function)
                result = self.run_function(app_function, event, context)
                logger.debug(result)
            else:
                logger.error("Cannot find a function to process the triggered event.")
            return result

        # This is an API Gateway authorizer event
        elif event.get('type') == u'TOKEN':
            whole_function = self.settings.AUTHORIZER_FUNCTION
            if whole_function:
                app_function = self.import_module_and_get_function(whole_function)
                policy = self.run_function(app_function, event, context)
                return policy
            else:
                logger.error("Cannot find a function to process the authorization request.")
                raise Exception('Unauthorized')

        # This is an AWS Cognito Trigger Event
        elif event.get('triggerSource', None):
            triggerSource = event.get('triggerSource')
            whole_function = self.get_function_for_cognito_trigger(triggerSource)
            result = event
            if whole_function:
                app_function = self.import_module_and_get_function(whole_function)
                result = self.run_function(app_function, event, context)
                logger.debug(result)
            else:
                logger.error("Cannot find a function to handle cognito trigger {}".format(triggerSource))
            return result

        # Normal web app flow
        try:
            # Timing
            time_start = datetime.datetime.now()

            # This is a normal HTTP request
            if event.get('httpMethod', None):
                script_name = ''
                is_elb_context = False
                headers = merge_headers(event)
                if event.get('requestContext', None) and event['requestContext'].get('elb', None):
                    # Related: https://github.com/Miserlou/Zappa/issues/1715
                    # inputs/outputs for lambda loadbalancer
                    # https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html
                    is_elb_context = True
                    # host is lower-case when forwarded from ELB
                    host = headers.get('host')
                    # TODO: pathParameters is a first-class citizen in apigateway but not available without
                    # some parsing work for ELB (is this parameter used for anything?)
                    event['pathParameters'] = ''
                else:
                    if headers:
                        host = headers.get('Host')
                    else:
                        host = None
                    logger.debug('host found: [{}]'.format(host))

                    if host:
                        if 'amazonaws.com' in host:
                            logger.debug('amazonaws found in host')
                            # The path provided in th event doesn't include the
                            # stage, so we must tell Flask to include the API
                            # stage in the url it calculates. See https://github.com/Miserlou/Zappa/issues/1014
                            script_name = '/' + settings.API_STAGE
                    else:
                        # This is a test request sent from the AWS console
                        if settings.DOMAIN:
                            # Assume the requests received will be on the specified
                            # domain. No special handling is required
                            pass
                        else:
                            # Assume the requests received will be to the
                            # amazonaws.com endpoint, so tell Flask to include the
                            # API stage
                            script_name = '/' + settings.API_STAGE

                base_path = getattr(settings, 'BASE_PATH', None)

                # Create the environment for WSGI and handle the request
                environ = create_wsgi_request(
                    event,
                    script_name=script_name,
                    base_path=base_path,
                    trailing_slash=self.trailing_slash,
                    binary_support=settings.BINARY_SUPPORT,
                    context_header_mappings=settings.CONTEXT_HEADER_MAPPINGS
                )

                # We are always on https on Lambda, so tell our wsgi app that.
                environ['HTTPS'] = 'on'
                environ['wsgi.url_scheme'] = 'https'
                environ['lambda.context'] = context
                environ['lambda.event'] = event

                # Execute the application
                with Response.from_app(self.wsgi_app, environ) as response:
                    # This is the object we're going to return.
                    # Pack the WSGI response into our special dictionary.
                    zappa_returndict = dict()

                    # Issue #1715: ALB support. ALB responses must always include
                    # base64 encoding and status description
                    if is_elb_context:
                        zappa_returndict.setdefault('isBase64Encoded', False)
                        zappa_returndict.setdefault('statusDescription', response.status)

                    if response.data:
                        if settings.BINARY_SUPPORT:
                            if not response.mimetype.startswith("text/") \
                                or response.mimetype != "application/json":
                                    zappa_returndict['body'] = base64.b64encode(response.data).decode('utf-8')
                                    zappa_returndict["isBase64Encoded"] = True
                            else:
                                zappa_returndict['body'] = response.data
                        else:
                            zappa_returndict['body'] = response.get_data(as_text=True)

                    zappa_returndict['statusCode'] = response.status_code
                    if 'headers' in event:
                        zappa_returndict['headers'] = {}
                        for key, value in response.headers:
                            zappa_returndict['headers'][key] = value
                    if 'multiValueHeaders' in event:
                        zappa_returndict['multiValueHeaders'] = {}
                        for key, value in response.headers:
                            zappa_returndict['multiValueHeaders'][key] = response.headers.getlist(key)

                    # Calculate the total response time,
                    # and log it in the Common Log format.
                    time_end = datetime.datetime.now()
                    delta = time_end - time_start
                    response_time_ms = delta.total_seconds() * 1000
                    response.content = response.data
                    common_log(environ, response, response_time=response_time_ms)

                    return zappa_returndict
        except Exception as e:  # pragma: no cover
            # Print statements are visible in the logs either way
            print(e)
            exc_info = sys.exc_info()
            message = ('An uncaught exception happened while servicing this request. '
                       'You can investigate this with the `zappa tail` command.')

            # If we didn't even build an app_module, just raise.
            if not settings.DJANGO_SETTINGS:
                try:
                    self.app_module
                except NameError as ne:
                    message = 'Failed to import module: {}'.format(ne.message)

            # Call exception handler for unhandled exceptions
            exception_handler = self.settings.EXCEPTION_HANDLER
            self._process_exception(exception_handler=exception_handler,
                                    event=event, context=context, exception=e)

            # Return this unspecified exception as a 500, using template that API Gateway expects.
            content = collections.OrderedDict()
            content['statusCode'] = 500
            body = {'message': message}
            if settings.DEBUG:  # only include traceback if debug is on.
                body['traceback'] = traceback.format_exception(*exc_info)  # traceback as a list for readability.
            content['body'] = json.dumps(str(body), sort_keys=True, indent=4)
            return content
723940
function getChoices() {
    // First, retrieve possible values for the api-identifiers parameter
    return {
      httpMethod: plugin.httpMethods,
      auth: [
        { value: 'none', name: 'None' },
        { value: 'aws_iam', name: 'AWS authorization' }
      ],
      integration: [
        { value: 'lambda', name: 'Lambda function' },
        { value: 'lambda-proxy', name: 'Lambda function with proxy integration' },
        { value: 'http', name: 'Existing HTTP endpoint' },
        { value: 'mock', name: 'Mock' },
        { value: 'aws-service', name: 'AWS service' }
      ],
      apis: () => {
        return plugin.loadApis()
        .then(apis => {
          return _.map(apis, api => {
            return {
              value: api.getIdentifier(),
              name: icli.format.info(api.getIdentifier()) + (api.spec.info && api.spec.info.title ? ' - ' + api.spec.info.title : '')
            };
          });
        });
      },
      roleOrigins: () => {
        if (plugin.myrmex.isPluginRegistered('iam')) {
          const choices = [];
          choices.push({
            value: 'myrmex',
            name: 'Select a role managed by the plugin @myrmex/iam'
          });
          choices.push({
            value: 'aws',
            name: 'Select a role in your AWS account'
          });
          choices.push({
            value: '',
            name: 'Enter the value manually'
          });
          return choices;
        }
        return [];
      },
      roles: (answers) => {
        if (answers && answers.roleOrigin === 'aws') {
          return plugin.myrmex.call('iam:getAWSRoles', [])
          .then(roles => {
            const eligibleRoles = [];
            _.forEach(roles, role => {
              const trustRelationship = JSON.parse(decodeURIComponent(role.AssumeRolePolicyDocument))
              if (_.find(trustRelationship.Statement, (o) => { return o.Principal.Service === 'apigateway.amazonaws.com'; })) {
                eligibleRoles.push({
                  value: role.RoleName,
                  name: icli.format.info(role.RoleName)
                });
              }
            });
            return eligibleRoles;
          });
        } else {
          return plugin.myrmex.call('iam:getRoles', [])
          .then(roles => {
            const eligibleRoles = [];
            _.forEach(roles, role => {
              if (_.find(role.config['trust-relationship'].Statement, (o) => { return o.Principal.Service === 'apigateway.amazonaws.com'; })) {
                eligibleRoles.push({
                  value: role.getName(),
                  name: icli.format.info(role.getName())
                });
              }
            });
            return eligibleRoles;
          });
        }
      }
    };
  }
239616
def application(environ, start_response):
    """"""
    # the environment variable CONTENT_LENGTH may be empty or missing
    try:
        request_body_size = int(environ.get('CONTENT_LENGTH', 0))
    except ValueError:
        request_body_size = 0

    # When the method is POST the query string will be sent
    # in the HTTP request body which is passed by the WSGI server
    # in the file like wsgi.input environment variable.
    if request_body_size > 0:
        request_body = environ['wsgi.input'].read(request_body_size)
    else:
        request_body = environ['wsgi.input'].read()
    form = cgi.parse_qs(request_body)

    status = '200 OK'
    start_response(status, get_response_headers())
    for output in checklink(form=form, env=environ):
        yield output
33699
def _parse_lambda_output(lambda_output, binary_types, flask_request):
        
        json_output = json.loads(lambda_output)

        if not isinstance(json_output, dict):
            raise TypeError("Lambda returned %{s} instead of dict", type(json_output))

        status_code = json_output.get("statusCode") or 200
        headers = CaseInsensitiveDict(json_output.get("headers") or {})
        body = json_output.get("body") or "no data"
        is_base_64_encoded = json_output.get("isBase64Encoded") or False

        try:
            status_code = int(status_code)
            if status_code <= 0:
                raise ValueError
        except ValueError:
            message = "statusCode must be a positive int"
            LOG.error(message)
            raise TypeError(message)

        # If the customer doesn't define Content-Type default to application/json
        if "Content-Type" not in headers:
            LOG.info("No Content-Type given. Defaulting to 'application/json'.")
            headers["Content-Type"] = "application/json"

        if LocalApigwService._should_base64_decode_body(binary_types, flask_request, headers, is_base_64_encoded):
            body = base64.b64decode(body)

        return status_code, headers, body
497326
def ping(awsclient, function_name, alias_name=ALIAS_NAME, version=None):
    
    log.debug('sending ping to lambda function: %s', function_name)
    payload = '{"ramuda_action": "ping"}'  # default to ping event
    # reuse invoke
    return invoke(awsclient, function_name, payload, invocation_type=None,
                  alias_name=alias_name, version=version)
697002
def response_middleware(api=None):
    """"""
    def decorator(middleware_method):
        apply_to_api = hug.API(api) if api else hug.api.from_object(middleware_method)

        class MiddlewareRouter(object):
            __slots__ = ()

            def process_response(self, request, response, resource, req_succeeded):
                return middleware_method(request, response, resource)

        apply_to_api.http.add_middleware(MiddlewareRouter())
        return middleware_method
    return decorator
228620
def generate_api_gateway():
    """"""
    logger.debug("[#] Setting up the API Gateway")
    client = boto3.client('apigateway', region_name=PRIMARY_REGION)
    matches = [x for x in client.get_rest_apis().get('items', list())
               if x['name'] == API_GATEWAY]
    if len(matches) > 0:
        logger.debug("[#] API Gateway already setup")
        return matches.pop()

    response = client.create_rest_api(
        name=API_GATEWAY,
        description='REST-API to power the Blockade service'
    )
    logger.info("[#] Successfully setup the API Gateway")

    return response
971328
def make_wsgi_app(matching, not_found_app=not_found_app):
    
    def wsgi_app(environ, start_response):
        environ['matcha.matching'] = matching
        try:
            matched_case, matched_dict = matching(environ)
        except NotMatched:
            return not_found_app(environ, start_response)
        else:
            environ['matcha.matched_dict'] = matched_dict
            return matched_case(environ, start_response)
    return wsgi_app
836259
def _handle_POST(self, env, start_response):
        
        input = env['wsgi.input']
        data = input.read( int(env['CONTENT_LENGTH']) )
        mimeType = "text/xml"
        if self.encoding is not None:
            mimeType = 'text/xml; charset="%s"' % self.encoding

        request = None
        resource = self.delegate or self
        chain = self.factory.newInstance()
        try:
            pyobj = chain.processRequest(data, request=request, resource=resource)
        except Exception, ex:
            start_response("500 ERROR", [('Content-Type',mimeType)])
            return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]

        try:
            soap = chain.processResponse(pyobj, request=request, resource=resource)
        except Exception, ex:
            start_response("500 ERROR", [('Content-Type',mimeType)])
            return [fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
        
        start_response("200 OK", [('Content-Type',mimeType)])
        return [soap]
320380
def make_wsgi_app(registry=REGISTRY):
    """"""

    def prometheus_app(environ, start_response):
        params = parse_qs(environ.get('QUERY_STRING', ''))
        r = registry
        encoder, content_type = choose_encoder(environ.get('HTTP_ACCEPT'))
        if 'name[]' in params:
            r = r.restricted_registry(params['name[]'])
        output = encoder(r)

        status = str('200 OK')
        headers = [(str('Content-type'), content_type)]
        start_response(status, headers)
        return [output]

    return prometheus_app
116311
def wsgi_app(self, request):
        

        try:
            if request.method != 'POST':
                abort(400)

            try:
                # Python 2.7 compatibility
                data = request.data
                if isinstance(data, str):
                    body = json.loads(data)
                else:
                    body = json.loads(data.decode('utf-8'))
            except ValueError:
                abort(400)

            if self.validate:
                valid_cert = util.validate_request_certificate(
                    request.headers, request.data)

                valid_ts = util.validate_request_timestamp(body)

                if not valid_cert or not valid_ts:
                    log.error('failed to validate request')
                    abort(403)

            resp_obj = self.alexa.dispatch_request(body)
            return Response(response=json.dumps(resp_obj, indent=4),
                            status=200,
                            mimetype='application/json')

        except HTTPException as exc:
            log.exception('Failed to handle request')
            return exc
964770
def _run_lambda_function(event, context, app, config):  # pragma: no cover
    """"""
    args = event.get('args', [])
    kwargs = event.get('kwargs', {})

    # first attempt to invoke the function passing the lambda event and context
    try:
        ret = app(*args, event=event, context=context, **kwargs)
    except TypeError:
        # try again without passing the event and context
        ret = app(*args, **kwargs)
    return ret
521621
def get_response(wsgi_request):
    '''
        
    '''
    service_start_time = datetime.now()
    # Get the view / handler for this request
    view, args, kwargs = resolve(wsgi_request.path_info)

    kwargs.update({"request": wsgi_request})

    # Let the view do his task.
    try:
        resp = view(*args, **kwargs)
    except Exception as exc:
        resp = HttpResponseServerError(content=exc.message)

    headers = dict(resp._headers.values())
    # Convert HTTP response into simple dict type.
    d_resp = {"status_code": resp.status_code, "reason_phrase": resp.reason_phrase,
              "headers": headers}
    try:
        d_resp.update({"body": resp.content})
    except ContentNotRenderedError:
        resp.render()
        d_resp.update({"body": resp.content})

    # Check if we need to send across the duration header.
    if _settings.ADD_DURATION_HEADER:
        d_resp['headers'].update({_settings.DURATION_HEADER_NAME: (datetime.now() - service_start_time).seconds})

    return d_resp
24775
def definition
      {
        method_logical_id => {
          type: "AWS::ApiGateway::Method",
          properties: {
            resource_id: "!Ref #{resource_id}",
            rest_api_id: "!Ref #{RestApi.logical_id}",
            http_method: @route.method,
            request_parameters: {},
            authorization_type: authorization_type,
            integration: {
              integration_http_method: "POST",
              type: "AWS_PROXY",
              uri: "!Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${{namespace}LambdaFunction.Arn}/invocations"
            },
            method_responses: []
          }
        }
      }
    end
989172
def create_api_gateway_routes(  self,
                                    lambda_arn,
                                    api_name=None,
                                    api_key_required=False,
                                    authorization_type='NONE',
                                    authorizer=None,
                                    cors_options=None,
                                    description=None,
                                    endpoint_configuration=None
                                ):
        

        restapi = troposphere.apigateway.RestApi('Api')
        restapi.Name = api_name or lambda_arn.split(':')[-1]
        if not description:
            description = 'Created automatically by Zappa.'
        restapi.Description = description
        endpoint_configuration = [] if endpoint_configuration is None else endpoint_configuration
        if self.boto_session.region_name == "us-gov-west-1":
            endpoint_configuration.append("REGIONAL")
        if endpoint_configuration:
            endpoint = troposphere.apigateway.EndpointConfiguration()
            endpoint.Types = list(set(endpoint_configuration))
            restapi.EndpointConfiguration = endpoint
        if self.apigateway_policy:
            restapi.Policy = json.loads(self.apigateway_policy)
        self.cf_template.add_resource(restapi)

        root_id = troposphere.GetAtt(restapi, 'RootResourceId')
        invocation_prefix = "aws" if self.boto_session.region_name != "us-gov-west-1" else "aws-us-gov"
        invocations_uri = 'arn:' + invocation_prefix + ':apigateway:' + self.boto_session.region_name + ':lambda:path/2015-03-31/functions/' + lambda_arn + '/invocations'

        ##
        # The Resources
        ##
        authorizer_resource = None
        if authorizer:
            authorizer_lambda_arn = authorizer.get('arn', lambda_arn)
            lambda_uri = 'arn:{invocation_prefix}:apigateway:{region_name}:lambda:path/2015-03-31/functions/{lambda_arn}/invocations'.format(
                invocation_prefix=invocation_prefix,
                region_name=self.boto_session.region_name,
                lambda_arn=authorizer_lambda_arn
            )
            authorizer_resource = self.create_authorizer(
                restapi, lambda_uri, authorizer
            )

        self.create_and_setup_methods(  restapi,
                                        root_id,
                                        api_key_required,
                                        invocations_uri,
                                        authorization_type,
                                        authorizer_resource,
                                        0
                                        )

        if cors_options:
            self.create_and_setup_cors( restapi,
                                        root_id,
                                        invocations_uri,
                                        0,
                                        cors_options
                                    )

        resource = troposphere.apigateway.Resource('ResourceAnyPathSlashed')
        self.cf_api_resources.append(resource.title)
        resource.RestApiId = troposphere.Ref(restapi)
        resource.ParentId = root_id
        resource.PathPart = "{proxy+}"
        self.cf_template.add_resource(resource)

        self.create_and_setup_methods(  restapi,
                                        resource,
                                        api_key_required,
                                        invocations_uri,
                                        authorization_type,
                                        authorizer_resource,
                                        1
                                    )  # pragma: no cover

        if cors_options:
            self.create_and_setup_cors( restapi,
                                        resource,
                                        invocations_uri,
                                        1,
                                        cors_options
                                    )  # pragma: no cover
        return restapi
1170559
def lambda_handler(event, context):
    ''''''
    raw_kpl_records = event['records']
    output = [process_kpl_record(kpl_record) for kpl_record in raw_kpl_records]

    # Print number of successful and failed records.
    success_count = sum(1 for record in output if record['result'] == 'Ok')
    failure_count = sum(1 for record in output if record['result'] == 'ProcessingFailed')
    print('Processing completed.  Successful records: {0}, Failed records: {1}.'.format(success_count, failure_count))

    return {'records': output}
337497
def wsgi_app(self, environ, start_response):
        """"""
        @_LOCAL_MANAGER.middleware
        def _wrapped_app(environ, start_response):
            request = Request(environ)
            setattr(_local, _CURRENT_REQUEST_KEY, request)
            response = self._dispatch_request(request)
            return response(environ, start_response)
        return _wrapped_app(environ, start_response)