Common code for GET and POST requests
348897
def common_req(self, execute, send_body=True):
        ""
        self._SERVER            = {'CLIENT_ADDR_HOST': self.client_address[0],
                                   'CLIENT_ADDR_PORT': self.client_address[1]}

        self._to_log            = True
        self._cmd               = None

        self._payload           = None
        self._path              = None
        self._payload_params    = None
        self._query_params      = {}
        self._fragment          = None

        (cmd, res, req)         = (None, None, None)

        try:
            try:
                path    = self._pathify() # pylint: disable-msg=W0612
                cmd     = path[1:]
                res     = execute(cmd)
            except HttpReqError, e:
                e.report(self)
            except Exception:
                try:
                    self.send_exception(500) # XXX 500
                except Exception: # pylint: disable-msg=W0703
                    pass
                raise
            else:
                if not isinstance(res, HttpResponse):
                    req = self.build_response()
                    if send_body:
                        req.add_data(res)
                    req.set_send_body(send_body)
                else:
                    req = res

                self.end_response(req)
        except socket.error, e:
            if e.errno in (errno.ECONNRESET, errno.EPIPE):
                return
            LOG.exception("exception - cmd=%r - method=%r", cmd, self.command)
        except Exception: # pylint: disable-msg=W0703
            LOG.exception("exception - cmd=%r - method=%r", cmd, self.command)
        finally:
            del req, res
228330
def _http_request(url,
                  method='GET',
                  headers=None,
                  data=None):
    '''
    
    '''
    req = requests.request(method,
                           url,
                           headers=headers,
                           data=data)
    ret = _default_ret()
    ok_status = METHOD_OK_STATUS.get(method, 200)
    if req.status_code != ok_status:
        ret.update({
            'comment': req.json().get('error', '')
        })
        return ret
    ret.update({
        'result': True,
        'out': req.json() if method != 'DELETE' else None  # no body when DELETE
    })
    return ret
168087
def _post(self, *args, **kwargs):
        
        data = self._default_data()
        data.update(kwargs.get('data') or {})
        kwargs['data'] = data
        return self._request(requests.post, *args, **kwargs)
314434
def do_GET(self):
    """"""
    if not self._client_allowed():
      return

    try:
      (_, _, path, query, _) = urlsplit(self.path)
      params = parse_qs(query)
      # Give each handler a chance to respond.
      for prefix, handler in self._GET_handlers:
        if self._maybe_handle(prefix, handler, path, params):
          return
      # If no path specified, default to showing the list of all runs.
      if path == '/':
        self._handle_runs('', {})
        return

      content = 'Invalid GET request {}'.format(self.path).encode('utf-8'),
      self._send_content(content, 'text/html', code=400)
    except (IOError, ValueError):
      pass
312383
def _do_POSTGET(self, handler):
        """"""
        # at first, assume that the given path is the actual path and there are
        # no arguments
        self.server._dbg(self.path)

        self.path, self.args = _parse_url(self.path)

        # Extract POST data, if any. Clumsy syntax due to Python 2 and
        # 2to3's lack of a byte literal.
        self.data = u"".encode()
        length = self.headers.get('Content-Length')
        if length and length.isdigit():
            self.data = self.rfile.read(int(length))

        # POST data gets automatically decoded into Unicode. The bytestring
        # will still be available in the bdata attribute.
        self.bdata = self.data
        try:
            self.data = self.data.decode('utf8')
        except UnicodeDecodeError:
            self.data = None

        # Run the handler.
        try:
            handler()
        except:
            self.send_response(500)
            self.end_headers()
            self.wfile.write(format_exc().encode('utf8'))
1101370
def rest_post(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
        
        res = requests.post(url, params=params, headers=headers, auth=auth, verify=verify,
                            cert=cert)
        return res.text, res.status_code
1233899
def rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
        
        res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify,
                           cert=cert)
        return res.text, res.status_code
858624
def _get_request(url_root,api_key,path,response_type,params, ssl_verify):
    
    url = _url_builder(url_root,api_key,path,params)
    content = _fetch(url, ssl_verify)
    response = _dispatch(response_type)(content)
    return response
958642
def post(self, uri, body=None, **kwargs):
        """"""
        return self.fetch('post', uri, kwargs.pop("query", {}), body, **kwargs)
