A dictionary of the urls to be mocked with this service and the handlers
        that should be called in their place
559292
def urls(self):
        
        url_bases = self._url_module.url_bases
        unformatted_paths = self._url_module.url_paths

        urls = {}
        for url_base in url_bases:
            for url_path, handler in unformatted_paths.items():
                url = url_path.format(url_base)
                urls[url] = handler

        return urls
155124
def to_dict(self):
        
        request_context_dict = {}
        if self.request_context:
            request_context_dict = self.request_context.to_dict()

        json_dict = {"httpMethod": self.http_method,
                     "body": self.body if self.body else None,
                     "resource": self.resource,
                     "requestContext": request_context_dict,
                     "queryStringParameters": dict(self.query_string_params) if self.query_string_params else None,
                     "headers": dict(self.headers) if self.headers else None,
                     "pathParameters": dict(self.path_parameters) if self.path_parameters else None,
                     "stageVariables": dict(self.stage_variables) if self.stage_variables else None,
                     "path": self.path,
                     "isBase64Encoded": self.is_base_64_encoded
                     }

        return json_dict
1132270
def register_url(url, handler, name=None, kwargs=None):
    
    if name is None and kwargs is None:
        app_config.urls.append((url, handler))
        return

    if name is None:
        app_config.urls.append((url, handler, kwargs))
        return

    app_config.urls.append((url, handler, kwargs, name))
794606
function (baseUrl, callback) {
    var self = this;
    var tests = [];

    // Export own request handler examples as test functions.
    for (var method in self.handlers) {
      var handler = self.handlers[method];
      if (!handler.examples) {
        throw (
          'Handler ' + method.toUpperCase() + ' ' + this.path +
            ' does not have examples!'
        );
      }
      handler.examples.forEach(function (example) {
        var test =
          self.testHandlerExample.bind(self, baseUrl, method, handler, example);
        tests.push(test);
      });
    }

    // Don't hang when there are no children.
    var pendingChildren = Object.keys(self.children).length;
    if (pendingChildren === 0) {
      callback(tests);
      return;
    }

    // Export children's request handler test functions recursively.
    var childBaseUrl = url.parse(String(baseUrl));
    childBaseUrl.pathname = normalizePath(self.path, childBaseUrl.pathname);
    childBaseUrl = url.format(childBaseUrl);
    for (var path in self.children) {
      self.children[path].exportAllTests(childBaseUrl, function (childTests) {
        tests = tests.concat(childTests);
        pendingChildren--;
        if (pendingChildren === 0) {
          callback(tests);
        }
      });
    }
  }
425986
def get_mockdata_url(service_name, implementation_name,
                     url, headers):
    

    RESOURCE_ROOT = _mockdata_path_root(service_name, implementation_name)
    file_path = None
    success = False
    start_time = time.time()

    mockdata_delay = getattr(settings, "RESTCLIENTS_MOCKDATA_DELAY", 0.0)
    time.sleep(mockdata_delay)

    for resource_dir in app_resource_dirs:
        logger.debug("Check url %s, service_name: %s, in resource_dir: %s" %
                     (url, service_name, resource_dir))

        response = _load_resource_from_path(resource_dir, service_name,
                                            implementation_name, url, headers)

        if response:
            request_time = time.time() - start_time
            rest_request.send(sender='restclients',
                              url=url,
                              request_time=request_time,
                              hostname=socket.gethostname(),
                              service_name=service_name)
            rest_request_passfail.send(sender='restclients',
                                       url=url,
                                       success=True,
                                       hostname=socket.gethostname(),
                                       service_name=service_name)
            return response

    # If no response has been found in any installed app, return a 404
    logger.info("404 for url %s, path: %s" %
                (url, "resources/%s/%s/%s" %
                 (service_name,
                  implementation_name,
                  convert_to_platform_safe(url))))
    rest_request_passfail.send(sender='restclients',
                               url=url,
                               success=False,
                               hostname=socket.gethostname(),
                               service_name=service_name)
    response = MockHTTP()
    response.status = 404
    response.reason = "Not Found"
    return response
1029555
def execute(self, url, params):
        
        response = requests.get(url, params=params, **self.config.requests_kwargs)

        if 520 <= response.status_code < 530:
            if self.config.handler52x:
                return self.config.handler52x(response, self, url, params)

        response.raise_for_status()

        if not self.config.response_type:
            return response.json()
        else:
            return response.text
707387
def url_paths(self):
        
        unformatted_paths = self._url_module.url_paths

        paths = {}
        for unformatted_path, handler in unformatted_paths.items():
            path = unformatted_path.format("")
            paths[path] = handler

        return paths
