Attempts to insert the ScoutApm middleware as the first middleware
        (first on incoming requests, last on outgoing responses).
973241
def install_middleware(self):
        
        from django.conf import settings

        # If MIDDLEWARE is set, update that, with handling of tuple vs array forms
        if getattr(settings, "MIDDLEWARE", None) is not None:
            if isinstance(settings.MIDDLEWARE, tuple):
                settings.MIDDLEWARE = (
                    ("scout_apm.django.middleware.MiddlewareTimingMiddleware",)
                    + settings.MIDDLEWARE
                    + ("scout_apm.django.middleware.ViewTimingMiddleware",)
                )
            else:
                settings.MIDDLEWARE.insert(
                    0, "scout_apm.django.middleware.MiddlewareTimingMiddleware"
                )
                settings.MIDDLEWARE.append(
                    "scout_apm.django.middleware.ViewTimingMiddleware"
                )

        # Otherwise, we're doing old style middleware, do the same thing with
        # the same handling of tuple vs array forms
        else:
            if isinstance(settings.MIDDLEWARE_CLASSES, tuple):
                settings.MIDDLEWARE_CLASSES = (
                    ("scout_apm.django.middleware.OldStyleMiddlewareTimingMiddleware",)
                    + settings.MIDDLEWARE_CLASSES
                    + ("scout_apm.django.middleware.OldStyleViewMiddleware",)
                )
            else:
                settings.MIDDLEWARE_CLASSES.insert(
                    0, "scout_apm.django.middleware.OldStyleMiddlewareTimingMiddleware"
                )
                settings.MIDDLEWARE_CLASSES.append(
                    "scout_apm.django.middleware.OldStyleViewMiddleware"
                )
1209570
function createMiddleware(router, validator) {
  /**
   * Checks request and response against a swagger spec
   * Uses the usual koa context attributes
   * Uses the koa-bodyparser context attribute
   * Sets a new context attribute: {object} parameter
   */
  return function* middleware(next) {
    // Routing matches
    try {
      var routeMatch = match.path(router, this.path);
    } catch(e) {
      // TODO: let an option before doing that, strict mode throws the error
      yield next;
      return false;
    }
    this.pathParam = routeMatch.param; // Add the path's params to the context
    var methodDef = match.method(routeMatch.def, this.method);


    // Parameters check & assign
    this.parameter = check.parameters(validator,
      methodDef.parameters || [], this);

    // Let the implementation happen
    yield next;

    // Response check
    var statusDef = match.status(methodDef.responses || {}, this.status);
    check.sentHeaders(validator, statusDef.headers || {}, this.sentHeaders);
    if(statusDef.schema) {
      check.body(validator, statusDef.schema, yield this.body);
    }
  };
}
64950
def insert_before_each(middleware, *args, &block)
      self.stack = stack.reduce([]) do |carry, item|
        carry.push([middleware, args, block], item)
      end
    end
95415
def insert(index, middleware, *args, &block)
      index = self.index(index) unless index.is_a?(Integer)
      raise "no such middleware to insert before: #{index.inspect}" unless index
      stack.insert(index, [middleware, args, block])
    end
1149966
def prepare_middleware(&context_definition)
      last_middleware = AllImportantMiddleware.new(&context_definition)
      Context.middlewares.inject(last_middleware) do |previous_middleware, middleware|
        middleware.new(previous_middleware)
      end.call(self)
    end
284817
def start(self):
        
        if self._http_last_send is not None:
            raise RuntimeError('HttpMock has already been started')

        # 1) save request.Session.send in self._last_send
        # 2) replace request.Session.send with MockerCore send function
        super(HttpMock, self).start()

        # 3) save MockerCore send function in self._http_last_send
        # 4) replace request.Session.send with HttpMock send function
        self._patch_last_send()