725753
def _request(self, url, method="GET", params=None, api_call=None):
        """"""
        method = method.lower()
        params = params or {}
        func = getattr(requests, method)
        requests_args = {}
        if method == "get" or method == "delete":
            requests_args["params"] = params
        else:
            if params.get("json"):
                requests_args["json"] = params.get("json")
            if params.get("files"):
                requests_args["files"] = params.get("files")
            if params.get("data"):
                requests_args["data"] = params.get("data")
        try:
            response = func(url, **requests_args)
        except requests.RequestException as e:
            raise SafecastPyError(str(e))
        # greater than 304 (not modified) is an error
        if response.status_code > 304:
            if response.status_code == 401:
                raise SafecastPyAuthError(response.json().get("error"))
            if response.status_code in [422]:
                raise SafecastPyError(response.json().get("errors"))
            raise SafecastPyError(response.content, error_code=response.status_code)
        try:
            if response.status_code == 204:
                content = response.content
            else:
                content = response.json()
        except ValueError:
            raise SafecastPyError(
                "Response was not valid JSON. \
                               Unable to decode."
            )
        return content
371730
def post(self, url, data, charset=CHARSET_UTF8, headers={}):
        ''''''
        if 'Api-Lang' not in headers:
            headers['Api-Lang'] = 'python'
        if 'Content-Type' not in headers:
            headers['Content-Type'] = "application/x-www-form-urlencoded;charset=" + charset
        rsp = requests.post(url, data, headers=headers,
                            timeout=(int(self.conf(HTTP_CONN_TIMEOUT, '10')), int(self.conf(HTTP_SO_TIMEOUT, '30'))))
        return json.loads(rsp.text)
70186
def _request_get(self, path, params=None, json=True, url=BASE_URL):
        """"""
        url = urljoin(url, path)
        headers = self._get_request_headers()

        response = requests.get(url, params=params, headers=headers)
        if response.status_code >= 500:

            backoff = self._initial_backoff
            for _ in range(self._max_retries):
                time.sleep(backoff)
                backoff_response = requests.get(
                    url, params=params, headers=headers,
                    timeout=DEFAULT_TIMEOUT)
                if backoff_response.status_code < 500:
                    response = backoff_response
                    break
                backoff *= 2

        response.raise_for_status()
        if json:
            return response.json()
        else:
            return response
1096636
def request(self, url='', method = 'GET', data = None, parse=True, encoding=None):
        """"""

        requestparams = self.initrequest(data)


        if method == 'POST':
            request = requests.post
        elif method == 'DELETE':
            request = requests.delete
        elif method == 'PUT':
            request = requests.put
        else:
            request = requests.get

        r = request(self.url + url,**requestparams)
        if encoding is not None:
            r.encoding = encoding

        if r.status_code == 400:
            raise clam.common.data.BadRequest()
        elif r.status_code == 401:
            raise clam.common.data.AuthRequired()
        elif r.status_code == 403: #pylint: disable=too-many-nested-blocks
            content = r.text
            if parse:
                data = self._parse(content)
                if data:
                    if data.errors:
                        error = data.parametererror()
                        #print("DEBUG: parametererror=" + str(error),file=sys.stderr)
                        #for parametergroup, parameters in data.parameters: #pylint: disable=unused-variable
                        #    for parameter in parameters:
                        #        print("DEBUG: ", parameter.id, parameter.error,file=sys.stderr)
                        if error:
                            raise clam.common.data.ParameterError(error)
                    #print(content,file=sys.stderr)
                    raise clam.common.data.PermissionDenied(data)
                else:
                    raise clam.common.data.PermissionDenied(content)
            else:
                raise clam.common.data.PermissionDenied(content)
        elif r.status_code == 404 and data:
            raise clam.common.data.NotFound(r.text)
        elif r.status_code == 500:
            raise clam.common.data.ServerError(r.text)
        elif r.status_code == 405:
            raise clam.common.data.ServerError("Server returned 405: Method not allowed for " + method + " on " + self.url + url)
        elif r.status_code == 408:
            raise clam.common.data.TimeOut()
        elif not (r.status_code >= 200 and r.status_code <= 299):
            raise Exception("An error occured, return code " + str(r.status_code))

        if parse:
            return self._parse(r.text)
        else:
            return r.text
537557
def make_post_request(self, url, auth, json_payload):
        """"""
        response = requests.post(url, auth=auth, json=json_payload)
        return response.json()
144565
def do_GET(self):
        """"""
        thread_local.clock_start = get_time()
        thread_local.status_code = 200
        thread_local.message = None
        thread_local.headers = []
        thread_local.end_headers = []
        thread_local.size = -1
        thread_local.method = 'GET'
        try:
            self.cross_origin_headers()
            if self.handle_special(True, 'GET'):
                return
            SimpleHTTPRequestHandler.do_GET(self)
        except PreventDefaultResponse as pdr:
            if pdr.code:
                self.send_error(pdr.code, pdr.msg)
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.handle_error()
925683
def post(self, url, data=None, **kwargs):
        """"""
        return requests.post(url, data=data, headers=self.add_headers(**kwargs))
210581
def post(self, uri, data, **kwargs):
        
        return self.request("POST", uri, data=data, **kwargs)