195040
def as_dict(self):
        '''
        
        '''
        data = {}
        if settings.JS_CONTEXT_ENABLED:
            for context in RequestContext(self.request):
                for key, value in six.iteritems(context):
                    if settings.JS_CONTEXT and key not in settings.JS_CONTEXT:
                        continue
                    if settings.JS_CONTEXT_EXCLUDE and key in settings.JS_CONTEXT_EXCLUDE:
                        continue
                    handler_name = 'process_%s' % key
                    if hasattr(self, handler_name):
                        handler = getattr(self, handler_name)
                        data[key] = handler(value, data)
                    elif isinstance(value, SERIALIZABLE_TYPES):
                        data[key] = value
        if settings.JS_USER_ENABLED:
            self.handle_user(data)
        return data
1091001
def get(context, request, key=None):
    
    registry_records = api.get_registry_records_by_keyword(key)

    # Prepare batch
    size = req.get_batch_size()
    start = req.get_batch_start()
    batch = api.make_batch(registry_records, size, start)

    return {
        "pagesize": batch.get_pagesize(),
        "next": batch.make_next_url(),
        "previous": batch.make_prev_url(),
        "page": batch.get_pagenumber(),
        "pages": batch.get_numpages(),
        "count": batch.get_sequence_length(),
        "items": [registry_records],
        "url": api.url_for("senaite.jsonapi.v1.registry", key=key),
    }