573636
function compose(middlewares, options = {}) {
  const { beforeRunMiddleware } = options;// before invoking the middleware, check whether can be run

  // all middleware should be function
  if (!Array.isArray(middlewares)) middlewares = [middlewares];
  for (const mw of middlewares) {
    if (typeof mw !== 'function') throw new TypeError('middleware should be a function');
  }

  return function ComposedMiddleware(req, resp, next) {
    let doRunMiddleware;

    let lastIndex = -1;// last run middleware index
    const runMiddleware = (index) => {
      if (lastIndex >= index) {
        return Promise.reject(new Error('next() called multiple times'));
      }
      lastIndex = index;

      const middleware = middlewares[index];
      if (middleware && beforeRunMiddleware) {
        return Promise.resolve(beforeRunMiddleware(middleware, req, resp)).then((canRun) => {
          if (!canRun) return runMiddleware(index + 1);
          else return doRunMiddleware(index);
        });
      }

      return doRunMiddleware(index);
    };

    doRunMiddleware = (index) => {
      let middleware = middlewares[index];
      const nextIndex = index + 1;

      let runNextMiddleware = noop;
      if (!middleware) {
        if (next) middleware = next;
      } else if (middlewares[nextIndex] || next) {
        runNextMiddleware = () => runMiddleware(nextIndex);
      }

      try {
        let result;
        if (middleware) result = middleware.call(this, req, resp, runNextMiddleware);
        return Promise.resolve(result);
      } catch (e) {
        return Promise.reject(e);
      }
    };

    return runMiddleware(0);
  };
}
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
219788
function nextRequest() {
		// If there are no more middleware,
		// then resolve the middleware resolution
		if ( middleware.index == middleware.names.length ) {
			middleware.resolution.resolve();
		}

		// Attempt to invoke the next middleware
		middleware.next();
	}
850240
def pre_request(self):
        
        middleware = sort_by_priority(self)
        return tuple(m.pre_request for m in middleware if hasattr(m, 'pre_request'))
1029272
def make_middleware(app=None, *args, **kw):
    
    app = RaptorizeMiddleware(app, *args, **kw)
    return app
194079
def _try_trigger_before_first_request_funcs(self):  # pylint: disable=C0103
        """"""
        if self._after_first_request_handled:
            return
        else:
            with self._before_first_request_lock:
                if self._after_first_request_handled:
                    return
                for func in self._before_first_request_funcs:
                    func()
                self._after_first_request_handled = True
284992
def dispatch(self, request, *args, **kwargs):
        """"""
        self.request = DownstreamRequest(request)
        self.args = args
        self.kwargs = kwargs

        self._verify_config()

        self.middleware = MiddlewareSet(self.proxy_middleware)

        return self.proxy()
680754
def process_request(self, request):
        """"""
        batcher = PrioritizedBatcher.global_instance()
        if batcher.is_started:
            # This can happen in old-style middleware if consequent middleware
            # raises exception and thus `process_response` is not called.
            # Described under 3rd point of differences:
            # https://docs.djangoproject.com/en/1.11/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware
            batcher.rollback()
            logger.warning(
                "Uncommited batcher transaction from previous request was rollbacked."
            )

        batcher.start()
1063825
function mockResponse (req, res, next) {
    if (util.isSwaggerRequest(req) && !isDisabled()) {
      let response;

      // Is there already a statusCode? (perhaps set by third-party middleware)
      if (res.statusCode && req.swagger.operation.responses[res.statusCode]) {
        util.debug("Using %s response for %s %s", res.statusCode, req.method, req.path);
        response = req.swagger.operation.responses[res.statusCode];
      }
      else {
        // Use the first response with a 2XX or 3XX code (or "default")
        let responses = util.getResponsesBetween(req.swagger.operation, 200, 399);

        if (responses.length > 0) {
          response = responses[0].api;

          // Set the response status code
          if (_.isNumber(responses[0].code)) {
            util.debug("Using %s response for %s %s", responses[0].code, req.method, req.path);
            res.status(responses[0].code);
          }
          else {
            if (req.method === "POST" || req.method === "PUT") {
              res.status(201);
            }
            else if (req.method === "DELETE" && !responses[0].api.schema) {
              res.status(204);
            }
            else {
              res.status(200);
            }
            util.debug("Using %s (%d) response for %s %s", responses[0].code, res.statusCode, req.method, req.path);
          }
        }
        else {
          // There is no response with a 2XX or 3XX code, so just use the first one
          let keys = Object.keys(req.swagger.operation.responses);
          util.debug("Using %s response for %s %s", keys[0], req.method, req.path);
          response = req.swagger.operation.responses[keys[0]];
          res.status(parseInt(keys[0]));
        }
      }

      // The rest of the Mock middleware will use this ResponseMetadata object
      res.swagger = new SemanticResponse(response, req.swagger.path);
    }

    next();
  }
503236
function ClientRequest(client, opts, endpoint, head, body, date, callback, middlewares) {
    this.client = client;
    this.opts = opts;
    this.endpoint = endpoint;
    this.head = head;
    this.body = body;
    this.date = date || Date;
    this.callback = callback;
    this.id = uuid.v4();
    this.isCanceled = false;
    this.state = ClientRequestStates.initialized;
    this.timestamp = this.date.now();
    this.middlewareStack = new middleware.MiddlewareStack(middlewares || []);
}
968211
function middlewareFunction (req,res,next){

  return ipToLocation(req.ip)
    .then(function (location) {
      req.location = location;
      next();
    })
    .catch(function (error) {
      req.locationError = error;
      next();
    })

}