Glances API RESTful implementation.

        Return the JSON representation of all the plugins limits
        HTTP/200 if OK
        HTTP/400 if plugin is not found
        HTTP/404 if others error
551296
def _api_all_limits(self):
        
        response.content_type = 'application/json; charset=utf-8'

        try:
            # Get the JSON value of the stat limits
            limits = json.dumps(self.stats.getAllLimitsAsDict())
        except Exception as e:
            abort(404, "Cannot get limits (%s)" % (str(e)))
        return limits
832059
def __is_json_error(self, status, headers):
    
    content_header = headers.get('content-type', '')
    content_type, unused_params = cgi.parse_header(content_header)
    return (status.startswith('400') and
            content_type.lower() in _ALL_JSON_CONTENT_TYPES)
477921
def _rest_request_to_json(self, address, object_path, service_name, requests_config, tags, *args, **kwargs):
        
        response = self._rest_request(address, object_path, service_name, requests_config, tags, *args, **kwargs)

        try:
            response_json = response.json()

        except JSONDecodeError as e:
            self.service_check(
                service_name,
                AgentCheck.CRITICAL,
                tags=['url:%s' % self._get_url_base(address)] + tags,
                message='JSON Parse failed: {0}'.format(e),
            )
            raise

        return response_json
135685
def fetch_json(self, method, url, data=None, expected_status_code=None):
        
        return self.fetch(method, url, data, expected_status_code).json()
707912
def json_response(data, status=200, serializer=None):
    
    return HttpResponse(json.dumps(data, default=serializer),
                        status=status,
                        content_type='application/json; charset=UTF-8')
272885
def overloaded(self, client_address):
        
        body = {
            'status': False,
            'indexing': False,
            'lastblock': -1,
            'error': 'overloaded',
            'http_status': 429
        }
        body_str = json.dumps(body)

        resp = 'HTTP/1.0 200 OK\r\nServer: BaseHTTP/0.3 Python/2.7.14+\r\nContent-type: text/xml\r\nContent-length: {}\r\n\r\n'.format(len(body_str))
        resp += '<methodResponse><params><param><value><string>{}</string></value></param></params></methodResponse>'.format(body_str)
        return resp
924130
def json(self, **kwargs):
        '''
        
        '''
        body = self._decompress(self.encoding)
        return _json.loads(body, **kwargs)
1087322
def _api_all(self):
        
        response.content_type = 'application/json; charset=utf-8'

        if self.args.debug:
            fname = os.path.join(tempfile.gettempdir(), 'glances-debug.json')
            try:
                with open(fname) as f:
                    return f.read()
            except IOError:
                logger.debug("Debug file (%s) not found" % fname)

        # Update the stat
        self.__update__()

        try:
            # Get the JSON value of the stat ID
            statval = json.dumps(self.stats.getAllAsDict())
        except Exception as e:
            abort(404, "Cannot get stats (%s)" % str(e))

        return statval
557864
def json_response(func):
    

    @wraps(func)
    def wrapper(request, *args, **kwargs):
        res = func(request, *args, **kwargs)
        request.setHeader('Content-Type', 'application/json')
        return json.dumps(res)

    return wrapper
670647
public Map<String, Object> jsonToMap(String json) {

        /*
         * This if block treats the /v2/accounts/exists response. Currently the endpoint returns the status
         * code on its response body, breaking the JSON conversion.
         */
        if ("200".equals(json)) {
            this.responseBody.put("code", 200);
            return this.responseBody;
        }

        if ("400".equals(json)) {
            this.responseBody.put("code", 400);
            return this.responseBody;
        }

        if ("404".equals(json)) {
            this.responseBody.put("code", 404);
            return this.responseBody;
        }

        if (!json.equals("")) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                this.responseBody = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return this.responseBody;
    }
601142
def get_available_plugins(self):
        
        available_plugins = []
        PluginData = namedtuple('PluginData', 'name, plugin_class, conf, is_allowed_to_fail')
        for plugin_request in self.plugins_conf:
            plugin_name = plugin_request['name']
            try:
                plugin_class = self.plugin_classes[plugin_name]
            except KeyError:
                if plugin_request.get('required', True):
                    msg = ("no such plugin: '%s', did you set "
                           "the correct plugin type?") % plugin_name
                    exc = PluginFailedException(msg)
                    self.on_plugin_failed(plugin_name, exc)
                    logger.error(msg)
                    raise exc
                else:
                    # This plugin is marked as not being required
                    logger.warning("plugin '%s' requested but not available",
                                   plugin_name)
                    continue
            plugin_is_allowed_to_fail = plugin_request.get('is_allowed_to_fail',
                                                           getattr(plugin_class,
                                                                   "is_allowed_to_fail", True))
            plugin_conf = plugin_request.get("args", {})
            plugin = PluginData(plugin_name,
                                plugin_class,
                                plugin_conf,
                                plugin_is_allowed_to_fail)
            available_plugins.append(plugin)
        return available_plugins
237965
def get_json_online(self, url):
        
        if not requests:
            return False
        try:
            req = requests.get(url, timeout=.2)
            if not req.ok:
                return []
            return req
        except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError,
                requests.exceptions.ReadTimeout):
            return []
490914
def get(self, endpoint):
        ''''''
        json_body = urlopen(self.url(endpoint)).read().decode('utf-8')
        return json.loads(json_body)
211874
def getAllLimitsAsDict(self, plugin_list=None):
        
        if plugin_list is None:
            # All plugins should be exported
            plugin_list = self._plugins
        return {p: self._plugins[p].limits for p in plugin_list}
423607
def _request_api(self, **kwargs):
        
        _url = kwargs.get('url')
        _method = kwargs.get('method', 'GET')
        _status = kwargs.get('status', 200)

        counter = 0
        if _method not in ['GET', 'POST']:
            raise ValueError('Method is not GET or POST')

        while True:
            try:
                res = REQ[_method](_url, cookies=self._cookie)
                if res.status_code == _status:
                    break
                else:
                    raise BadStatusException(res.content)
            except requests.exceptions.BaseHTTPError:
                if counter < self._retries:
                    counter += 1
                    continue
                raise MaxRetryError
        self._last_result = res
        return res
1015309
def _get_response(**kwargs):
    
    if 'code' not in kwargs:
        kwargs['code'] = 200
    if 'headers' not in kwargs:
        kwargs['headers'] = dict()
    if 'version' not in kwargs:
        kwargs['version'] = 'HTTP/1.1'

    return dict(**kwargs)
1317352
def get_stats(self):
        '''
        
        '''
        resp = requests.get('%s/api/stats.json' % self.url)
        assert(resp.status_code == 200)
        return resp.json()