query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
httpclient post json
python
def post_json(self, url, data, cls=None, **kwargs): """ POST data to the api-server :param url: resource location (eg: "/type/uuid") :type url: str :param cls: JSONEncoder class :type cls: JSONEncoder """ kwargs['data'] = to_json(data, cls=cls) kwargs['headers'] = self.default_headers return self.post(url, **kwargs).json()
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/client.py#L136-L147
httpclient post json
python
def post_json(self, uri, data, **kwargs): """POST the provided data as json to the specified path See :meth:`request` for additional details. """ encoded_data = json.dumps(data) kwargs.setdefault("headers", {}).update({ "Content-Type": "application/json", # tell server we are sending json }) return self.post(uri, data=encoded_data, **kwargs)
https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/http_client.py#L145-L154
httpclient post json
python
def _post_json(self, url, data, **kw): ''' Makes a POST request, setting Authorization and Content-Type headers by default ''' data = json.dumps(data) headers = kw.pop('headers', {}) headers.setdefault('Content-Type', 'application/json') headers.setdefault('Accept', 'application/json') kw['headers'] = headers kw['data'] = data return self._post(url, **kw)
https://github.com/joealcorn/xbox/blob/3d2aeba10244dcb58d714d76fc88487c74bd1510/xbox/client.py#L68-L80
httpclient post json
python
def client_post(self, url, **kwargs): """Send POST request with given url and keyword args.""" response = requests.post(self.make_url(url), data=json.dumps(kwargs), headers=self.headers) if not response.ok: raise Exception( '{status}: {reason}.\nCircleCI Status NOT OK'.format( status=response.status_code, reason=response.reason)) return response.json()
https://github.com/qba73/circleclient/blob/8bf5b093e416c899cc39e43a770c17a5466487b0/circleclient/circleclient.py#L46-L55
httpclient post json
python
def _post(self, url, obj, content_type, **kwargs): """ POST an object and check the response. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected content type of the response. :raises txacme.client.ServerError: If server response body carries HTTP Problem (draft-ietf-appsawg-http-problem-00). :raises acme.errors.ClientError: In case of other protocol errors. """ with LOG_JWS_POST().context(): headers = kwargs.setdefault('headers', Headers()) headers.setRawHeaders(b'content-type', [JSON_CONTENT_TYPE]) return ( DeferredContext(self._get_nonce(url)) .addCallback(self._wrap_in_jws, obj) .addCallback( lambda data: self._send_request( u'POST', url, data=data, **kwargs)) .addCallback(self._add_nonce) .addCallback(self._check_response, content_type=content_type) .addActionFinish())
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L851-L875
httpclient post json
python
def post(self, json=None): """Send a POST request and return the JSON decoded result. Args: json (dict, optional): Object to encode and send in request. Returns: mixed: JSON decoded response data. """ return self._call('post', url=self.endpoint, json=json)
https://github.com/LasLabs/python-helpscout/blob/84bf669417d72ca19641a02c9a660e1ae4271de4/helpscout/request_paginator/__init__.py#L114-L123
httpclient post json
python
def post(self, url, data, params=None, headers=None, connection=None): """ Synchronous POST request. ``data`` must be a JSONable value. """ params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url, None) self._authenticate(params, headers) data = json.dumps(data, cls=JSONEncoder) return make_post_request(endpoint, data, params, headers, connection=connection)
https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L319-L329
httpclient post json
python
def _fetch_json(self, url, payload): """Fetch json data for requests.""" params = { 'data': json.dumps(payload), 'headers': {'content-type': 'application/json'}, 'params': {'sid': self.sma_sid} if self.sma_sid else None, } for _ in range(3): try: with async_timeout.timeout(3): res = yield from self._aio_session.post( self._url + url, **params) return (yield from res.json()) or {} except asyncio.TimeoutError: continue return {'err': "Could not connect to SMA at {} (timeout)" .format(self._url)}
https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L190-L206
httpclient post json
python
def _put_or_post_json(self, method, url, data): """ urlencodes the data and PUTs it to the url the response is parsed as JSON and the resulting data type is returned """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc) else: conn = httplib.HTTPConnection(self.parsed_endpoint.netloc) head = { "Content-Type": "application/json", "Accept": "application/json", "User-Agent": USER_AGENT, API_TOKEN_HEADER_NAME: self.api_token, } if self.api_version in ['0.1', '0.01a']: head[API_VERSION_HEADER_NAME] = self.api_version conn.request(method, url, json.dumps(data), head) resp = conn.getresponse() self._handle_response_errors(method, url, resp) return json.loads(resp.read())
https://github.com/Captricity/captools/blob/e7dc069ff5ede95d4956c7a0a4614d0e53e5a955/captools/api/client.py#L207-L227
httpclient post json
python
def _http_post(self, url, data, **kwargs): """ Performs the HTTP POST request. """ if not kwargs.get('file_upload', False): data = json.dumps(data) kwargs.update({'data': data}) return self._http_request('post', url, kwargs)
https://github.com/contentful/contentful-management.py/blob/707dd30883b98a10c7ff0f7f5bdb8edbdc1d8df0/contentful_management/client.py#L709-L719
httpclient post json
python
def post(self, url, obj, content_type=JSON_CONTENT_TYPE, **kwargs): """ POST an object and check the response. Retry once if a badNonce error is received. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected content type of the response. By default, JSON. :raises txacme.client.ServerError: If server response body carries HTTP Problem (draft-ietf-appsawg-http-problem-00). :raises acme.errors.ClientError: In case of other protocol errors. """ def retry_bad_nonce(f): f.trap(ServerError) # The current RFC draft defines the namespace as # urn:ietf:params:acme:error:<code>, but earlier drafts (and some # current implementations) use urn:acme:error:<code> instead. We # don't really care about the namespace here, just the error code. if f.value.message.typ.split(':')[-1] == 'badNonce': # If one nonce is bad, others likely are too. Let's clear them # and re-add the one we just got. self._nonces.clear() self._add_nonce(f.value.response) return self._post(url, obj, content_type, **kwargs) return f return ( self._post(url, obj, content_type, **kwargs) .addErrback(retry_bad_nonce))
https://github.com/twisted/txacme/blob/9478381cc63c6d53d14bf8db8407c923f472989a/src/txacme/client.py#L877-L907
httpclient post json
python
def do_POST(self): ''' Handle POST requests ''' try: self._parse_request() except Exception as ex1: print(traceback.format_exc()) self.error_response(JSONRPC_PARSE_ERROR, 'exception when parsing jsonrpc request [%s]' % (ex1)) return try: if self.req_method.startswith('_meta_'): self.req_method = self.req_method.replace('_meta_', '') instance = self.server.meta else: instance = self.server.impl method = getattr(instance, self.req_method) except AttributeError: self.error_response(JSONRPC_METHOD_NOT_FOUND, 'no method named "%s"' % self.req_method) return try: res = method(**self.req_params) except Exception as ex1: self.error_response(JSONRPC_INTERNAL_ERROR, 'exception in call "%s(%s)" -> %s' % (self.req_method, self.req_params, ex1)) return if res is None: self.error_response(JSONRPC_NO_RESULT, JSONRPC_NO_RESULT_STR) else: self.valid_response(res)
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/remote/rpc.py#L222-L250
httpclient post json
python
def _request_json( url, parameters=None, body=None, headers=None, cache=True, agent=None, reattempt=5, ): """ Queries a url for json data Note: Requests are cached using requests_cached for a week, this is done transparently by using the package's monkey patching """ assert url content = None status = 500 log.info("url: %s" % url) if isinstance(headers, dict): headers = _clean_dict(headers) else: headers = dict() if isinstance(parameters, dict): parameters = _d2l(_clean_dict(parameters)) if body: method = "POST" headers["content-type"] = "application/json" headers["user-agent"] = _get_user_agent(agent) headers["content-length"] = ustr(len(body)) else: method = "GET" headers["user-agent"] = _get_user_agent(agent) initial_cache_state = SESSION._is_cache_disabled # yes, i'm a bad person try: SESSION._is_cache_disabled = not cache response = SESSION.request( url=url, params=parameters, json=body, headers=headers, method=method, timeout=1, ) status = response.status_code content = response.json() if status // 100 == 2 else None cache = getattr(response, "from_cache", False) except RequestException as e: log.debug(e, exc_info=True) return _request_json( url, parameters, body, headers, cache, agent, reattempt - 1 ) except Exception as e: log.error(e, exc_info=True) if reattempt > 0: SESSION.cache.clear() return _request_json( url, parameters, body, headers, False, agent, 0 ) else: log.info("method: %s" % method) log.info("headers: %r" % headers) log.info("parameters: %r" % parameters) log.info("cache: %r" % cache) log.info("status: %d" % status) log.debug("content: %s" % content) finally: SESSION._is_cache_disabled = initial_cache_state return status, content
https://github.com/jkwill87/mapi/blob/730bf57c12aecaf49e18c15bf2b35af7f554b3cc/mapi/endpoints.py#L97-L167
httpclient post json
python
async def post(self, url_path: str, params: dict = None, rtype: str = RESPONSE_JSON, schema: dict = None) -> Any: """ POST request on self.endpoint + url_path :param url_path: Url encoded path following the endpoint :param params: Url query string parameters dictionary :param rtype: Response type :param schema: Json Schema to validate response (optional, default None) :return: """ if params is None: params = dict() client = API(self.endpoint.conn_handler(self.session, self.proxy)) # get aiohttp response response = await client.requests_post(url_path, **params) # if schema supplied... if schema is not None: # validate response await parse_response(response, schema) # return the chosen type if rtype == RESPONSE_AIOHTTP: return response elif rtype == RESPONSE_TEXT: return await response.text() elif rtype == RESPONSE_JSON: return await response.json()
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/client.py#L246-L275
httpclient post json
python
def _post(self, q, payload='', params=''): '''Generic POST wrapper including the api_key''' if (q[-1] == '/'): q = q[:-1] headers = {'Content-Type': 'application/json'} r = requests.post('{url}{q}?api_key={key}{params}'.format(url=self.url, q=q, key=self.api_key, params=params), headers=headers, data=payload) ret = DotDict(r.json()) if (not r.ok or ('error' in ret and ret.error == True)): raise Exception(r.url, r.reason, r.status_code, r.json()) return DotDict(r.json())
https://github.com/gdestuynder/simple_bugzilla/blob/c69766a81fa7960a8f2b22287968fa4787f1bcfe/bugzilla.py#L126-L135
httpclient post json
python
def _post(self, data, file_to_upload=None): """ Make the POST request. """ # pylint: disable=E1101 params = {"JSONRPC": simplejson.dumps(data)} req = None if file_to_upload: req = http_core.HttpRequest(self.write_url) req.method = 'POST' req.add_body_part("JSONRPC", simplejson.dumps(data), 'text/plain') upload = file(file_to_upload, "rb") req.add_body_part("filePath", upload, 'application/octet-stream') req.end_of_parts() content_type = "multipart/form-data; boundary=%s" % \ http_core.MIME_BOUNDARY req.headers['Content-Type'] = content_type req.headers['User-Agent'] = config.USER_AGENT req = http_core.ProxiedHttpClient().request(req) else: msg = urllib.urlencode({'json': params['JSONRPC']}) req = urllib2.urlopen(self.write_url, msg) if req: result = simplejson.loads(req.read()) if 'error' in result and result['error']: exceptions.BrightcoveError.raise_exception( result['error']) return result['result']
https://github.com/studionow/pybrightcove/blob/19c946b689a80156e070fe9bc35589c4b768e614/pybrightcove/connection.py#L181-L210
httpclient post json
python
def http_post_request(url, params, add_to_headers=None, _async=False): """ from 火币demo, post方法 :param url: :param params: :param add_to_headers: :return: """ headers = { "Accept": "application/json", 'Content-Type': 'application/json' } if add_to_headers: headers.update(add_to_headers) postdata = json.dumps(params) if _async: response = async_session.post(url, postdata, headers=headers, timeout=10) return response else: response = requests.post(url, postdata, headers=headers, timeout=10) try: if response.status_code == 200: return response.json() else: logger.debug(f'<POST>error_code:{response.status_code} reason:{response.reason} detail:{response.text}') return except BaseException as e: logger.exception( f'<POST>httpPost failed, detail is:{response.text},{e}') return
https://github.com/hadrianl/huobi/blob/bbfa2036703ee84a76d5d8e9f89c25fc8a55f2c7/huobitrade/utils.py#L211-L241
httpclient post json
python
def _post(self, url, data=None): """ Handle authenticated POST requests :param url: The url for the endpoint including path parameters :type url: :py:class:`str` :param data: The request body parameters :type data: :py:data:`none` or :py:class:`dict` :returns: The JSON output from the API or an error message """ url = urljoin(self.base_url, url) try: r = self._make_request(**dict( method='POST', url=url, json=data, auth=self.auth, timeout=self.timeout, hooks=self.request_hooks, headers=self.request_headers )) except requests.exceptions.RequestException as e: raise e else: if r.status_code >= 400: # in case of a 500 error, the response might not be a JSON try: error_data = r.json() except ValueError: error_data = { "response": r } raise MailChimpError(error_data) if r.status_code == 204: return None return r.json()
https://github.com/VingtCinq/python-mailchimp/blob/1b472f1b64fdde974732ac4b7ed48908bb707260/mailchimp3/mailchimpclient.py#L101-L134
httpclient post json
python
def post(self, url, post_data, query_params=None): """Makes a POST request to the specified url endpoint. Args: url (string): The url to the API without query params. Example: "https://api.housecanary.com/v2/property/value" post_data: Json post data to send in the body of the request. query_params (dict): Optional. Dictionary of query params to add to the request. Returns: The result of calling this instance's OutputGenerator process_response method on the requests.Response object. If no OutputGenerator is specified for this instance, returns the requests.Response. """ if query_params is None: query_params = {} return self.execute_request(url, "POST", query_params, post_data)
https://github.com/housecanary/hc-api-python/blob/2bb9e2208b34e8617575de45934357ee33b8531c/housecanary/requestclient.py#L76-L93
httpclient post json
python
def put_json(self, url, data, cls=None, **kwargs): """ PUT data to the api-server :param url: resource location (eg: "/type/uuid") :type url: str :param cls: JSONEncoder class :type cls: JSONEncoder """ kwargs['data'] = to_json(data, cls=cls) kwargs['headers'] = self.default_headers return self.put(url, **kwargs).json()
https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/client.py#L150-L161
httpclient post json
python
def post(self, path, payload): """Make a POST request from the API.""" body = json.dumps(payload) return self._request(path, 'POST', body)
https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/__init__.py#L57-L60
httpclient post json
python
def post(json_data, url, dry_run=False): """ POST json data to the url provided and verify the requests was successful """ if dry_run: info('POST: %s' % json.dumps(json_data, indent=4)) else: response = SESSION.post(url, data=json.dumps(json_data), headers={'content-type': 'application/json'}) if response.status_code != 200: raise Exception("Failed to import %s with %s: %s" % (json_data, response.status_code, response.text))
https://github.com/jut-io/jut-python-tools/blob/65574d23f51a7bbced9bb25010d02da5ca5d906f/jut/commands/upload.py#L19-L36
httpclient post json
python
def _api_post(path, data, server=None): ''' Do a POST request to the API ''' server = _get_server(server) response = requests.post( url=_get_url(server['ssl'], server['url'], server['port'], path), auth=_get_auth(server['user'], server['password']), headers=_get_headers(), data=salt.utils.json.dumps(data), verify=False ) return _api_response(response)
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glassfish.py#L126-L138
httpclient post json
python
def post(self, url, data=None, files=None, headers=None, get_json=True): ''' Make POST request to a url Args: url (str): URL to send the request to data (dict, optional): Data to send files (dict, optional): Files to send with the request headers (str, optional): custom headers Returns: A JSON object of the returned response if `get_json` is True, Requests' response object otherwise ''' if self.debug: print("POST: %s, headers=%s" % (url, headers)) self.headers = self._get_default_headers() if headers is not None: self.headers.update(headers) response = requests.post(url, headers=self.headers, data=data, auth=self.auth, files=files, verify=self.verify_ssl) json_response = self._process_json_response(response) return json_response if get_json is True else response
https://github.com/hellosign/hellosign-python-sdk/blob/4325a29ad5766380a214eac3914511f62f7ecba4/hellosign_sdk/utils/request.py#L145-L170
httpclient post json
python
def make_post_request(self, url, auth, json_payload): """This function executes the request with the provided json payload and return the json response""" response = requests.post(url, auth=auth, json=json_payload) return response.json()
https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/backend/quiver_cloud.py#L64-L68
httpclient post json
python
def post(self, client_method, data, post_params=None, is_json=True): """Make a POST request""" url = self._wa.apollo_url + self.CLIENT_BASE + client_method if post_params is None: post_params = {} headers = { 'Content-Type': 'application/json' } data.update({ 'username': self._wa.username, 'password': self._wa.password, }) curl_command = ['curl', url] for (k, v) in headers.items(): curl_command += ['-H', quote('%s: %s' % (k, v))] curl_command += ['-d', quote(json.dumps(data))] log.info(' '.join(curl_command)) resp = requests.post(url, data=json.dumps(data), headers=headers, verify=self.__verify, params=post_params, allow_redirects=False, **self._request_args) if resp.status_code == 200 or resp.status_code == 302: if is_json: data = resp.json() return self._scrub_data(data) else: return resp.text # @see self.body for HTTP response body raise Exception("Unexpected response from apollo %s: %s" % (resp.status_code, resp.text))
https://github.com/galaxy-genome-annotation/python-apollo/blob/2bc9991302abe4402ec2885dcaac35915475b387/apollo/client.py#L29-L65
httpclient post json
python
def request_json(self, url, params=None, data=None, as_objects=True, retry_on_error=True, method=None): """Get the JSON processed from a page. :param url: the url to grab content from. :param params: a dictionary containing the GET data to put in the url :param data: a dictionary containing the extra data to submit :param as_objects: if True return reddit objects else raw json dict. :param retry_on_error: if True retry the request, if it fails, for up to 3 attempts :returns: JSON processed page """ if not url.endswith('.json'): url += '.json' response = self._request(url, params, data, method=method, retry_on_error=retry_on_error) hook = self._json_reddit_objecter if as_objects else None # Request url just needs to be available for the objecter to use self._request_url = url # pylint: disable=W0201 if response == '': # Some of the v1 urls don't return anything, even when they're # successful. return response data = json.loads(response, object_hook=hook) delattr(self, '_request_url') # Update the modhash if isinstance(data, dict) and 'data' in data \ and 'modhash' in data['data']: self.modhash = data['data']['modhash'] return data
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L604-L636
httpclient post json
python
def do_POST(self): """Handles HTTP POST requests.""" post_data = self.rfile.read(int(self.headers['Content-Length'])) json_data = gzip.decompress(post_data) self._profile_json.update(json.loads(json_data.decode('utf-8'))) self._send_response( 200, headers=(('Content-type', '%s; charset=utf-8' % 'text/json'), ('Content-Encoding', 'gzip'), ('Content-Length', len(post_data))))
https://github.com/nvdv/vprof/blob/4c3ff78f8920ab10cb9c00b14143452aa09ff6bb/vprof/stats_server.py#L68-L76
httpclient post json
python
def post(self, path, data, is_json=True): '''Make a post request with client_id and secret key.''' post_data = { 'client_id': self.client_id, 'secret': self.secret, } post_data.update(data) return self._post(path, post_data, is_json)
https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/client.py#L80-L87
httpclient post json
python
def post(self, url, params={}, files=None): """ Issues a POST request against the API, allows for multipart data uploads :param url: a string, the url you are requesting :param params: a dict, the key-value of all the parameters needed in the request :param files: a list, the list of tuples of files :returns: a dict parsed of the JSON response """ params.update({'api_key': self.api_key}) try: response = requests.post(self.host + url, data=params, files=files) return self.json_parse(response.content) except RequestException as e: return self.json_parse(e.args)
https://github.com/tklovett/PyShirtsIO/blob/ff2f2d3b5e4ab2813abbce8545b27319c6af0def/ShirtsIO/request.py#L33-L49
httpclient post json
python
def post_async(self, url, data, callback=None, params=None, headers=None): """ Asynchronous POST request with the process pool. """ params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url, None) self._authenticate(params, headers) data = json.dumps(data, cls=JSONEncoder) process_pool.apply_async(make_post_request, args=(endpoint, data, params, headers), callback=callback)
https://github.com/ozgur/python-firebase/blob/6b96b326f6d8f477503ca42fdfbd81bcbe1f9e0d/firebase/firebase.py#L331-L342
httpclient post json
python
def do_post(url, payload, to=3, use_json=True): """ 使用 ``request.get`` 从指定 url 获取数据 :param use_json: 是否使用 ``json`` 格式, 如果是, 则可以直接使用字典, 否则需要先转换成字符串 :type use_json: bool :param payload: 实际数据内容 :type payload: dict :param url: ``接口地址`` :type url: :param to: ``响应超时返回时间`` :type to: :return: ``接口返回的数据`` :rtype: dict """ try: if use_json: rs = requests.post(url, json=payload, timeout=to) else: rs = requests.post(url, data=payload, timeout=to) if rs.status_code == 200: log.warn(rs.text) return rs.json() except Exception as er: log.error('post to {} ({}) with err: {}'.format(url, payload, er)) time.sleep(0.5) return {}
https://github.com/coghost/izen/blob/432db017f99dd2ba809e1ba1792145ab6510263d/izen/helper.py#L960-L986
httpclient post json
python
def post_request(self, container, resource=None, params=None, accept=None): """Send a POST request.""" url = self.make_url(container, resource) headers = self._make_headers(accept) try: rsp = requests.post(url, data=params, headers=headers, verify=self._verify, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) if self._dbg_print: self.__print_req('POST', rsp.url, headers, params) return self._handle_response(rsp)
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L220-L234
httpclient post json
python
def post(self, url, headers=None, params=None, **kwargs): """Send a JSON POST request with the given request headers, additional URL query parameters, and the given JSON in the request body. The extra query parameters are merged with any which already exist in the URL. The 'json' and 'data' parameters may not both be given. Args: url (str): URL to retrieve headers (dict): Any other headers to be added to the request. params: dictionary or bytes to be sent in the query string for the request. (optional) json: json to send in the body of the Request. This must be a JSON-serializable object. (optional) data: raw request body data. May be a dictionary, list of tuples, bytes, or file-like object to send in the body of the Request. (optional) """ if len(kwargs) > 1: raise InvalidArgumentsError("Too many extra args ({} > 1)".format( len(kwargs))) if kwargs: kwarg = next(iter(kwargs)) if kwarg not in ("json", "data"): raise InvalidArgumentsError("Invalid kwarg: " + kwarg) resp = self.session.post(url, headers=headers, params=params, **kwargs) resp.raise_for_status() return _to_json(resp)
https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L951-L980
httpclient post json
python
def _post(self, url, data): """ Helper method: POST data to a given URL on TBA's API. :param url: URL string to post data to and hash. :pararm data: JSON data to post and hash. :return: Requests Response object. """ return self.session.post(self.WRITE_URL_PRE + url % self.event_key, data=data, headers={'X-TBA-Auth-Sig': md5((self.auth_secret + '/api/trusted/v1/' + url % self.event_key + data).encode('utf-8')).hexdigest()})
https://github.com/frc1418/tbapy/blob/3866d5a9971fe3dfaf1a1d83638bd6be6070f0c4/tbapy/main.py#L42-L51
httpclient post json
python
def post(self, url: str, data: str, expected_status_code=201): """ Do a POST request """ r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT) self._check_response(r, expected_status_code) return r.json()
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L95-L102
httpclient post json
python
def _request_post(self, path, data=None, params=None, url=BASE_URL): """Perform a HTTP POST request..""" url = urljoin(url, path) headers = self._get_request_headers() response = requests.post( url, json=data, params=params, headers=headers, timeout=DEFAULT_TIMEOUT) response.raise_for_status() if response.status_code == 200: return response.json()
https://github.com/tsifrer/python-twitch-client/blob/d8eda09acddabe1a9fd9eb76b3f454fa827b5074/twitch/api/base.py#L59-L70
httpclient post json
python
def _post(url, data, content_type, params=None): """HTTP POST request.""" try: response = requests.post(url, params=params, data=data, headers={ 'Content-Type': content_type, }) response.raise_for_status() return response.json() except NameError: url = '{0}?{1}'.format(url, urllib.urlencode(params)) req = urllib2.Request(url, data.encode(ENCODING), { 'Content-Type': content_type, }) return json.loads(urllib2.urlopen(req).read().decode(ENCODING))
https://github.com/attilaolah/diffbot.py/blob/b66d68a36a22c944297c0575413db23687029af4/diffbot.py#L49-L62
httpclient post json
python
def post(self, endpoint, data): """ Executes the HTTP POST request :param endpoint: string indicating the URL component to call :param data: the data to submit :return: the dumped JSON response content """ headers = { "Content-Type": "application/json", "Accept": "application/json", "x-standardize-only": "true" if self.standardize else "false", "x-include-invalid": "true" if self.invalid else "false", "x-accept-keypair": "true" if self.accept_keypair else "false", } if not self.logging: headers["x-suppress-logging"] = "true" params = {"auth-id": self.auth_id, "auth-token": self.auth_token} url = self.BASE_URL + endpoint response = self.session.post( url, json.dumps(stringify(data)), params=params, headers=headers, timeout=self.timeout, ) if response.status_code == 200: return response.json() raise ERROR_CODES.get(response.status_code, SmartyStreetsError)
https://github.com/bennylope/smartystreets.py/blob/f45e37dd52ea7cec8ed43ce2b64724beb6dbbb69/smartystreets/client.py#L128-L158
httpclient post json
python
def post(self, path, params='', data=None): """ POST Method Wrapper of the REST API """ self.result = None data = data or {} headers = {'Content-Type': 'application/json', 'x-qx-client-application': self.client_application} url = str(self.credential.config['url'] + path + '?access_token=' + self.credential.get_token() + params) retries = self.retries while retries > 0: respond = requests.post(url, data=data, headers=headers, verify=self.verify, **self.extra_args) if not self.check_token(respond): respond = requests.post(url, data=data, headers=headers, verify=self.verify, **self.extra_args) if self._response_good(respond): if self.result: return self.result elif retries < 2: return respond.json() else: retries -= 1 else: retries -= 1 time.sleep(self.timeout_interval) # timed out raise ApiError(usr_msg='Failed to get proper ' + 'response from backend.')
https://github.com/Qiskit/qiskit-api-py/blob/2ab240110fb7e653254e44c4833f3643e8ae7f0f/IBMQuantumExperience/IBMQuantumExperience.py#L273-L305
httpclient post json
python
def put_json(self, uri, data, **kwargs): """PUT the provided data as json to the specified path See :meth:`request` for additional details. """ encoded_data = json.dumps(data) kwargs.setdefault("headers", {}).update({ "Content-Type": "application/json", # tell server we are sending json }) return self.put(uri, data=encoded_data, **kwargs)
https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/http_client.py#L164-L173
httpclient post json
python
def _get_json(self, url): """ Get json from url """ self.log.info(u"/GET " + url) r = requests.get(url) if hasattr(r, 'from_cache'): if r.from_cache: self.log.info("(from cache)") if r.status_code != 200: throw_request_err(r) return r.json()
https://github.com/jplusplus/statscraper/blob/932ec048b23d15b3dbdaf829facc55fd78ec0109/statscraper/scrapers/VantetiderScraper.py#L163-L174
httpclient post json
python
def post_request(self, url, params): """Send a post request. :return: a dict or raise Exception. """ data = encrypted_request(params) resp = self.session.post(url, data=data, timeout=self.timeout, proxies=self.proxies) result = resp.json() if result['code'] != 200: LOG.error('Return %s when try to post %s => %s', result, url, params) raise PostRequestIllegal(result) else: return result
https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L86-L101
httpclient post json
python
def _api_post(self, url, **kwargs): """ Convenience method for posting """ response = self.session.post( url=url, headers=self._get_api_headers(), **kwargs ) if not response.ok: raise ServerException( '{0}: {1}'.format( response.status_code, response.text or response.reason )) return response.json()
https://github.com/ambitioninc/python-logentries-api/blob/77ff1a7a2995d7ea2725b74e34c0f880f4ee23bc/logentries_api/special_alerts.py#L274-L289
httpclient post json
python
def post(self): """ Makes the HTTP POST to the url sending post_data. """ self._construct_post_data() post_args = {"json": self.post_data} self.http_method_args.update(post_args) return self.http_method("POST")
https://github.com/RIPE-NCC/ripe-atlas-cousteau/blob/ffee2556aaa4df86525b88c269bb098de11678ec/ripe/atlas/cousteau/request.py#L117-L126
httpclient post json
python
def do_POST(self): """ Perform a POST request """ # Doesn't do anything with posted data # print "uri: ", self.client_address, self.path self.do_initial_operations() payload = self.coap_uri.get_payload() if payload is None: logger.error("BAD POST REQUEST") self.send_error(BAD_REQUEST) return coap_response = self.client.post(self.coap_uri.path, payload) self.client.stop() logger.info("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response)
https://github.com/Tanganelli/CoAPthon3/blob/985763bfe2eb9e00f49ec100c5b8877c2ed7d531/coapthon/http_proxy/http_coap_proxy.py#L148-L163
httpclient post json
python
def http_post(self, url, data=None): """POST to URL and get result as a response object. :param url: URL to POST. :type url: str :param data: Data to send in the form body. :type data: str :rtype: requests.Response """ if not url.startswith('https://'): raise ValueError('Protocol must be HTTPS, invalid URL: %s' % url) return requests.post(url, data, verify=True)
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/client.py#L36-L47
httpclient post json
python
def post_json(url, **kwargs): """ ASSUME RESPONSE IN IN JSON """ if 'json' in kwargs: kwargs['data'] = unicode2utf8(value2json(kwargs['json'])) del kwargs['json'] elif 'data' in kwargs: kwargs['data'] = unicode2utf8(value2json(kwargs['data'])) else: Log.error(u"Expecting `json` parameter") response = post(url, **kwargs) details = json2value(utf82unicode(response.content)) if response.status_code not in [200, 201, 202]: if "template" in details: Log.error(u"Bad response code {{code}}", code=response.status_code, cause=Except.wrap(details)) else: Log.error(u"Bad response code {{code}}\n{{details}}", code=response.status_code, details=details) else: return details
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/env/http.py#L223-L243
httpclient post json
python
def POST(self, *args, **kwargs): """ POST request """ return self._handle_api(self.API_POST, args, kwargs)
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L27-L29
httpclient post json
python
def post(self, path, body): """POST request.""" return self._make_request('post', self._format_url(API_ROOT + path), { 'json': body })
https://github.com/mattbierner/blotre-py/blob/c98228d1159bc651aad546e442b0acbf97b1e043/blotre.py#L241-L246
httpclient post json
python
def post(self, url, postParameters=None, urlParameters=None): """ Implement libgreader's interface for authenticated POST request """ if self._action_token == None: self._action_token = self.get(ReaderUrl.ACTION_TOKEN_URL) if self._http == None: self._setupHttp() uri = url + "?" + self.getParameters(urlParameters) postParameters.update({'T':self._action_token}) body = self.postParameters(postParameters) response, content = self._http.request(uri, "POST", body=body) return content
https://github.com/askedrelic/libgreader/blob/7b668ee291c2464ea172ef44393100c369efa970/libgreader/auth.py#L374-L387
httpclient post json
python
def _post(self, url, data={}): """Wrapper around request.post() to use the API prefix. Returns a JSON response.""" r = requests.post(self._api_prefix + url, data=json.dumps(data), headers=self.headers, auth=self.auth, allow_redirects=False, ) return self._action(r)
https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v1/api.py#L264-L272
httpclient post json
python
def _post(self, *args, **kwargs): """ A wrapper for posting things. It will also json encode your 'data' parameter :returns: The response of your post :rtype: dict """ if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) response = requests.post(*args, **kwargs) response.raise_for_status()
https://github.com/ambitioninc/rabbitmq-admin/blob/ff65054115f19991da153f0e4f4e45e526545fea/rabbitmq_admin/base.py#L100-L110
httpclient post json
python
def json(self, data): """Set the POST/PUT body content in JSON format for this request.""" if data is not None: self._body = json.dumps(data) self.add_header('Content-Type', 'application/json')
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_request.py#L77-L81
httpclient post json
python
def send_json(self, obj, status=200): """ Sends a stringified JSON response to client. Automatically sets the content-type header to application/json. Parameters ---------- obj : mixed Any object which will be serialized by the json.dumps module function status : int, optional The HTTP status code, defaults to 200 (OK) """ self.headers['Content-Type'] = 'application/json' self.status_code = status message = json.dumps(obj) self.send_text(message)
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L171-L187
httpclient post json
python
def post(self, request, *args, **kwargs): """ Return a response to the statement in the posted data. * The JSON data should contain a 'text' attribute. """ input_data = json.loads(request.body.decode('utf-8')) if 'text' not in input_data: return JsonResponse({ 'text': [ 'The attribute "text" is required.' ] }, status=400) response = self.chatterbot.get_response(input_data) response_data = response.serialize() return JsonResponse(response_data, status=200)
https://github.com/gunthercox/ChatterBot/blob/1a03dcb45cba7bdc24d3db5e750582e0cb1518e2/examples/django_app/example_app/views.py#L20-L39
httpclient post json
python
def post(self, url, data): """Send a HTTP POST request to a URL and return the result. """ headers = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/json" } self.conn.request("POST", url, data, headers) return self._process_response()
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/httpclient.py#L54-L62
httpclient post json
python
def _post(self, *args, **kwargs): """ A wrapper for posting things. It will also json encode your 'data' parameter :returns: The response of your post :rtype: dict :raises: This will raise a :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>` if there is an error from New Relic """ if 'data' in kwargs: kwargs['data'] = json.dumps(kwargs['data']) response = requests.post(*args, **kwargs) if not response.ok: raise NewRelicAPIServerException('{}: {}'.format(response.status_code, response.text)) return response.json()
https://github.com/ambitioninc/newrelic-api/blob/07b4430aa6ae61e4704e2928a6e7a24c76f0f424/newrelic_api/base.py#L75-L92
httpclient post json
python
async def create_post_request(self, method: str, params: Dict = None): """Call the given method over POST. :param method: Name of the method :param params: dict of parameters :return: JSON object """ if params is None: params = {} headers = {"Content-Type": "application/json"} payload = { "method": method, "params": [params], "id": next(self.idgen), "version": "1.0", } if self.debug > 1: _LOGGER.debug("> POST %s with body: %s", self.guide_endpoint, payload) async with aiohttp.ClientSession(headers=headers) as session: res = await session.post(self.guide_endpoint, json=payload, headers=headers) if self.debug > 1: _LOGGER.debug("Received %s: %s" % (res.status_code, res.text)) if res.status != 200: raise SongpalException( "Got a non-ok (status %s) response for %s" % (res.status, method), error=await res.json()["error"], ) res = await res.json() # TODO handle exceptions from POST? This used to raise SongpalException # on requests.RequestException (Unable to get APIs). if "error" in res: raise SongpalException("Got an error for %s" % method, error=res["error"]) if self.debug > 1: _LOGGER.debug("Got %s: %s", method, pf(res)) return res
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L74-L115
httpclient post json
python
def json(self): """ Return an object representing the return json for the request """ try: return self._json except AttributeError: try: self._json = json.loads(self.text) return self._json except: # noqa e722 raise RequestInvalidJSON("Invalid JSON received")
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/request.py#L118-L129
httpclient post json
python
def post(self, url, data, charset=CHARSET_UTF8, headers={}): '''response json text''' 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)
https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/ypclient.py#L185-L193
httpclient post json
python
def post(self): """ The HTTP-Post endpoint """ logger.info("--- In SSO POST ---") saml_msg = self.unpack_either() self.req_info = IDP.parse_authn_request( saml_msg["SAMLRequest"], BINDING_HTTP_POST) _req = self.req_info.message if self.user: if _req.force_authn: saml_msg["req_info"] = self.req_info key = self._store_request(saml_msg) return self.not_authn(key, _req.requested_authn_context) else: return self.operation(saml_msg, BINDING_HTTP_POST) else: saml_msg["req_info"] = self.req_info key = self._store_request(saml_msg) return self.not_authn(key, _req.requested_authn_context)
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/example/idp2/idp_uwsgi.py#L391-L410
httpclient post json
python
def post(self, endpoint, json=None, params=None, **kwargs): """POST to DHIS2 :param endpoint: DHIS2 API endpoint :param json: HTTP payload :param params: HTTP parameters :return: requests.Response object """ json = kwargs['data'] if 'data' in kwargs else json return self._make_request('post', endpoint, data=json, params=params)
https://github.com/davidhuser/dhis2.py/blob/78cbf1985506db21acdfa0f2e624bc397e455c82/dhis2/api.py#L253-L261
httpclient post json
python
def post_url(self, url, token='', json=None, data=None, headers=None): """ Returns a post resquest object taking in a url, user token, and possible json information. Arguments: url (str): The url to make post to token (str): The authentication token json (dict): json info to send Returns: obj: Post request object """ if (token == ''): token = self._user_token if headers: headers.update({'Authorization': 'Token {}'.format(token)}) else: headers = {'Authorization': 'Token {}'.format(token)} if json: return requests.post(url, headers=headers, json=json, verify=False) if data: return requests.post(url, headers=headers, data=data, verify=False) return requests.post(url, headers=headers, verify=False)
https://github.com/neurodata/ndio/blob/792dd5816bc770b05a3db2f4327da42ff6253531/ndio/remote/remote_utils.py#L44-L78
httpclient post json
python
def __request(self, url, params): """ Make an HTTP POST request to the server and return JSON data. :param url: HTTP URL to object. :returns: Response as dict. """ log.debug('request: %s %s' %(url, str(params))) try: response = urlopen(url, urlencode(params)).read() if params.get('action') != 'data': log.debug('response: %s' % response) if params.get('action', None) == 'data': return response else: return json.loads(response) except TypeError, e: log.exception('request error') raise ServerError(e) except IOError, e: log.error('request error: %s' % str(e)) raise ServerError(e)
https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/proxy.py#L90-L112
httpclient post json
python
def _do_post(self): """ HTTP Post Request """ return requests.post(self._url, data=self._data, headers=self._headers, auth=(self._email, self._api_token))
https://github.com/boundary/pulse-api-cli/blob/b01ca65b442eed19faac309c9d62bbc3cb2c098f/boundary/api_call.py#L198-L202
httpclient post json
python
def _post(self, url, data={}, **kwargs): """Wrapper around request.post() to use the API prefix. Returns a JSON response.""" if 'files' in kwargs: req = self._session.post(self._api_prefix + url, auth=self._session.auth, data=data, **kwargs) return self._action(req) req = self._session.post(self._api_prefix + url, data=data, **kwargs) return self._action(req)
https://github.com/sjkingo/python-freshdesk/blob/39edca5d86e73de5619b1d082d9d8b5c0ae626c8/freshdesk/v2/api.py#L447-L454
httpclient post json
python
def post_public(self, path, data, is_json=True): '''Make a post request requiring no auth.''' return self._post(path, data, is_json)
https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/client.py#L89-L91
httpclient post json
python
def post(self, endpoint, message): """ Todo """ r = self.http.request('POST', self._api_base.format(endpoint), headers={'Content-Type': 'application/json', 'Authorization': 'Bot '+self.token}, body=message.encode('utf-8'))
https://github.com/askovpen/discord_simple/blob/6dff3a94b63bb3657fae8b16e3d03f944afee71b/discord_simple/transport.py#L56-L62
httpclient post json
python
def _http_request(self, api, data, headers=None): """ internal method for handling request and response and raising an exception is http return status code is not success :rtype : response object from requests.post() """ if not headers: headers = {'Content-Type': 'application/json'} if not self._token_valid: self._token = self.get_token(self._app_name, self._username, self._password) response = requests.post(self._base_url + '/' + api, data=json.dumps(data), headers=headers) # raise an exception if the status was not 200 logger.debug(json.dumps(data)) logger.debug(response.text) response.raise_for_status() return response
https://github.com/farshidce/touchworks-python/blob/ea8f93a0f4273de1317a318e945a571f5038ba62/touchworks/api/http.py#L178-L195
httpclient post json
python
async def requests_post(self, path: str, **kwargs) -> ClientResponse: """ Requests POST wrapper in order to use API parameters. :param path: the request path :return: """ if 'self_' in kwargs: kwargs['self'] = kwargs.pop('self_') logging.debug("POST : {0}".format(kwargs)) response = await self.connection_handler.session.post( self.reverse_url(self.connection_handler.http_scheme, path), data=kwargs, headers=self.headers, proxy=self.connection_handler.proxy, timeout=15 ) return response
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/client.py#L148-L166
httpclient post json
python
async def receive_json(self, content: typing.Dict, **kwargs): """ Called with decoded JSON content. """ # TODO assert format, if does not match return message. request_id = content.pop('request_id') action = content.pop('action') await self.handle_action(action, request_id=request_id, **content)
https://github.com/hishnash/djangochannelsrestframework/blob/19fdec7efd785b1a94d19612a8de934e1948e344/djangochannelsrestframework/consumers.py#L170-L177
httpclient post json
python
def post(self, path, body, headers=None): """Perform a POST request, providing a body, which will be JSON-encoded. Args: path (str): A path that gets appended to ``base_url``. body (dict): Dictionary that will be JSON-encoded and sent as the body. Example: api_client.post('/users', body={'name': 'Billy Jean'}) Returns: A requests ``Response`` object. """ response = requests.post( self._url_for(path), data=json.dumps(body), headers=self._headers(headers) ) self._handle_errors(response) return response
https://github.com/gocardless/gocardless-pro-python/blob/7b57f037d14875eea8d659084eeb524f3ce17f4a/gocardless_pro/api_client.py#L51-L71
httpclient post json
python
def _post(self, *args, **kwargs): """ Make a POST request. """ data = self._default_data() data.update(kwargs.get('data') or {}) kwargs['data'] = data return self._request(requests.post, *args, **kwargs)
https://github.com/kmadac/bitstamp-python-client/blob/35b9a61f3892cc281de89963d210f7bd5757c717/bitstamp/client.py#L41-L48
httpclient post json
python
def fetch_json(self, method, url, data=None, expected_status_code=None): """Return json decoded data from fetch """ return self.fetch(method, url, data, expected_status_code).json()
https://github.com/mozilla/Marketplace.Python/blob/88176b12201f766b6b96bccc1e4c3e82f0676283/marketplace/connection.py#L81-L84
httpclient post json
python
def _post_response(self, params): """ wrap a post call to the requests package """ return self._session.post( self._api_url, data=params, timeout=self._timeout ).json(encoding="utf8")
https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L903-L907
httpclient post json
python
def POST_query(self, req_hook, req_args): ''' Generic POST query method ''' # HTTP POST queries require keyManagerTokens and sessionTokens headers = {'Content-Type': 'application/json', 'sessionToken': self.__session__, 'keyManagerToken': self.__keymngr__} # HTTP POST query to keymanager authenticate API try: if req_args is None: response = requests.post(self.__url__ + req_hook, headers=headers, verify=True) else: response = requests.post(self.__url__ + req_hook, headers=headers, data=req_args, verify=True) except requests.exceptions.RequestException as err: self.logger.error(err) return '500', 'Internal Error in RESTful.POST_query()' # return the token return response.status_code, response.text
https://github.com/symphonyoss/python-symphony/blob/b939f35fbda461183ec0c01790c754f89a295be0/symphony/RESTful/nopkcs.py#L43-L65
httpclient post json
python
def _request(self, path, method, body=None): """Make a request from the API.""" url = '/'.join([_SERVER, path]) (resp, content) = _HTTP.request(url, method, headers=self._headers, body=body) content_type = resp.get('content-type') if content_type and content_type.startswith('application/json'): content = json.loads(content.decode('UTF-8')) return (resp, content)
https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/__init__.py#L32-L42
httpclient post json
python
def post(self, request, data=None): """ Used to make post calls to mattermost api :param request: :param data: :return: """ headers = {"Authorization": "Bearer " + self.token } logging.debug(json.dumps(data, indent=4)) p = requests.post(self.url + request, headers=headers, data=json.dumps(data)) return json.loads(p.text)
https://github.com/btotharye/mattermostwrapper/blob/d1eedee40f697246dd56caf6df233e77c48ddbb3/mattermostwrapper/wrapper.py#L23-L33
httpclient post json
python
def json_post(methodname, rtype, key): """decorator factory for json POST queries""" return compose( reusable, map_return(registry(rtype), itemgetter(key)), basic_interaction, map_yield(partial(_json_as_post, methodname)), oneyield, )
https://github.com/ariebovenberg/snug/blob/4f5cd30e6b7b2c3f0ad3cc10be865bd8900b38ef/examples/slack/query.py#L62-L70
httpclient post json
python
def post(self, path, data=None): """Encapsulates POST requests""" data = data or {} response = requests.post(self.url(path), data=to_json(data), headers=self.request_header()) return self.parse_response(response)
https://github.com/marvin-ai/marvin-python-toolbox/blob/7c95cb2f9698b989150ab94c1285f3a9eaaba423/marvin_python_toolbox/common/http_client.py#L111-L115
httpclient post json
python
def get_json(url, **kwargs): """ ASSUME RESPONSE IN IN JSON """ response = get(url, **kwargs) try: c = response.all_content return json2value(utf82unicode(c)) except Exception as e: if mo_math.round(response.status_code, decimal=-2) in [400, 500]: Log.error(u"Bad GET response: {{code}}", code=response.status_code) else: Log.error(u"Good GET requests, but bad JSON", cause=e)
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/pyLibrary/env/http.py#L196-L208
httpclient post json
python
def post(self, endpoint, return_response=False, **kwargs): """Send HTTP POST to the endpoint. :arg str endpoint: The endpoint to send to. :returns: JSON decoded result. :raises: requests.RequestException on timeout or connection error. """ args = self.translate_kwargs(**kwargs) response = self.session.post(self.make_url(endpoint), **args) decoded_response = _decode_response(response) if return_response: return decoded_response, response return decoded_response
https://github.com/dpursehouse/pygerrit2/blob/141031469603b33369d89c38c703390eb3786bd0/pygerrit2/rest/__init__.py#L197-L216
httpclient post json
python
async def post(self): """ Accepts json-rpc post request. Retrieves data from request body. Calls defined method in field 'method_name' """ request = self.request.body.decode() response = await methods.dispatch(request) if not response.is_notification: self.write(response)
https://github.com/Robin8Put/pmes/blob/338bec94162098f05b75bad035417317e1252fd2/history/ClickHouse/views.py#L101-L111
httpclient post json
python
def request( self, method, path, data=None, files=None, json=None, params=None ): """Return the json content from the resource at ``path``. :param method: The request verb. E.g., get, post, put. :param path: The path of the request. This path will be combined with the ``oauth_url`` of the Requestor. :param data: Dictionary, bytes, or file-like object to send in the body of the request. :param files: Dictionary, mapping ``filename`` to file-like object. :param json: Object to be serialized to JSON in the body of the request. :param params: The query parameters to send with the request. Automatically refreshes the access token if it becomes invalid and a refresh token is available. Raises InvalidInvocation in such a case if a refresh token is not available. """ params = deepcopy(params) or {} params["raw_json"] = 1 if isinstance(data, dict): data = deepcopy(data) data["api_type"] = "json" data = sorted(data.items()) url = urljoin(self._requestor.oauth_url, path) return self._request_with_retries( data=data, files=files, json=json, method=method, params=params, url=url, )
https://github.com/praw-dev/prawcore/blob/b16ae88a1f2bf98095ed6fe64851cb7add7ed752/prawcore/sessions.py#L226-L260
httpclient post json
python
def _post(self, path, **kwargs): """ return a dict. """ # clean kwargs (filter None and empty string) clean_kwargs = clean_dict(kwargs) data = bytes(json.dumps(clean_kwargs), encoding='UTF-8') # change content type on post self._headers['Content-Type'] = 'application/json' api = self._api('%s.json' % path) req = request.Request( api, headers=self._headers, data=data, method='POST') try: resp = request.urlopen(req, data).read() except urllib.error.HTTPError as e: resp = e.fp.read() # reset content type self._headers['Content-Type'] = 'text/json' return json.loads(resp.decode())
https://github.com/damnit/pymite/blob/1e9b9bf6aef790af2d8781f9f77c098c54ca0342/pymite/mite.py#L77-L94
httpclient post json
python
def post(self, endpoint, data, files=None, headers=None): # pylint: disable=unused-argument """ Create a new item :param endpoint: endpoint (API URL) :type endpoint: str :param data: properties of item to create :type data: dict :param files: Not used. To be implemented :type files: None :param headers: headers (example: Content-Type) :type headers: dict :return: response (creation information) :rtype: dict """ # We let Requests encode data to json response = self.get_response(method='POST', endpoint=endpoint, json=data, headers=headers) resp = self.decode(response=response) return resp
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L251-L272
httpclient post json
python
def post(self, url, data, params=None): """ Initiate a POST request """ r = self.session.post(url, data=data, params=params) return self._response_parser(r, expect_json=False)
https://github.com/shichao-an/115wangpan/blob/e7cc935313f675e886bceca831fcffcdedf1e880/u115/api.py#L63-L68
httpclient post json
python
async def post(self, path, data={}, send_raw=False, **params): '''sends post request Parameters ---------- path : str same as get_url query : kargs dict additional info to pass to get_url See Also -------- get_url : Returns ------- requests.models.Response the response that was given ''' url = self.get_url(path, **params) jstr = json.dumps(data) for i in range(self.tries+1): try: if send_raw: resp = await self.session.post(url, data=data, timeout=self.timeout) else: resp = await self.session.post(url, data=jstr, timeout=self.timeout) if await self._process_resp(resp): return resp else: continue except aiohttp.ClientConnectionError: if i >= self.tries: raise aiohttp.ClientConnectionError( 'Emby server is probably down' )
https://github.com/andy29485/embypy/blob/cde658d380965caaf4789d4d182d045b0346797b/embypy/utils/connector.py#L339-L375
httpclient post json
python
def to_json(self): """Short cut for JSON response service data. Returns: Dict that implements JSON interface. """ web_resp = collections.OrderedDict() web_resp['status_code'] = self.status_code web_resp['status_text'] = dict(HTTP_CODES).get(self.status_code) web_resp['data'] = self.data if self.data is not None else {} web_resp['errors'] = self.errors or [] return web_resp
https://github.com/agile4you/bottle-neck/blob/ebc670a4b178255473d68e9b4122ba04e38f4810/bottle_neck/response.py#L294-L308
httpclient post json
python
def _do_POSTGET(self, handler): """handle an HTTP request""" # 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'))
https://github.com/knipknap/exscript/blob/72718eee3e87b345d5a5255be9824e867e42927b/Exscript/servers/httpd.py#L220-L249
httpclient post json
python
def post(self, result_id, project_id): """POST /api/v1/results/<int:id>/commands.""" result = db.session.query(Result).filter_by(id=result_id).first() if result is None: return jsonify({ 'result': None, 'message': 'No interface defined for URL.' }), 404 job_status = CommandsState.job_status(result.path_name) if job_status != JobStatus.RUNNING: if job_status == JobStatus.NO_EXTENSION_ERROR: return jsonify({ 'message': '\'CommandsExtension\' is not set or disabled.' }), 400 elif job_status == JobStatus.INITIALIZED: return jsonify({ 'message': 'The target training job has not run, yet' }), 400 elif job_status == JobStatus.STOPPED: return jsonify({ 'message': 'The target training job has already stopped' }), 400 else: return jsonify({ 'message': 'Cannot get the target training job status' }), 400 request_json = request.get_json() if request_json is None: return jsonify({ 'message': 'Empty request.' }), 400 command_name = request_json.get('name', None) if command_name is None: return jsonify({ 'message': 'Name is required.' }), 400 schedule = request_json.get('schedule', None) if not CommandItem.is_valid_schedule(schedule): return jsonify({ 'message': 'Schedule is invalid.' }), 400 command = CommandItem( name=command_name, ) command.set_request( CommandItem.REQUEST_OPEN, request_json.get('body', None), request_json.get('schedule', None) ) commands = CommandItem.load_commands(result.path_name) commands.append(command) CommandItem.dump_commands(commands, result.path_name) new_result = crawl_result(result, force=True) new_result_dict = new_result.serialize return jsonify({'commands': new_result_dict['commands']})
https://github.com/chainer/chainerui/blob/87ad25e875bc332bfdad20197fd3d0cb81a078e8/chainerui/views/result_command.py#L16-L82
httpclient post json
python
def post(self, resource, data=None, **kwargs): """Shortcut for ``request('POST', resource)``. Use this to make POST request since it will also encode ``data`` to 'application/json' format.""" headers = dict(kwargs.pop('headers', {})) headers.setdefault('Content-Type', 'application/json') data = json.dumps(data) return self.request('POST', resource, headers=headers, data=data, **kwargs)
https://github.com/cenkalti/github-flask/blob/9f58d61b7d328cef857edbb5c64a5d3f716367cb/flask_github.py#L287-L295
httpclient post json
python
def get_json(url, post_values=None, headers=None): """ Download request as JSON data type :param url: url to Sentinel Hub's services or other sources from where the data is downloaded :type url: str :param post_values: form encoded data to send in POST request. Default is ``None`` :type post_values: dict :param headers: add HTTP headers to request. Default is ``None`` :type headers: dict :return: request response as JSON instance :rtype: JSON instance or None :raises: RunTimeError """ json_headers = {} if headers is None else headers.copy() if post_values is None: request_type = RequestType.GET else: request_type = RequestType.POST json_headers = {**json_headers, **{'Content-Type': MimeType.get_string(MimeType.JSON)}} request = DownloadRequest(url=url, headers=json_headers, request_type=request_type, post_values=post_values, save_response=False, return_data=True, data_type=MimeType.JSON) return execute_download_request(request)
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L463-L488
httpclient post json
python
def post(self, path, data=None, json=None, headers=None, **kwargs): """ Sends a POST request to host/path. :param path: String, resource path on server :param data: Dictionary, bytes or file-like object to send in the body of the request :param json: JSON formatted data to send in the body of the request :param headers: Dictionary of HTTP headers to be sent with the request, overwrites default headers if there is overlap :param kwargs: Other arguments used in the requests.request call valid parameters in kwargs are the optional parameters of Requests.Request http://docs.python-requests.org/en/master/api/ :return: requests.Response :raises: RequestException """ if headers is not None: merger = jsonmerge.Merger(SCHEMA) kwargs["headers"] = merger.merge(self.defaultHeaders, headers) else: kwargs["headers"] = self.defaultHeaders url = combine_urls(self.host, path) if self.cert is not None: kwargs["cert"] = self.cert self.logger.debug("Trying to send HTTP POST to {}".format(url)) try: resp = requests.post(url, data, json, **kwargs) self._log_response(resp) except requests.RequestException as es: self._log_exception(es) raise return resp
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/tools/HTTP/Api.py#L136-L170
httpclient post json
python
def post(self, request, response): """Processes a `POST` request.""" if self.slug is not None: # Don't know what to do an item access. raise http.exceptions.NotImplemented() # Ensure we're allowed to create a resource. self.assert_operations('create') # Deserialize and clean the incoming object. data = self._clean(None, self.request.read(deserialize=True)) # Delegate to `create` to create the item. item = self.create(data) # Build the response object. self.response.status = http.client.CREATED self.make_response(item)
https://github.com/armet/python-armet/blob/d61eca9082256cb1e7f7f3c7f2fbc4b697157de7/armet/resources/managed/base.py#L360-L377
httpclient post json
python
def post_public_key(self, path, data, is_json=True): '''Make a post request using a public key.''' post_data = { 'public_key': self.public_key } post_data.update(data) return self._post(path, post_data, is_json)
https://github.com/plaid/plaid-python/blob/c549c3108790266a3b344c47e0c83fff59146eeb/plaid/client.py#L93-L99
httpclient post json
python
def post(self, path, args, wait=False): """POST an HTTP request to a daemon :param path: path to do the request :type path: str :param args: args to add in the request :type args: dict :param wait: True for a long timeout :type wait: bool :return: Content of the HTTP response if server returned 200 :rtype: str """ uri = self.make_uri(path) timeout = self.make_timeout(wait) for (key, value) in list(args.items()): args[key] = serialize(value, True) try: logger.debug("post: %s, timeout: %s, params: %s", uri, timeout, args) rsp = self._requests_con.post(uri, json=args, timeout=timeout, verify=self.strong_ssl) logger.debug("got: %d - %s", rsp.status_code, rsp.text) if rsp.status_code != 200: raise HTTPClientDataException(rsp.status_code, rsp.text, uri) return rsp.content except (requests.Timeout, requests.ConnectTimeout): raise HTTPClientTimeoutException(timeout, uri) except requests.ConnectionError as exp: raise HTTPClientConnectionException(uri, exp.args[0]) except Exception as exp: raise HTTPClientException('Request error to %s: %s' % (uri, exp))
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/client.py#L219-L247
httpclient post json
python
def _http_request(url, headers=None, data=None): ''' Make the HTTP request and return the body as python object. ''' if not headers: headers = _get_headers() session = requests.session() log.debug('Querying %s', url) req = session.post(url, headers=headers, data=salt.utils.json.dumps(data)) req_body = req.json() ret = _default_ret() log.debug('Status code: %d', req.status_code) log.debug('Response body:') log.debug(req_body) if req.status_code != 200: if req.status_code == 500: ret['comment'] = req_body.pop('message', '') ret['out'] = req_body return ret ret.update({ 'comment': req_body.get('error', '') }) return ret ret.update({ 'result': True, 'out': req.json() }) return ret
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mandrill.py#L101-L132
httpclient post json
python
def submission_to_json(self, task, data, debug, reloading=False, replace=False, tags={}): """ Converts a submission to json (keeps only needed fields) """ if "ssh_host" in data: return json.dumps({'status': "waiting", 'text': "<b>SSH server active</b>", 'ssh_host': data["ssh_host"], 'ssh_port': data["ssh_port"], 'ssh_password': data["ssh_password"]}) # Here we are waiting. Let's send some useful information. waiting_data = self.submission_manager.get_job_queue_info(data["jobid"]) if "jobid" in data else None if waiting_data is not None and not reloading: nb_tasks_before, approx_wait_time = waiting_data wait_time = round(approx_wait_time) if nb_tasks_before == -1 and wait_time <= 0: text = _("<b>INGInious is currently grading your answers.<b/> (almost done)") elif nb_tasks_before == -1: text = _("<b>INGInious is currently grading your answers.<b/> (Approx. wait time: {} seconds)").format( wait_time) elif nb_tasks_before == 0: text = _("<b>You are next in the waiting queue!</b>") elif nb_tasks_before == 1: text = _("<b>There is one task in front of you in the waiting queue.</b>") else: text = _("<b>There are {} tasks in front of you in the waiting queue.</b>").format(nb_tasks_before) return json.dumps({'status': "waiting", 'text': text}) tojson = { 'status': data['status'], 'result': data.get('result', 'crash'), 'id': str(data["_id"]), 'submitted_on': str(data['submitted_on']), 'grade': str(data.get("grade", 0.0)), 'replace': replace and not reloading # Replace the evaluated submission } if "text" in data: tojson["text"] = data["text"] if "problems" in data: tojson["problems"] = data["problems"] if debug: tojson["debug"] = data if tojson['status'] == 'waiting': tojson["text"] = _("<b>Your submission has been sent...</b>") elif tojson["result"] == "failed": tojson["text"] = _("There are some errors in your answer. Your score is {score}%.").format(score=data["grade"]) elif tojson["result"] == "success": tojson["text"] = _("Your answer passed the tests! Your score is {score}%.").format(score=data["grade"]) elif tojson["result"] == "timeout": tojson["text"] = _("Your submission timed out. Your score is {score}%.").format(score=data["grade"]) elif tojson["result"] == "overflow": tojson["text"] = _("Your submission made an overflow. Your score is {score}%.").format(score=data["grade"]) elif tojson["result"] == "killed": tojson["text"] = _("Your submission was killed.") else: tojson["text"] = _("An internal error occurred. Please retry later. " "If the error persists, send an email to the course administrator.") tojson["text"] = "<b>" + tojson["text"] + " " + _("[Submission #{submissionid}]").format(submissionid=data["_id"]) + "</b>" + data.get("text", "") tojson["text"] = self.plugin_manager.call_hook_recursive("feedback_text", task=task, submission=data, text=tojson["text"])["text"] if reloading: # Set status='ok' because we are reloading an old submission. tojson["status"] = 'ok' # And also include input tojson["input"] = data.get('input', {}) if "tests" in data: tojson["tests"] = {} if tags: for tag in tags[0]+tags[1]: # Tags only visible for admins should not appear in the json for students. if (tag.is_visible_for_student() or debug) and tag.get_id() in data["tests"]: tojson["tests"][tag.get_id()] = data["tests"][tag.get_id()] if debug: #We add also auto tags when we are admin for tag in data["tests"]: if tag.startswith("*auto-tag-"): tojson["tests"][tag] = data["tests"][tag] # allow plugins to insert javascript to be run in the browser after the submission is loaded tojson["feedback_script"] = "".join(self.plugin_manager.call_hook("feedback_script", task=task, submission=data)) return json.dumps(tojson, default=str)
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/tasks.py#L291-L374