Handy way to query the server, returning *only* the body
 Will raise an exception when the status is not in the 2xx range
492103
def request(method, path, params={}, body=nil, headers={}, options={}, &block)
      options = { :mashify => true }.merge(options)
      req = http.build_request(method)
      req.path = path
      req.params.update(Util.clean_params(params)) if params
      req.body = body
      req.headers.update(headers) if headers
      block.call(req) if block
      logger.debug { Util.curl_format(req) }

      if @http_threadsafe
        env = req.to_env(http)
        check_response(http.app.call(env), options)
      else
        @request_mtx.synchronize {
          env = req.to_env(http)
          check_response(http.app.call(env), options)
        }
      end
    end
229473
def get_payload(self):
        
        temp = self.get_uri_as_list()
        query_string = temp[4]
        if query_string == "":
            return None  # Bad request error code
        query_string_as_list = str.split(query_string, "=")
        return query_string_as_list[1]
382811
def get_status(self, response, finished=False):
        """"""
        for line in response.split("\n"):
            if line.strip() in self.status_mapping:
                return self.status_mapping[line.strip()]
        return None
788103
def _query_api(self, method, url, fields=None, extra_headers=None, req_body=None):
        
        with self.auth.authenticate() as token:
            logging.debug('PA Authentication returned token %s', token)
            headers = {
                'Authorization': 'Bearer %s' % (token,),
                'Realm': self.auth_realm
            }
            if extra_headers is not None:
                headers.update(extra_headers)

            logging.info('[%s] %s', method, url)
            if req_body is not None:
                response = self.http.request(method, url, fields, headers, body=req_body)
            else:
                response = self.http.request(method, url, fields, headers)                
            if response.status != 200:
                print(response.data)
                logging.warning('Got non-200 HTTP status from API: %d', response.status)
                raise ApiQueryError("Failed to get API data", response.status)
            return json.loads(response.data.decode())
645034
def _get_status_code(self, http_status):
    
    try:
      return int(http_status.split(' ', 1)[0])
    except TypeError:
      _logger.warning('Unable to find status code in HTTP status %r.',
                      http_status)
    return 500
1228375
def get_status_from_resource(self, response):
        
        self._raise_if_bad_http_status_and_method(response)
        if self._is_empty(response):
            raise BadResponse('The response from long running operation '
                              'does not contain a body.')

        status = self._get_provisioning_state(response)
        self.status = status or 'Succeeded'

        self.parse_resource(response)
6796
def query(self, query):
        
        if not isinstance(query, bytes):
            query = query.encode("utf-8")

        retry_num = 0
        retry_exceptions = []
        do_retry = True if self.max_retry_count > 0 else False
        while retry_num <= self.max_retry_count:
            if retry_num > 0:
                time.sleep(self.retry_timeout)
            retry_num += 1
            try:
                f = urlopen(self.url, query)
            except HTTPError as e:
                f = e

            response = f.read(self.read_chunk_size)
            while True:
                data = f.read(self.read_chunk_size)
                if len(data) == 0:
                    break
                response = response + data
            f.close()

            if f.code == 200:
                if PY2:
                    http_info = f.info()
                    content_type = http_info.getheader("content-type")
                else:
                    content_type = f.getheader("Content-Type")

                if content_type == "application/json":
                    return self.parse_json(response)

                if content_type == "application/osm3s+xml":
                    return self.parse_xml(response)

                e = exception.OverpassUnknownContentType(content_type)
                if not do_retry:
                    raise e
                retry_exceptions.append(e)
                continue

            if f.code == 400:
                msgs = []
                for msg in self._regex_extract_error_msg.finditer(response):
                    tmp = self._regex_remove_tag.sub(b"", msg.group("msg"))
                    try:
                        tmp = tmp.decode("utf-8")
                    except UnicodeDecodeError:
                        tmp = repr(tmp)
                    msgs.append(tmp)

                e = exception.OverpassBadRequest(
                    query,
                    msgs=msgs
                )
                if not do_retry:
                    raise e
                retry_exceptions.append(e)
                continue

            if f.code == 429:
                e = exception.OverpassTooManyRequests
                if not do_retry:
                    raise e
                retry_exceptions.append(e)
                continue

            if f.code == 504:
                e = exception.OverpassGatewayTimeout
                if not do_retry:
                    raise e
                retry_exceptions.append(e)
                continue

            e = exception.OverpassUnknownHTTPStatusCode(f.code)
            if not do_retry:
                raise e
            retry_exceptions.append(e)
            continue

        raise exception.MaxRetriesReached(retry_count=retry_num, exceptions=retry_exceptions)
37652
def query(self, body, params=None):
        
        if body in SKIP_IN_PATH:
            raise ValueError("Empty value passed for a required argument 'body'.")
        return self.transport.perform_request("POST", "/_sql", params=params, body=body)
