Here are the examples of the python api requests.patch taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
61 Examples
3
Example 1
Project: GitIssueBot Source File: autolabel.py
def apply_label(label, issue, headers, dryrun=False):
current_labels = list(issue["labels"])
current_labels.append(label)
logger.debug("-> Adding a label via PATCH %s, labels=%r" % (issue["url"], current_labels))
if not dryrun:
requests.patch(issue["url"], headers=headers, data=json.dumps({"labels": current_labels}))
3
Example 2
def update(self, job_id, update_doc):
endpoint = self.endpoint + job_id
r = requests.patch(endpoint,
headers=self.headers,
data=json.dumps(update_doc),
verify=self.verify)
if r.status_code != 200:
raise exceptions.ApiClientException(r)
return r.json()['version']
3
Example 3
def update(self, action_id, update_doc):
endpoint = self.endpoint + action_id
r = requests.patch(endpoint,
headers=self.headers,
data=json.dumps(update_doc), verify=self.verify)
if r.status_code != 200:
raise exceptions.ApiClientException(r)
return r.json()['version']
3
Example 4
def patch(self, patch_url, params):
"""POST to the web form"""
try:
self.res = requests.patch(patch_url, data=json.dumps(params),
headers=self.headers, proxies=self.proxies)
except requests.exceptions.RequestException as e:
if self.settings["debug_mode"]:
print ("requests request exception: " + str(e))
return
return self.res
3
Example 5
def on_epoch_end(self, epoch, logs={}):
W = np.asarray(K.eval(self.weights))
I = img_grid(W)
fig = plt.figure(figsize=(8, 5))
plt.imshow(I)
plt.savefig(os.path.join(self.static_path, 'images',
self.name+'.png'))
# html = mpld3.fig_to_html(fig)
plt.close(fig)
requests.patch(self.app_url, json={
'name': self.name, 'type': 'img',
'value': os.path.join('./images', self.name+'.png'),
'pos': self.position, 'description': self.description})
3
Example 6
Project: allianceauth Source File: discord_manager.py
@staticmethod
def __edit_role(role_id, name, color=0, hoist=True, permissions=36785152):
custom_headers = {'content-type': 'application/json', 'authorization': 'Bot ' + settings.DISCORD_BOT_TOKEN}
data = {
'color': color,
'hoist': hoist,
'name': name,
'permissions': permissions,
}
path = DISCORD_URL + "/guilds/" + str(settings.DISCORD_GUILD_ID) + "/roles/" + str(role_id)
r = requests.patch(path, headers=custom_headers, data=json.dumps(data))
logger.debug("Received status code %s after editing role id %s" % (r.status_code, role_id))
r.raise_for_status()
return r.json()
3
Example 7
def scale(app_name, proc_name, num_instances):
url = VIP + CONSOLE_API + app_name + "/procs/" + \
proc_name + "/"
headers = {"Host": CONSOLE_ADDRESS, "Content-Type": "application/json"}
app_info = json.dumps({"num_instances": num_instances})
return requests.patch(url, data=app_info, headers=headers)
3
Example 8
def patch(self, **kwargs):
data = self._prepare_data(**kwargs)
headers = {'content-type': 'application/json'}
response = requests.patch(self.url, data=data,
auth=self.config['auth'],
verify=self.config['verify'],
headers=headers)
entity = self._prepare_entity(response)
return entity
3
Example 9
def patch(self, api, data=None, params=None):
"""
Executes a PATCH call
:param api: Specification to fill out in the URL, eg: /vpools/<vpool_guid>/shrink_vpool
:param data: Data to patch
:param params: Additional query parameters, eg: _dynamics
"""
return self._call(api=api, params=params, function=requests.patch, data=data)
3
Example 10
@add_ssl_verify_to_kwargs
@add_auth_token_to_headers
@add_json_content_type_to_headers
def patch(self, url, data, **kwargs):
response = requests.patch(self.root + url, data, **kwargs)
response = self._response_hook(response=response)
return response
3
Example 11
Project: ir-scripts Source File: Vuln-tickets.py
def sn_update(sys_id, comment):
sn_url = sn_server + '/' + sys_id # REST URL for the ticket
update = requests.patch(sn_url, auth=(user, pwd), headers=headers,\
data='{"comments":"' + comment +'"}')
if update.status_code != 200:
print('Status:', response.status_code, 'Headers:',\
response.headers, 'Error Response:',response.json())
exit()
print("Updated Service Now ticket" + " " + sys_id) # user output
3
Example 12
def patch(self, uri, params=None, headers=None):
if headers is None:
headers = dict()
headers.update(self._headers)
return requests.patch(self._url + uri, params=params, headers=headers)
3
Example 13
Project: indico Source File: util.py
def unregister_instance():
payload = {'enabled': False}
url = urljoin(_url, settings.get('uuid'))
response = requests.patch(url, data=dumps(payload), headers=_headers, timeout=TIMEOUT)
try:
response.raise_for_status()
except HTTPError as err:
if err.response.status_code != 404:
logger.error('failed to unregister the server to the community hub, got: %s', err.message)
raise
except Timeout:
logger.error('failed to unregister: timeout while contacting the community hub')
raise
except RequestException as err:
logger.error('unexpected exception while unregistering the server with the Community Hub: %s', err.message)
raise
settings.set('joined', False)
logger.info('successfully unregistered the server from the community hub')
3
Example 14
@step('I issue a {request_method:w} request to {url:url} with {data}')
def do_request(context, request_method, url, data):
data = data and json.loads(data) or {}
try:
if request_method == 'PATCH':
r = requests.patch(url, json=data)
else:
r = requests.post(url, json=data)
except requests.exceptions.RequestException:
context.status_code = None
context.response = None
else:
_set_response(context, r)
3
Example 15
Project: behave-http Source File: __init__.py
@behave.when('I make a PATCH request to "{url_path_segment}"')
@dereference_step_parameters_and_data
def patch_request(context, url_path_segment):
url = append_path(context.server, url_path_segment)
context.response = requests.patch(
url, data=context.data, headers=context.headers, auth=context.auth,
verify=context.verify_ssl)
3
Example 16
def _patch(self, resource, data, *args, **kwargs):
url = self._url(resource)
r = requests.patch(
url,
data=json.dumps(data),
headers={'content-type': 'application/merge-patch+json'},
*args,
**kwargs)
self._wrap_exception(r)
return r.json()
3
Example 17
@_enabled_or_noop
def _patch(self, url, data=None):
"""
Handle authenticated PATCH 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
"""
url = urljoin(self.base_url, url)
try:
r = requests.patch(url, auth=self.auth, json=data)
except requests.exceptions.RequestException as e:
raise e
else:
r.raise_for_status()
return r.json()
3
Example 18
def markAsRead(self):
'''marks analogous message as read in the cloud.'''
read = '{"IsRead":true}'
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
try:
response = requests.patch(self.update_url.format(self.json['Id']),read,headers=headers,auth=self.auth)
except:
return False
return True
3
Example 19
@staticmethod
def patch(url=None, headers=None, content=None):
result = requests.patch(url, data=content, headers=headers)
if result.status_code != 200:
RestClient._raise_error(result)
return result.json()
3
Example 20
Project: requests-mock Source File: test_mocker.py
@requests_mock.Mocker()
def test_mocker_patch(self, m):
mock_obj = m.patch(self.URL, text=self.TEXT)
self.assertResponse(requests.patch(self.URL))
self.assertTrue(mock_obj.called)
self.assertTrue(mock_obj.called_once)
self.assertTrue(m.called)
self.assertTrue(m.called_once)
3
Example 21
def on_epoch_end(self, epoch=None, logs={}):
fig = self.generate_plot()
html = mpld3.fig_to_html(fig)
return requests.patch(self.app_url, json={
'name': self.name, 'type': 'html', 'value': html,
'pos': self.position, 'description': self.description})
3
Example 22
def on_epoch_end(self, epoch, logs={}):
self.train_values.append(self.totals['loss']/self.seen)
self.valid_values.append(logs['val_loss'])
fig = plt.figure(figsize=(8, 5))
plt.plot(self.train_values)
plt.plot(self.valid_values)
# plt.xlabel('epochs')
# plt.ylabel('loss')
html = mpld3.fig_to_html(fig)
plt.close(fig)
requests.patch(self.app_url, json={
'name': self.name, 'type': 'html', 'value': html,
'pos': self.position, 'description': self.description})
3
Example 23
def on_epoch_end(self, epoch=None, logs={}):
img = self.generate_img()
res = self.client.upload_from_path(img)
return requests.patch(self.app_url, json={
'name': self.name, 'type': 'img', 'value': res['link'],
'pos': self.position, 'description': self.description})
3
Example 24
def update_gist(self, payload):
""" Update an existent Gist via PATCH method.
:param payload: the data of the message body. It contains description,
whenever is public or private and, of course, file contents.
"""
url = self.ENDPOINT_GIST % (payload.identifier)
headers = {'Content-type': self.APPLICATION_JSON}
data_json = json.dumps(payload, indent=2)
if self.basic_auth:
return requests.patch(url, data=data_json, headers=headers,
auth=(self.username, self.credential))
else:
params = {'access_token': self.credential}
return requests.patch(url, data=data_json, headers=headers,
params=params)
3
Example 25
def _patch(self, url, data_dict, params):
rdata = json.dumps(data_dict)
response = requests.patch(url, data=rdata, params=params, headers=self._headers)
data = json.loads(response.content.decode())
if response.status_code == 200:
return data
self.last_error = {
"status_code": response.status_code,
"detail": data.get("detail", "")
}
return None
3
Example 26
def patch(url, data=None, **kwargs):
"""A wrapper for ``requests.patch``. Sends a PATCH request."""
_set_content_type(kwargs)
if _content_type_is_json(kwargs) and data is not None:
data = dumps(data)
_log_request('PATCH', url, kwargs, data)
response = requests.patch(url, data, **kwargs)
_log_response(response)
return response
3
Example 27
Project: allianceauth Source File: discord_manager.py
@staticmethod
def update_nickname(user_id, nickname):
try:
custom_headers = {'content-type': 'application/json', 'authorization': 'Bot ' + settings.DISCORD_BOT_TOKEN}
data = {'nick': nickname, }
path = DISCORD_URL + "/guilds/" + str(settings.DISCORD_GUILD_ID) + "/members/" + str(user_id)
r = requests.patch(path, headers=custom_headers, json=data)
logger.debug("Got status code %s after setting nickname for Discord user ID %s (%s)" % (
r.status_code, user_id, nickname))
if r.status_code == 404:
logger.warn("Discord user ID %s could not be found in server." % user_id)
return True
r.raise_for_status()
return True
except:
logger.exception("Failed to set nickname for Discord user ID %s (%s)" % (user_id, nickname))
return False
3
Example 28
Project: allianceauth Source File: discord_manager.py
@staticmethod
def update_groups(user_id, groups):
custom_headers = {'content-type': 'application/json', 'authorization': 'Bot ' + settings.DISCORD_BOT_TOKEN}
group_ids = [DiscordOAuthManager.__group_name_to_id(DiscordOAuthManager._sanitize_groupname(g)) for g in groups]
path = DISCORD_URL + "/guilds/" + str(settings.DISCORD_GUILD_ID) + "/members/" + str(user_id)
data = {'roles': group_ids}
r = requests.patch(path, headers=custom_headers, json=data)
logger.debug("Received status code %s after setting user roles" % r.status_code)
r.raise_for_status()
3
Example 29
def update(self, session_id, update_doc):
endpoint = self.endpoint + session_id
r = requests.patch(endpoint,
headers=self.headers,
data=json.dumps(update_doc),
verify=self.verify)
if r.status_code != 200:
raise exceptions.ApiClientException(r)
return r.json()['version']
3
Example 30
Project: bashhub-client Source File: rest_client.py
def patch_system(system_patch, mac):
url = BH_URL + "/api/v1/system/{0}".format(mac)
try:
r = requests.patch(url,
data=system_patch.to_JSON(),
headers=json_auth_headers())
r.raise_for_status()
return r.status_code
except Exception as error:
if r.status_code in (403, 401):
print("Permissons Issue. Run bashhub setup to re-login.")
return None
3
Example 31
def patch(self, url, data={}):
headers = self.base_headers.copy()
headers.update({
'Authorization': 'Bearer %s' % self.jwt,
'Content-Type': 'application/json'
})
response = requests.patch(url, data=json.dumps(data), headers=headers)
return self._process_response(response)
3
Example 32
Project: django-bulbs Source File: tasks.py
@shared_task(default_retry_delay=5)
def firebase_update_entry(entry_id):
endpoint = _get_endpoint()
if endpoint:
entry = LiveBlogEntry.objects.get(id=entry_id)
url = endpoint.format(liveblog_id=entry.liveblog.id,
entry_id=entry.id)
if entry.published:
resp = requests.patch(url, json={
'published': entry.published.isoformat(),
})
else:
resp = requests.delete(url)
resp.raise_for_status()
0
Example 33
Project: chip-seq-pipeline Source File: analysis_status.py
def main():
args = get_args()
authid, authpw, server = common.processkey(args.key, args.keyfile)
keypair = (authid,authpw)
if args.infile and args.experiments:
experiments = args.experiments
experiments.extend([e.strip() for e in args.infile if e.strip()])
elif args.infile:
experiments = args.infile
else:
experiments = args.experiments
for exp_id in experiments:
uri = '/experiments/%s' %(exp_id)
experiment = common.encoded_get(urlparse.urljoin(server,'%s' %(uri)), keypair)
if experiment.get('status') == 'error':
print experiment
print "Error fetching %s ... skipping" %(exp_id)
continue
print experiment.get('accession')
for uri in experiment['original_files']:
url = urlparse.urljoin(server,'%s' %(uri))
file_obj = common.encoded_get(url, keypair)
print "%s, %s, %s, %s, %s, %s" %(file_obj.get('accession'),file_obj.get('file_type'),file_obj.get('file_format'),file_obj.get('file_format_type'),file_obj.get('output_type'),file_obj.get('status'))
if file_obj.get('file_format') in ['bed', 'bigBed', 'bigWig']:
if file_obj.get('status') != 'released' or args.force:
patch_payload = {'status': args.status}
if args.dryrun:
print "--dryrun: would have patched %s" %(json.dumps(patch_payload))
else:
r = requests.patch(url, auth=keypair, data=json.dumps(patch_payload), headers={'content-type': 'application/json', 'accept': 'application/json'})
try:
r.raise_for_status()
except:
print(r.text)
print('Patch failed: %s %s ... skipping' % (r.status_code, r.reason))
continue
else:
print "Patched %s" %(json.dumps(patch_payload))
0
Example 34
def create_gist(anonymous=False, command=None, description=None,
files=None, private=False, vim=False, edit=False):
conf = parse_config()
if vim:
payload = get_vim_payload()
else:
payload = get_commandline_payload(conf.get('prompt'), command, files)
if private:
url = private_gist_url(conf, anonymous)
token = None if anonymous else conf.get('private_oauth')
else:
url = conf.get('public_github_url')
token = None if anonymous else conf.get('public_oauth')
headers = get_headers(token) if token else None
if edit:
payload = {'description': description or '',
'files': payload}
edit = edit[0].split('/')[-1]
r = requests.patch(url + '/gists/%s' % edit, data=json.dumps(payload),
headers=headers)
else:
payload = {'description': description or '',
'public': False,
'files': payload}
r = requests.post(url + '/gists', data=json.dumps(payload),
headers=headers)
r.raise_for_status()
link = r.json()['html_url']
return link
0
Example 35
def encoded_update(method, url, keypair, payload, return_response):
import urlparse, urllib, requests, json
if method == 'patch':
request_method = requests.patch
elif method == 'post':
request_method = requests.post
elif method == 'put':
request_method = requests.put
else:
logging.error('Invalid HTTP method: %s' %(method))
return
RETRY_CODES = [500]
RETRY_EXCEPTIONS = (requests.exceptions.ConnectionError, requests.exceptions.SSLError)
HEADERS = {'accept': 'application/json', 'content-type': 'application/json'}
max_retries = 10
max_sleep = 10
while max_retries:
try:
response = request_method(
url, auth=keypair, headers=HEADERS, data=json.dumps(payload))
except RETRY_EXCEPTIONS as e:
logging.warning(
"%s ... %d retries left." % (e, max_retries))
sleep(max_sleep - max_retries)
max_retries -= 1
continue
except Exception as e:
logging.error("%s" % (e))
return None
else:
if response.status_code in RETRY_CODES:
logging.warning(
"%d %s ... %d retries left."
% (response.status_code, response.text, max_retries))
sleep(max_sleep - max_retries)
max_retries -= 1
continue
if return_response:
return response
else:
try:
return response.json()
except:
return response.text
logging.error("Max retried exhausted.")
return None
0
Example 36
def update_comment(comments, body):
requests.patch(comments['url'],
params={'access_token': GH_TOKEN},
json={'body': body})
0
Example 37
Project: niji Source File: tests.py
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)
0
Example 38
Project: niji Source File: tests.py
def test_close_open_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({"closed": True})
).json()
self.assertEqual(d["closed"], True)
d = s.patch(
self.live_server_url + api_reverse('niji:topic-detail', kwargs={"pk": lucky_topic1.pk}),
json.dumps({"closed": False})
).json()
self.assertEqual(d["closed"], False)
0
Example 39
Project: niji Source File: tests.py
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)
0
Example 40
Project: niji Source File: tests.py
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)
0
Example 41
Project: spilo Source File: callback_role.py
def change_host_role_label(new_role):
try:
with open(TOKEN_FILENAME, "r") as f:
token = f.read()
except IOError:
sys.exit("Unable to read K8S authorization token")
headers = {'Authorization': 'Bearer {0}'.format(token)}
headers['Content-Type'] = 'application/json-patch+json'
url = API_URL.format(os.environ.get('POD_NAMESPACE', 'default'),
os.environ['HOSTNAME'])
data = [{'op': 'add', 'path': '/metadata/labels/{0}'.format(LABEL), 'value': new_role}]
for i in range(NUM_ATTEMPTS):
try:
r = requests.patch(url, headers=headers, data=json.dumps(data), verify=CA_CERT_FILENAME)
if r.status_code >= 300:
logger.warning("Unable to change the role label to {0}: {1}".format(new_role, r.text))
else:
break
except requests.exceptions.RequestException as e:
logger.warning("Exception when executing POST on {0}: {1}".format(url, e))
time.sleep(1)
else:
logger.warning("Unable to set the label after {0} attempts".format(NUM_ATTEMPTS))
0
Example 42
Project: GitIssueBot Source File: approve.py
def mark_issue_valid(issue, headers, config, dryrun):
"""
Marks a (formerly invalidated) issue as valid.
:param issue: the issue to mark as valid
:param headers: headers to use for requests against API
:param config: config to use
:param dryrun: whether to only simulate the writing API calls
"""
label = config.get("label", None)
oklabel = config.get("oklabel", None)
if not label and not oklabel:
return
current_labels = list(issue["labels"])
# apply the "incomplete ticket" label if configured
if label and label in current_labels:
current_labels.remove(label)
# apply the "ok ticket" label if configured and issue wouldn't be ignored otherwise
if oklabel and not oklabel in current_labels and not (has_ignored_labels(issue, config) or has_ignored_title(issue, config)):
current_labels.append(oklabel)
logger.debug("-> Marking issue valid via PATCH %s, labels=%r" % (issue["url"], current_labels))
if not dryrun:
requests.patch(issue["url"], headers=headers, data=json.dumps({"labels": current_labels}))
0
Example 43
def patch(URL, msg):
to_post = json.dumps(msg)
response = requests.patch(firebaseURL(URL), data=to_post)
if response.status_code != 200:
raise FirebaseException(response.text)
0
Example 44
def patch(self, url, data=None, **kwargs):
"""Encapsulte requests.patch to use this class instance header"""
return requests.patch(url, data=data, **self.add_headers(kwargs))
0
Example 45
def edit(self, **args):
if 'body' in args:
self.body = {'body':args['body']}
else:
raise Exception('Comment Body can\'t be empty')
if 'user' in args:
self.user = args['user']
else:
self.user = self.gist.username
if 'commentid' in args:
self.commentid = args['commentid']
else:
raise Exception('CommenID not provided')
self.gist_name = ''
if 'name' in args:
self.gist_name = args['name']
self.gist_id = self.getMyID(self.gist_name)
elif 'id' in args:
self.gist_id = args['id']
else:
raise Exception('Either provide authenticated user\'s Unambigious Gistname or any unique Gistid')
if self.gist_id:
r = requests.patch(
'%s/gists/%s/comments/%s'%(BASE_URL,self.gist_id, self.commentid),
headers=self.gist.header,
data=json.dumps(self.body)
)
if (r.status_code == 200):
response ={
'GistID': self.gist_id,
'CommenID': r.json()['id'],
'body': self.body['body'],
'created_at': r.json()['created_at']
}
return response
else:
response = {
'comment' : 'not edited'
}
raise Exception('Comment not edited')
0
Example 46
@parse_results
@validate_payload
def update(self, payload):
return requests.patch(self.current_url, json=payload)
0
Example 47
def edit(self, **args):
'''
Doesn't require manual fetching of gistID of a gist
passing gistName will return edit the gist
'''
self.gist_name = ''
if 'description' in args:
self.description = args['description']
else:
self.description = ''
if 'name' in args and 'id' in args:
self.gist_name = args['name']
self.gist_id = args['id']
elif 'name' in args:
self.gist_name = args['name']
self.gist_id = self.getMyID(self.gist_name)
elif 'id' in args:
self.gist_id = args['id']
else:
raise Exception('Gist Name/ID must be provided')
if 'content' in args:
self.content = args['content']
else:
raise Exception('Gist content can\'t be empty')
if (self.gist_name == ''):
self.gist_name = self.getgist(id=self.gist_id)
data = {"description": self.description,
"files": {
self.gist_name: {
"content": self.content
}
}
}
else:
data = {"description": self.description,
"files": {
self.gist_name: {
"content": self.content
}
}
}
if self.gist_id:
r = requests.patch(
'%s/gists/%s'%(BASE_URL,self.gist_id),
headers=self.gist.header,
data=json.dumps(data),
)
if (r.status_code == 200):
r_text = json.loads(r.text)
response = {
'updated_content': self.content,
'created_at': r.json()['created_at'],
'comments':r.json()['comments']
}
return response
raise Exception('No such gist found')
0
Example 48
Project: runbook Source File: cloudflare.py
def change_zone_settings(email, key, domain, logger, setting, value):
''' Get the ZoneID for the specified domain '''
headers = {
'X-Auth-Email' : email,
'X-Auth-Key' : key,
'Content-Type' : 'application/json'
}
zoneid = get_zoneid(email, key, domain, logger)
url = "%s/zones/%s/settings/%s" % (baseurl,
zoneid, setting)
payload = json.dumps(value)
logger.debug("cloudflare: Requesting url " + url)
try:
req = requests.patch(url=url, headers=headers, data=payload)
if validate_response(req, logger):
return True
else:
return False
except:
return False
0
Example 49
@action
def patch(url, data=None, **kwargs):
return requests.patch(url, data, **kwargs)
0
Example 50
def encoded_update(method, url, keypair, payload, return_response):
import urlparse, urllib, requests, json
if method == 'patch':
request_method = requests.patch
elif method == 'post':
request_method = requests.post
elif method == 'put':
request_method = requests.put
else:
logging.error('Invalid HTTP method: %s' %(method))
return
RETRY_CODES = [500]
RETRY_EXCEPTIONS = (requests.exceptions.ConnectionError, requests.exceptions.SSLError)
HEADERS = {'accept': 'application/json', 'content-type': 'application/json'}
max_retries = 10
max_sleep = 10
while max_retries:
try:
response = request_method(
url, auth=keypair, headers=HEADERS, data=json.dumps(payload))
except RETRY_EXCEPTIONS as e:
logging.warning(
"%s ... %d retries left." % (e, max_retries))
sleep(max_sleep - max_retries)
max_retries -= 1
continue
except Exception as e:
logging.error("%s" % (e))
return None
else:
if response.status_code in RETRY_CODES:
logging.warning(
"%d %s ... %d retries left."
% (response.status_code, response.text, max_retries))
sleep(max_sleep - max_retries)
max_retries -= 1
continue
if return_response:
return response
else:
try:
return response.json()
except:
return response.text
logging.error("Max retries exhausted.")
if return_response:
return response
else:
return None