310141
def http_error_handler(f):
    

    def hrefs_to_resources(hrefs):
        for href in hrefs.replace(',', '').split():
            type, uuid = href.split('/')[-2:]
            yield Resource(type, uuid=uuid)

    def hrefs_list_to_resources(hrefs_list):
        for href in eval(hrefs_list):
            type, uuid = href.split('/')[-2:]
            yield Resource(type, uuid=uuid)

    @wraps(f)
    def wrapper(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except HttpError as e:
            if e.http_status == 404:
                # remove previously created resource
                # from the cache
                self.emit('deleted', self)
                if isinstance(self, Resource):
                    raise ResourceNotFound(resource=self)
                elif isinstance(self, Collection):
                    raise CollectionNotFound(collection=self)
            elif e.http_status == 409:
                # contrail 3.2
                matches = re.match(r'^Delete when children still present: (\[[^]]*\])', e.message)
                if matches:
                    raise ChildrenExists(
                        resources=list(hrefs_list_to_resources(matches.group(1))))
                matches = re.match(r'^Delete when resource still referred: (\[[^]]*\])', e.message)
                if matches:
                    raise BackRefsExists(
                        resources=list(hrefs_list_to_resources(matches.group(1))))
                # contrail 2.21
                matches = re.match(r'^Children (.*) still exist$', e.message)
                if matches:
                    raise ChildrenExists(
                        resources=list(hrefs_to_resources(matches.group(1))))
                matches = re.match(r'^Back-References from (.*) still exist$', e.message)
                if matches:
                    raise BackRefsExists(
                        resources=list(hrefs_to_resources(matches.group(1))))
            raise
    return wrapper
226190
function(req) {
        var args = utils.arg2arr(arguments), index = -1;
        var allHandlers = this._handlers.concat(this._lastHandlers);
        var next = function(error) {
            var item = allHandlers[++index];
            if (item) {
                var matched = false;
                if (utils.isString(item.routeExp)) {
                    matched = req.url.indexOf(item.routeExp) === 0;
                } else if (utils.type(item.routeExp) === 'regexp') {
                    matched = item.routeExp.test(parse(req.url).pathname);
                }
                //
                if (matched) {
                    var clone = args.concat();
                    if (error) { clone.push(error); }
                    item.handler.apply(null, clone);
                }
            }
        };
        args.push(next);
        next();
    }
797109
def lookup(self, request: Request) -> List[Callable[[], Handler]]:
        
        key = request.__class__.__name__
        if key not in self._registry:
            if request.is_command():
                raise ConfigurationException("There is no handler registered for this request")
            elif request.is_event():
                return []  # type: Callable[[] Handler]

        return self._registry[key]
749074
def GetHandlers(self):
    
    handlers = []

    if self.ssl_context:
      handlers.append(urllib2.HTTPSHandler(context=self.ssl_context))

    if self.proxies:
      handlers.append(urllib2.ProxyHandler(self.proxies))

    return handlers
272508
def _init_request_urls(self, api_urls):
        
        if not isinstance(api_urls, (str, list, tuple)):
            raise TypeError('api_urls needs to be string or iterable!')

        if isinstance(api_urls, str):
            api_urls = (api_urls,)

        api_urls = list(api_urls)

        for url in api_urls:
            if not url.startswith('http://') and \
               not url.startswith('https://'):
                raise ValueError(('URL "%s" contains an invalid or missing'
                                 ' scheme' % (url)))

        return list(api_urls)
586840
def _generate_handler_wrapper(api_name, api_spec, endpoint, handler_func, error_callback, global_decorator):
    """"""

    # Decorate the handler function, if Swagger spec tells us to
    if endpoint.decorate_server:
        endpoint_decorator = get_function(endpoint.decorate_server)
        handler_func = endpoint_decorator(handler_func)

    @wraps(handler_func)
    def handler_wrapper(**path_params):
        log.info(" ")
        log.info(" ")
        log.info("=> INCOMING REQUEST %s %s -> %s" %
                 (endpoint.method, endpoint.path, handler_func.__name__))
        log.info(" ")
        log.info(" ")

        # Get caller's pym-call-id or generate one
        call_id = request.headers.get('PymCallID', None)
        if not call_id:
            call_id = str(uuid.uuid4())
        stack.top.call_id = call_id

        # Append current server to call path, or start one
        call_path = request.headers.get('PymCallPath', None)
        if call_path:
            call_path = "%s.%s" % (call_path, api_name)
        else:
            call_path = api_name
        stack.top.call_path = call_path

        if endpoint.param_in_body or endpoint.param_in_query:
            # Turn the flask request into something bravado-core can process...
            try:
                req = FlaskRequestProxy(request, endpoint.param_in_body)
            except BadRequest:
                ee = error_callback(ValidationError("Cannot parse json data: have you set 'Content-Type' to 'application/json'?"))
                return _responsify(api_spec, ee, 400)

            try:
                # Note: unmarshall validates parameters but does not fail
                # if extra unknown parameters are submitted
                parameters = unmarshal_request(req, endpoint.operation)
                # Example of parameters: {'body': RegisterCredentials()}
            except jsonschema.exceptions.ValidationError as e:
                ee = error_callback(ValidationError(str(e)))
                return _responsify(api_spec, ee, 400)

        # Call the endpoint, with proper parameters depending on whether
        # parameters are in body, query or url
        args = []
        kwargs = {}

        if endpoint.param_in_path:
            kwargs = path_params

        if endpoint.param_in_body:
            # Remove the parameters already defined in path_params
            for k in list(path_params.keys()):
                del parameters[k]
            lst = list(parameters.values())
            assert len(lst) == 1
            args.append(lst[0])

        if endpoint.param_in_query:
            kwargs.update(parameters)

        result = handler_func(*args, **kwargs)

        if not result:
            e = error_callback(PyMacaronCoreException("Have nothing to send in response"))
            return _responsify(api_spec, e, 500)

        # Did we get the expected response?
        if endpoint.produces_html:
            if type(result) is not tuple:
                e = error_callback(PyMacaronCoreException("Method %s should return %s but returned %s" %
                                                          (endpoint.handler_server, endpoint.produces, type(result))))
                return _responsify(api_spec, e, 500)

            # Return an html page
            return result

        elif endpoint.produces_json:
            if not hasattr(result, '__module__') or not hasattr(result, '__class__'):
                e = error_callback(PyMacaronCoreException("Method %s did not return a class instance but a %s" %
                                                          (endpoint.handler_server, type(result))))
                return _responsify(api_spec, e, 500)

            # If it's already a flask Response, just pass it through.
            # Errors in particular may be either passed back as flask Responses, or
            # raised as exceptions to be caught and formatted by the error_callback
            result_type = result.__module__ + "." + result.__class__.__name__
            if result_type == 'flask.wrappers.Response':
                return result

            # We may have got a pymacaron Error instance, in which case
            # it has a http_reply() method...
            if hasattr(result, 'http_reply'):
                # Let's transform this Error into a flask Response
                log.info("Looks like a pymacaron error instance - calling .http_reply()")
                return result.http_reply()

            # Otherwise, assume no error occured and make a flask Response out of
            # the result.

            # TODO: check that result is an instance of a model expected as response from this endpoint
            result_json = api_spec.model_to_json(result)

            # Send a Flask Response with code 200 and result_json
            r = jsonify(result_json)
            r.status_code = 200
            return r

    handler_wrapper = cross_origin(headers=['Content-Type', 'Authorization'])(handler_wrapper)

    # And encapsulate all in a global decorator, if given one
    if global_decorator:
        handler_wrapper = global_decorator(handler_wrapper)

    return handler_wrapper
250114
def post_mockdata_url(service_name, implementation_name,
                      url, headers, body,
                      dir_base=dirname(__file__)):
    
    # Currently this post method does not return a response body
    response = MockHTTP()
    if body is not None:
        if "dispatch" in url:
            response.status = 200
        else:
            response.status = 201
        response.headers = {"X-Data-Source": service_name + " file mock data",
                            "Content-Type": headers['Content-Type']}
    else:
        response.status = 400
        response.data = "Bad Request: no POST body"
    return response
545311
def urls(self):
        
        urls = []

        for url_name in sorted(self.resources.keys()):

            resource = self.resources[url_name]
            urls.append(resource.as_url(
                api=self,
                name_prefix='-'.join(
                    (self.prefix, self.str_version)).strip('-'),
                url_prefix=self.str_version
            ))

        return patterns(self.prefix, *urls)