1299374
def query(self,
              startTime=None,
              endTime=None,
              sinceServerStart=False,
              level="WARNING",
              services="*",
              machines="*",
              server="*",
              codes=[],
              processIds=[],
              export=False,
              exportType="CSV", #CSV or TAB
              out_path=None
              ):
        
        allowed_levels = ("SEVERE", "WARNING", "INFO",
                          "FINE", "VERBOSE", "DEBUG")
        qFilter = {
            "services": "*",
            "machines": "*",
            "server" : "*"
        }
        if len(processIds) > 0:
            qFilter['processIds'] = processIds
        if len(codes) > 0:
            qFilter['codes'] = codes
        params = {
            "f" : "json",
            "sinceServerStart" : sinceServerStart,
            "pageSize" : 10000
        }
        if startTime is not None and \
           isinstance(startTime, datetime):
            params['startTime'] = startTime.strftime("%Y-%m-%dT%H:%M:%S")
        if endTime is not None and \
           isinstance(endTime, datetime):
            params['endTime'] = endTime.strftime("%Y-%m-%dT%H:%M:%S")
        if level.upper() in allowed_levels:
            params['level'] = level
        if server != "*":
            qFilter['server'] = server.split(',')
        if services != "*":
            qFilter['services'] = services.split(',')
        if machines != "*":
            qFilter['machines'] = machines.split(",")
        params['filter'] = qFilter
        if export == True and \
           out_path is not None:
            messages = self._post(self._url + "/query", params,
                                     securityHandler=self._securityHandler,
                                     proxy_url=self._proxy_url,
                                     proxy_port=self._proxy_port)

            with open(name=out_path, mode='wb') as f:
                hasKeys = False
                if exportType == "TAB":
                    csvwriter = csv.writer(f, delimiter='\t')
                else:
                    csvwriter = csv.writer(f)
                for message in messages['logMessages']:
                    if hasKeys == False:
                        csvwriter.writerow(message.keys())
                        hasKeys = True
                    csvwriter.writerow(message.values())
                    del message
            del messages
            return out_path
        else:
            return self._post(self._url + "/query", params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
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
816888
def status(host=None, port=None):
    """"""
    app.config['HOST'] = first_value(host, app.config.get('HOST',None), '0.0.0.0')
    app.config['PORT'] = int(first_value(port, app.config.get('PORT',None), 5001))
    if app.config['HOST'] == "0.0.0.0": 
        host="127.0.0.1"
    else:
        host = app.config['HOST']
    port = app.config['PORT']    
    try:
        rep = requests.get('http://%s:%s/api/status' % (host,port))
        if rep.status_code == 200:
            try:
                rep = json.loads(rep.text)
                for k in rep:
                    print('%s\t: %s' % (k, rep[k]))
            except:
                print('web server is not flaskserver', file=sys.stderr)
        else:
            print('web server is not flaskserver', file=sys.stderr)
    except:
        print('web server is not started', file=sys.stderr)
1047960
def get_status(self):
        
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url,
            headers={
                "Accept": Consts.mediaTypeMigrationPreview
            }
        )
        self._useAttributes(data)
        return self.state
1330536
def getBody(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120):
        
        if not 'User-Agent' in headers:
            headers['User-Agent'] = ['Tensor HTTP checker']

        return cls().request(url, method, headers, data, socket, timeout)
957966
def status(cls):
        """"""
        return cls.json_get('%s/status' % cls.api_url, empty_key=True,
                            send_key=False)
80106
def check_server(self):
        
        msg = 'API server not found. Please check your API url configuration.'

        try:
            response = self.session.head(self.domain)
        except Exception as e:
            raise_from(errors.ServerError(msg), e)

        try:
            self._check_response(response)
        except errors.NotFound as e:
            raise raise_from(errors.ServerError(msg), e)
1194389
def _check_response(self, response):
        
        if response.status_code > 299 or response.status_code < 200:
            log.debug("Received response code [%s] - headers: %s" % (response.status_code, str(response.headers)))
            try:
                _json = response.json()
                err_type = _json.get("error", '')
                if err_type == 'RecordNotFound':
                    raise RecordNotFoundException(json.dumps(_json), response=response)
                elif err_type == "TooManyValues":
                    raise TooManyValuesException(json.dumps(_json), response=response)
                else:
                    raise APIException(json.dumps(_json), response=response)
            except ValueError:
                response.raise_for_status()
1280938
def header_status(header):
    """"""
    status_line = header[:header.find('\r')]
    # 'HTTP/1.1 200 OK' -> (200, 'OK')
    fields = status_line.split(None, 2)
    return int(fields[1]), fields[2]