Here are the examples of the python api requests.codes.OK taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
16 Examples
3
Example 1
def upload(self, package, max_redirects=5):
number_of_redirects = 0
while number_of_redirects < max_redirects:
resp = self._upload(package)
if resp.status_code == codes.OK:
return resp
if 500 <= resp.status_code < 600:
number_of_redirects += 1
print('Received "{status_code}: {reason}" Package upload '
'appears to have failed. Retry {retry} of 5'.format(
status_code=resp.status_code,
reason=resp.reason,
retry=number_of_redirects,
))
else:
return resp
return resp
3
Example 2
Project: gitem Source File: test_api.py
@staticmethod
def api_will_return(json_return_value, status_code=requests.codes.OK, oauth2_token=None):
assert isinstance(json_return_value, dict)
return_value = mock.MagicMock()
return_value.status_code = status_code
return_value.json = mock.MagicMock(
return_value=json_return_value
)
return_value.ok = status_code == requests.codes.OK
return api.Api(oauth2_token, requester=mock.MagicMock(
return_value=return_value
))
3
Example 3
@staticmethod
def _rest_call(method, uri, headers=None, session=None):
response = mock.Mock()
response.status_code = requests.codes.OK
response.reason = 'Ok'
response.text = '{}'
response.headers = {
'Location': 'location'
}
return response
3
Example 4
def _check_response(self, response, config_url=None, session=None):
if session is None:
session = requests
if response.status_code not in (requests.codes.OK,
requests.codes.CREATED):
LOG.error(_LE('Vyatta vRouter REST API: Response Status : '
'%(status)s Reason: %(reason)s') %
{'status': response.status_code,
'reason': response.reason})
if config_url is not None:
self._rest_call("DELETE", config_url, session=session)
raise v_exc.VRouterOperationError(
ip_address=self.address, reason=response.reason)
3
Example 5
def __init__(self, settings):
self.port = str(settings.get('protocol_port', 55443))
self.host = ':'.join([settings.get('rest_mgmt_ip', ''), self.port])
self.auth = (settings['username'], settings['password'])
self.token = None
self.status = requests.codes.OK
self.timeout = settings.get('timeout')
self.max_tries = 5
self.session = requests.Session()
3
Example 6
def __init__(self, settings):
self.port = str(settings.get('protocol_port', 55443))
self.host = ':'.join([settings.get('rest_mgmt_ip', ''), self.port])
self.auth = (settings['username'], settings['password'])
self.inner_if_name = settings.get('inner_if_name', '')
self.outer_if_name = settings.get('outer_if_name', '')
self.token = None
self.vrf = settings.get('vrf', '')
self.vrf_prefix = 'vrf/%s/' % self.vrf if self.vrf else ""
self.status = requests.codes.OK
self.timeout = settings.get('timeout')
self.max_tries = 5
self.session = requests.Session()
3
Example 7
Project: neutron-vpnaas Source File: cisco_csr_rest_client.py
def read_tunnel_statuses(self):
results = self.get_request(self.vrf_prefix +
URI_VPN_SITE_ACTIVE_SESSIONS)
if self.status != requests.codes.OK or not results:
return []
tunnels = [(t[u'vpn-interface-name'], t[u'status'])
for t in results['items']]
return tunnels
0
Example 8
def _get_secret(self, name):
"""
Gets a Kubernetes secret.
:param name: The name of the secret.
:type name: str
"""
response = self._store.get(self._secrets_endpoint + '/' + name)
if response.status_code != requests.codes.OK:
raise KeyError('No secrets for {0}'.format(name))
secrets = {}
rj = response.json()
# The we have a data key use it directly
if 'data' in rj.keys():
rj = rj['data']
# If we have an items key pull the data from the first item
# FIXME: Verify it's the right data :-)
elif 'items' in rj.keys():
rj = rj['items'][0]['data']
for k, v in rj.items():
secrets[k.replace('-', '_')] = base64.decodebytes(v)
return secrets
0
Example 9
Project: commissaire-mvp Source File: kubestorehandler.py
def _save_on_namespace(self, model_instance):
"""
Saves data to a namespace and returns back a saved model.
:param model_instance: Model instance to save
:type model_instance: commissaire.model.Model
:returns: The saved model instance
:rtype: commissaire.model.Model
"""
patch_path = "/metadata/annotations"
path = _model_mapper[model_instance.__class__.__name__]
class_name = model_instance.__class__.__name__.lower()
r = self._store.get(self._endpoint + path)
if not r.json().get('metadata', {}).get('annotations', {}):
# Ensure we have an annotation container.
if self._store.patch(
self._endpoint + path,
json=[{
'op': 'add',
'path': patch_path,
'value': {'commissaire-manager': 'yes'}
}],
headers={'Content-Type': 'application/json-patch+json'}
).status_code != 200:
raise KeyError(
'Could creat annotation container for {0}={1}'.format(
class_name, model_instance.primary_key))
response = None
# NOTE: Kubernetes does not allow underscores in keys. To get past
# this we substitute _'s with -'s
for x in model_instance._attribute_map.keys():
annotation_key = 'commissaire-{0}-{1}-{2}'.format(
class_name, model_instance.primary_key, x.replace('_', '-'))
annotation_value = getattr(model_instance, x)
# If the value is iterable (list, dict) turn it into a json string
if hasattr(annotation_value, '__iter__'):
annotation_value = 'json:' + json.dumps(annotation_value)
# Skip any empty values
if annotation_value:
full_patch = [{
'op': 'add',
'path': patch_path + '/' + annotation_key,
'value': str(annotation_value)}]
response = self._store.patch(
self._endpoint + path,
json=full_patch,
headers={'Content-Type': 'application/json-patch+json'})
if response.status_code != requests.codes.OK:
# TODO log
print('Could not save annotation {0}: {1}'.format(
annotation_key, response.status_code))
if response:
return self._format_model(response.json(), model_instance)
raise KeyError('Could not save annotations!')
0
Example 10
Project: commissaire-mvp Source File: kubestorehandler.py
def _delete_on_namespace(self, model_instance):
"""
Deletes data within a namespace from a store.
:param model_instance: Model instance to delete
:type model_instance: commissaire.model.Model
"""
full_patch = []
class_name = model_instance.__class__.__name__.lower()
for x in model_instance._attribute_map.keys():
patch_path = (
'/metadata/annotations/commissaire-{0}-{1}-{2}'.format(
class_name, model_instance.primary_key, x))
patch_value = str(getattr(model_instance, x))
# Skip any empty values
if not patch_value:
continue
full_patch.append({'op': 'remove', 'path': patch_path})
path = _model_mapper[model_instance.__class__.__name__]
response = self._store.patch(
self._endpoint + path,
json=full_patch,
headers={'Content-Type': 'application/json-patch+json'})
if response.status_code != requests.codes.OK:
raise KeyError(response.text)
0
Example 11
Project: zest.releaser Source File: release.py
def _retry_twine(self, twine_command, server, filename):
repository = self._get_repository(server)
package_file = PackageFile.from_filename(filename, comment=None)
if twine_command == 'register':
# Register the package.
twine_function = repository.register
twine_args = (package_file, )
elif twine_command == 'upload':
# Note: we assume here that calling package_is_uploaded does not
# give an error, and that there is no reason to retry it.
if repository.package_is_uploaded(package_file):
logger.warn(
'A file %s has already been uploaded. Ignoring.', filename)
return
twine_function = repository.upload
twine_args = (package_file, )
else:
print(Fore.RED + "Unknown twine command: %s" % twine_command)
sys.exit(1)
response = twine_function(*twine_args)
if response is not None and response.status_code == codes.OK:
return
# Something went wrong. Close repository.
repository.close()
self._drop_repository(server)
if response is not None:
# Some errors reported by PyPI after register or upload may be
# fine. The register command is not really needed anymore with the
# new PyPI. See https://github.com/pypa/twine/issues/200
# This might change, but for now the register command fails.
if (twine_command == 'register'
and response.reason == 'This API is no longer supported, '
'instead simply upload the file.'):
return
# Show the error.
print(Fore.RED + "Response status code: %s" % response.status_code)
print(Fore.RED + "Reason: %s" % response.reason)
print(Fore.RED + "There were errors or warnings.")
logger.exception("Package %s has failed.", twine_command)
retry = utils.retry_yes_no('twine %s' % twine_command)
if retry:
logger.info("Retrying.")
return self._retry_twine(twine_command, server, filename)
0
Example 12
def test_url(self, url):
return self._http.head(url).status_code == requests.codes.OK
0
Example 13
def assertOk(self, status_code):
self.assertEqual(status_code, requests.codes.OK)
0
Example 14
Project: gitem Source File: test_api.py
@staticmethod
def paged_api_will_return(json_return_values, status_codes=None, oauth2_token=None):
assert isinstance(json_return_values, list)
assert isinstance(status_codes, list) or status_codes is None
if status_codes is None:
status_codes = [requests.codes.OK] * len(json_return_values)
return_value = mock.MagicMock()
# This is some weird mock black magic...
type(return_value).status_code = mock.PropertyMock(
side_effect=status_codes
)
return_value.json = mock.Mock(
side_effect=json_return_values
)
type(return_value).ok = mock.PropertyMock(
side_effect=[
status_code == requests.codes.OK
for status_code in status_codes
]
)
return api.Api(oauth2_token, requester=mock.MagicMock(
return_value=return_value
))
0
Example 15
def _response_info_for(self, response, method):
"""Return contents or location from response.
For a POST or GET with a 200 response, the response content
is returned.
For a POST with a 201 response, return the header's location,
which contains the identifier for the created resource.
If there is an error, return the response content, so that
it can be used in error processing ('error-code', 'error-message',
and 'detail' fields).
"""
if method in ('POST', 'GET') and self.status == requests.codes.OK:
LOG.debug('RESPONSE: %s', response.json())
return response.json()
if method == 'POST' and self.status == requests.codes.CREATED:
return response.headers.get('location', '')
if self.status >= requests.codes.BAD_REQUEST and response.content:
if six.b('error-code') in response.content:
content = jsonutils.loads(response.content)
LOG.debug("Error response content %s", content)
return content
0
Example 16
def _response_info_for(self, response, method):
"""Return contents or location from response.
For a POST or GET with a 200 response, the response content
is returned.
For a POST with a 201 response, return the header's location,
which contains the identifier for the created resource.
If there is an error, return the response content, so that
it can be used in error processing ('error-code', 'error-message',
and 'detail' fields).
"""
if method in ('POST', 'GET') and self.status == requests.codes.OK:
LOG.debug('RESPONSE: %s', response.json())
return response.json()
if method == 'POST' and self.status == requests.codes.CREATED:
return response.headers.get('location', '')
if self.status >= requests.codes.BAD_REQUEST and response.content:
if b'error-code' in response.content:
content = jsonutils.loads(response.content)
LOG.debug("Error response content %s", content)
return content