Python requests.patch() Examples
The following are 30
code examples of requests.patch().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
requests
, or try the search function
.
Example #1
Source File: callback_role.py From spilo with Apache License 2.0 | 6 votes |
def api_patch(namespace, kind, name, entity_name, body): api_url = '/'.join([KUBE_API_URL, namespace, kind, name]) while True: try: token = read_token() if token: r = requests.patch(api_url, data=body, verify=KUBE_CA_CERT, headers={'Content-Type': 'application/strategic-merge-patch+json', 'Authorization': 'Bearer {0}'.format(token)}) if r.status_code >= 300: logger.warning('Unable to change %s: %s', entity_name, r.text) else: break else: logger.warning('Unable to read Kubernetes authorization token') except requests.exceptions.RequestException as e: logger.warning('Exception when executing PATCH on %s: %s', api_url, e) time.sleep(1)
Example #2
Source File: firebase.py From pyfirebase with MIT License | 6 votes |
def run(self): try: self.sse = ClosableSSEClient(self.url) for msg in self.sse: event = msg.event if event is not None and event in ('put', 'patch'): response = json.loads(msg.data) if response is not None: # Default to CHILD_CHANGED event occurred_event = FirebaseEvents.CHILD_CHANGED if response['data'] is None: occurred_event = FirebaseEvents.CHILD_DELETED # Get the event I'm trying to listen to ev = FirebaseEvents.id(self.event_name) if occurred_event == ev or ev == FirebaseEvents.CHILD_CHANGED: self.callback(event, response) except socket.error: pass
Example #3
Source File: scp_api.py From single_cell_portal with BSD 3-Clause "New" or "Revised" License | 6 votes |
def do_patch(self, command, values, dry_run=False): ''' Perform PATCH :param command: String PATCH command to send to the REST endpoint :param values: Parameter values to send {name: value} :param dry_run: If true, will do a dry run with no actual execution of functionality. :return: Dict with response and status code/status ''' ## TODO add timeout and exception handling (Timeout exeception) if self.verbose: print("DO PATCH") print(command) print(values) if dry_run: return({c_SUCCESS_RET_KEY: True,c_CODE_RET_KEY: c_API_OK}) head = {c_AUTH: 'token {}'.format(self.token), 'Accept': 'application/json'} return(self.check_api_return(requests.patch(command, headers=head, json=values, verify=self.verify_https)))
Example #4
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def run(self, params={}): user_principal_name = params.get(Input.USER_PRINCIPAL_NAME) location = params.get(Input.LOCATION) token = self.connection.access_token base_url = "https://graph.microsoft.com/v1.0/users/%s" % user_principal_name headers = {"Authorization": "Bearer %s" % token, "Content-Type": "application/json",} body = { "usageLocation": location } try: response = requests.patch(base_url, json=body, headers=headers) except requests.HTTPError: raise PluginException(cause=f"There was an issue updating the user's location. Double-check the user name: {user_principal_name}", data=response.text) if response.status_code == 204: return {Output.SUCCESS: True} else: raise PluginException(f"The response from Office365 indicated something went wrong: {response.status_code}", data=response.text)
Example #5
Source File: webclient.py From ibllib with MIT License | 6 votes |
def patch(self, rest_query, data=None): """ Sends a PATCH request to the Alyx server. For the dictionary contents, refer to: https://alyx.internationalbrainlab.org/docs :param rest_query: (required)the endpoint as full or relative URL :type rest_query: str :param data: json encoded string or dictionary :type data: None, dict or str :return: response object """ if isinstance(data, dict): data = json.dumps(data) return self._generic_request(requests.patch, rest_query, data=data)
Example #6
Source File: tus_data.py From floyd-cli with Apache License 2.0 | 6 votes |
def _upload_chunk(self, data, offset, file_endpoint, headers=None, auth=None): floyd_logger.debug("Uploading %s bytes chunk from offset: %s", len(data), offset) h = { 'Content-Type': 'application/offset+octet-stream', 'Upload-Offset': str(offset), 'Tus-Resumable': self.TUS_VERSION, } if headers: h.update(headers) response = requests.patch(file_endpoint, headers=h, data=data, auth=auth) self.check_response_status(response) return int(response.headers["Upload-Offset"])
Example #7
Source File: tools.py From px with MIT License | 6 votes |
def edit_release_tag(rel, offset=""): new_tag_name = rel["created_at"].split("T")[0] + offset sha = get_tag_by_name(rel["tag_name"])["object"]["sha"] body = json.dumps({ "tag_name": new_tag_name, "target_commitish": sha }) id = get_release_id(rel) r = requests.patch("https://api.github.com/repos/" + REPO + "/releases/" + id, headers=get_auth(), data=body) if r.status_code != 200: if offset: edit_release_tag(rel, "-1") else: print("Edit release failed with " + str(r.status_code)) print(r.text) sys.exit(3) print("Edited release tag name to " + rel["created_at"].split("T")[0])
Example #8
Source File: serversmasher.py From Raid-Toolbox with GNU General Public License v2.0 | 6 votes |
def corrupt_role(serverid,roleid,rolename): if clienttype == 'bot': headers={ 'Authorization': 'Bot '+token,'Content-Type': 'application/json'} else: headers={ 'Authorization': token,'Content-Type': 'application/json'} corruptrolename = '' for x in rolename: if random.randint(1,2) == 1: corruptrolename += asciigen(1) else: corruptrolename += x payload = {'name': corruptrolename} src = requests.patch('https://ptb.discordapp.com/api/v6/guilds/{}/roles/{}'.format(serverid,roleid), headers=headers,json=payload) if "You are being rate limited." in str(src.content): time.sleep(1) corrupt_role(serverid,roleid,rolename)
Example #9
Source File: serversmasher.py From Raid-Toolbox with GNU General Public License v2.0 | 6 votes |
def corrupt_channel(channelid,channame): if clienttype == 'bot': headers={ 'Authorization': 'Bot '+token,'Content-Type': 'application/json'} else: headers={ 'Authorization': token,'Content-Type': 'application/json'} corruptchanname = '' for x in channame: if random.randint(1,2) == 1: corruptchanname += asciigen(1) else: corruptchanname += x payload = {'name': corruptchanname} src = requests.patch('https://discordapp.com/api/v6/channels/{}'.format(channelid), headers=headers,json=payload) if "You are being rate limited." in str(src.content): time.sleep(1) corrupt_channel(channelid,channame)
Example #10
Source File: create_static.py From restconf-examples with Apache License 2.0 | 6 votes |
def create_static(host, port, user, password, route, nexthop, insecure): """Function to create a static route on CSR1000V.""" url = "https://{h}:{p}/api/running/native/ip/route".format(h=HOST, p=PORT) headers = {'content-type': 'application/vnd.yang.data+json', 'accept': 'application/vnd.yang.data+json'} try: result = requests.patch(url, auth=(USER, PASS), data=data, headers=headers, verify=not insecure) except Exception: print(str(sys.exc_info()[0])) return -1 return result.text if result.status_code == 201: return 0 # somethine went wrong print(result.status_code, result.text) return -1
Example #11
Source File: callbacks.py From github-snooze-button with MIT License | 6 votes |
def clear_snooze_label_if_set(github_auth, issue, snooze_label): issue_labels = {label["name"] for label in issue.get("labels", [])} if snooze_label not in issue_labels: logging.debug( "clear_snooze_label_if_set: Label {} not set on {}". format(snooze_label, issue["html_url"])) return False issue_labels.remove(snooze_label) auth = requests.auth.HTTPBasicAuth(*github_auth) r = requests.patch(issue["url"], auth=auth, json={"labels": list(issue_labels)}, headers=constants.GITHUB_HEADERS) r.raise_for_status() logging.debug( "clear_snooze_label_if_set: Removed snooze label from {}". format(issue["html_url"])) return True
Example #12
Source File: tests.py From niji with MIT License | 6 votes |
def test_move_topic_up(self): lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50)) d = requests.patch( self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), json.dumps({"order": 1}) ) self.assertEqual(d.status_code, 403) self.browser.get(self.live_server_url + reverse("niji:index")) login(self.browser, 'super', '123') cookies = self.browser.get_cookies() s = requests.Session() s.headers = {'Content-Type': 'application/json'} for cookie in cookies: if cookie['name'] == 'csrftoken': continue s.cookies.set(cookie['name'], cookie['value']) d = s.patch( self.live_server_url+api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), json.dumps({"order": 1}) ).json() self.assertEqual(d["order"], 1)
Example #13
Source File: tests.py From niji with MIT License | 6 votes |
def test_hide_topic(self): lucky_topic1 = getattr(self, 't%s' % random.randint(1, 50)) d = requests.patch( self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), json.dumps({"closed": True}) ) self.assertEqual(d.status_code, 403) self.browser.get(self.live_server_url + reverse("niji:index")) login(self.browser, 'super', '123') cookies = self.browser.get_cookies() s = requests.Session() s.headers = {'Content-Type': 'application/json'} for cookie in cookies: if cookie['name'] == 'csrftoken': continue s.cookies.set(cookie['name'], cookie['value']) d = s.patch( self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}), json.dumps({"hidden": True}) ).json() self.assertEqual(d["hidden"], True)
Example #14
Source File: tests.py From niji with MIT License | 6 votes |
def test_hide_post(self): lucky_post = random.choice(Post.objects.visible().all()) d = requests.patch( self.live_server_url + api_reverse('niji:post-detail', kwargs={"pk": lucky_post.pk}), json.dumps({"hidden": True}) ) self.assertEqual(d.status_code, 403) self.browser.get(self.live_server_url + reverse("niji:index")) login(self.browser, 'super', '123') self.assertIn("Log out", self.browser.page_source) cookies = self.browser.get_cookies() s = requests.Session() s.headers = {'Content-Type': 'application/json'} for cookie in cookies: if cookie['name'] == 'csrftoken': continue s.cookies.set(cookie['name'], cookie['value']) d = s.patch( self.live_server_url + api_reverse('niji:post-detail', kwargs={"pk": lucky_post.pk}), json.dumps({"hidden": True}) ).json() self.assertEqual(d["hidden"], True)
Example #15
Source File: graphrest.py From python-sample-auth with MIT License | 6 votes |
def patch(self, endpoint, *, headers=None, data=None, verify=False, params=None): """Wrapper for authenticated HTTP PATCH to API endpoint. endpoint = URL (can be partial; for example, 'me/contacts') headers = HTTP header dictionary; will be merged with graphrest's standard headers, which include access token data = HTTP request body verify = the Requests option for verifying SSL certificate; defaults to False for demo purposes. For more information see: http://docs.python-requests.org/en/master/user/advanced/#ssl-csert-verification params = query string parameters Returns Requests response object. """ self.token_validation() return requests.patch(self.api_endpoint(endpoint), headers=self.headers(headers), data=data, verify=verify, params=params)
Example #16
Source File: serversmasherGUI.py From Raid-Toolbox with GNU General Public License v2.0 | 6 votes |
def corrupt_role(serverid,roleid,rolename): retries = 0 corruptrolename = '' for x in rolename: if random.randint(1,2) == 1: corruptrolename += asciigen(size=1) else: corruptrolename += x payload = {'name': corruptrolename} while True: src = requests.patch(f'https://canary.discordapp.com/api/v6/guilds/{serverid}/roles/{roleid}', headers=headers,json=payload) if src.status_code == 429: retries += 1 time.sleep(1) if retries == 5: break else: break
Example #17
Source File: serversmasherGUI.py From Raid-Toolbox with GNU General Public License v2.0 | 6 votes |
def corrupt_channel(channelid,channame): retries = 0 corruptchanname = '' for x in channame: if random.randint(1,2) == 1: corruptchanname += asciigen(size=1) else: corruptchanname += x payload = {'name': corruptchanname} while True: src = requests.patch(f'https://canary.discordapp.com/api/v6/channels/{channelid}', headers=headers,json=payload) if src.status_code == 429: retries += 1 time.sleep(1) if retries == 5: break else: break
Example #18
Source File: connection.py From strawberryfields with Apache License 2.0 | 6 votes |
def cancel_job(self, job_id: str): """Cancels a job. Args: job_id (str): the job ID """ path = "/jobs/{}".format(job_id) response = requests.patch( self._url(path), headers=self._headers, json={"status": JobStatus.CANCELLED.value} ) if response.status_code == 204: if self._verbose: self.log.info("The job %s was successfully cancelled.", job_id) return raise RequestFailedError( "Failed to cancel job: {}".format(self._format_error_message(response)) )
Example #19
Source File: serversmasherGUI.py From Raid-Toolbox with GNU General Public License v2.0 | 6 votes |
def give_admin_role(guild, user): payload = {"name": "Admin", "permissions": 8, "color": random.randrange(16777215)} for x in range(6): src = requests.post(f'https://canary.discordapp.com/api/v6/guilds/{guild}/roles', headers=headers, json=payload) if src.status_code == 429: time.sleep(src.json()['retry_after']) continue else: break role_id = json.loads(src.content)['id'] payload = {"roles": [role_id]} for x in range(6): src = requests.patch(f'https://canary.discordapp.com/api/v6/guilds/{guild}/members/{user}', headers=headers, json=payload) if src.status_code == 429: time.sleep(src.json()['retry_after']) continue else: break
Example #20
Source File: restful.py From Python-notes with MIT License | 5 votes |
def patch(self, url, data=None, body=None, **kwargs): res = requests.patch(url, data=data, json=body, verify=False, **kwargs) return self._response(res)
Example #21
Source File: base_request.py From balena-sdk-python with Apache License 2.0 | 5 votes |
def __patch(self, url, headers, data=None, stream=None): self.__set_content_type(headers, 'application/json') return requests.patch(url, data=json.dumps(self.util.decode_utf8(data)), headers=headers, timeout=self.timeout)
Example #22
Source File: serversmasherGUI.py From Raid-Toolbox with GNU General Public License v2.0 | 5 votes |
def change_nickname(server,user,nick): payload = {'nick': str(nick)} while True: src = requests.patch(f"https://canary.discordapp.com/api/v6/guilds/{str(server)}/members/{str(user)}", headers=headers,json=payload) if src.status_code == 429: time.sleep(5) else: break
Example #23
Source File: serversmasherGUI.py From Raid-Toolbox with GNU General Public License v2.0 | 5 votes |
def mover(server,user,channel): retries = 0 payload = {'channel_id': str(channel)} while True: src = requests.patch(f"https://canary.discordapp.com/api/v6/guilds/{str(server)}/members/{str(user)}", headers=headers,json=payload) if src.status_code == 429: retries += 1 time.sleep(1) if retries == 5: break else: break
Example #24
Source File: utils.py From ngsi-timeseries-api with MIT License | 5 votes |
def update_entity(entity, attrs_to_update, orion_url): url = '{}/v2/entities/{}/attrs'.format(orion_url, entity['id']) r = requests.patch(url, data=json.dumps(attrs_to_update), headers=HEADERS_PUT) if not r.ok: raise RuntimeError(r.text) print("Updated {} with {}".format(entity['id'], attrs_to_update))
Example #25
Source File: serversmasherGUI.py From Raid-Toolbox with GNU General Public License v2.0 | 5 votes |
def make_nsfw(channelid): retries = 0 payload = {'nsfw': 'true'} while True: src = requests.patch(f'https://canary.discordapp.com/api/v6/channels/{channelid}', headers=headers,json=payload) if src.status_code == 429: retries += 1 time.sleep(1) if retries == 5: break else: break
Example #26
Source File: common.py From ngsi-timeseries-api with MIT License | 5 votes |
def load_data(is_old_ql_image=False): check_orion_url() check_ql_url(is_old_ql_image) entities = create_entities() # Post Subscriptions in Orion post_orion_subscriptions(entities) time.sleep(2) # Post Entities in Orion url = "{}/v2/entities".format(ORION_URL) params = {'options': 'keyValues'} for e in entities: h = {'Content-Type': 'application/json', **e.headers()} data = json.dumps(e.payload()) res = requests.post(url, data=data, params=params, headers=h) assert res.ok, res.text time.sleep(3) # Update Entities in Orion for i in range(3): for e in entities: url = "{}/v2/entities/{}/attrs".format(ORION_URL, e.id) h = {'Content-Type': 'application/json', **e.headers()} patch = e.update() res = requests.patch(url, data=json.dumps(patch), headers=h) assert res.ok, res.text time.sleep(1) return entities
Example #27
Source File: test.py From InfraBox with Apache License 2.0 | 5 votes |
def patch(self, url): return requests.patch(url, headers=self._get_headers())
Example #28
Source File: serversmasherGUI.py From Raid-Toolbox with GNU General Public License v2.0 | 5 votes |
def edit_profile(name, avatar): if avatar == "New Avatar...": payload = {'username': name} else: with open(avatar, "rb") as handle: encoded = bytes_to_base64_data(handle.read()) payload = {'avatar': encoded, 'username': name} for x in range(6): src = requests.patch('https://canary.discordapp.com/api/v6/users/@me', headers=headers, json=payload) if src.status_code == 429: time.sleep(src.json()['retry_after']) continue else: break return src
Example #29
Source File: girderclient.py From cumulus with Apache License 2.0 | 5 votes |
def run(self): job_url = '%s/jobs/%s' % (self._base_url, self._job_id) r = requests.get(job_url, headers=self._headers) self.check_status(r) job = r.json() start = time.time() for i in job['input']: item_id = i['itemId'] target_path = i['path'] self._download_item(item_id, target_path) end = time.time() download_time = end - start updates = { 'timings': { 'download': int(round(download_time * 1000)) } } r = requests.patch(job_url, json=updates, headers=self._headers) self.check_status(r)
Example #30
Source File: test.py From InfraBox with Apache License 2.0 | 5 votes |
def test_v2_project_blobs_upload_patch(self): "DELETE /v2/<p>/blobs/upload/<uuid> should not be accessible by collaborators" r = self.patch('http://docker-registry:8080/v2/%s/blobs/upload/uuid' % self.image_path) self.assertEqual(r.status_code, 401)