本文整理汇总了Python中requests.patch方法的典型用法代码示例。如果您正苦于以下问题:Python requests.patch方法的具体用法?Python requests.patch怎么用?Python requests.patch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests
的用法示例。
在下文中一共展示了requests.patch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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
示例2: do_patch
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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)))
示例3: patch
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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)
示例4: run
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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)
示例5: _upload_chunk
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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"])
示例6: edit_release_tag
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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])
示例7: cancel_job
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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))
)
示例8: create_static
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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
示例9: clear_snooze_label_if_set
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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
示例10: test_move_topic_up
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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)
示例11: test_hide_topic
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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)
示例12: test_hide_post
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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)
示例13: patch
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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)
示例14: api_patch
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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)
示例15: corrupt_channel
# 需要导入模块: import requests [as 别名]
# 或者: from requests import patch [as 别名]
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