本文整理汇总了Python中requests.codes方法的典型用法代码示例。如果您正苦于以下问题:Python requests.codes方法的具体用法?Python requests.codes怎么用?Python requests.codes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests
的用法示例。
在下文中一共展示了requests.codes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _do_http_request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def _do_http_request(self, method, resource, json=None):
verify = self._verify_server
headers = self._build_auth_headers()
try:
resp = method(resource, headers=headers, json=json, verify=verify)
except requests.exceptions.Timeout as ex:
raise exception.KeyManagerError(str(ex))
except requests.exceptions.ConnectionError as ex:
raise exception.KeyManagerError(str(ex))
except Exception as ex:
raise exception.KeyManagerError(str(ex))
if resp.status_code in _EXCEPTIONS_BY_CODE:
raise exception.KeyManagerError(resp.reason)
if resp.status_code == requests.codes['forbidden']:
raise exception.Forbidden()
return resp
示例2: get_user_info
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def get_user_info(user_id):
"""
Returns info about a user
See https://api.slack.com/methods/users.info for the contents of info
"""
api_url = 'https://slack.com/api/users.info'
response = requests.get(api_url, params={'token': UQCSTESTING_USER_TOKEN, 'user': user_id})
if response.status_code != requests.codes['ok']:
LOGGER.error(f'Received status code {response.status.code}')
sys.exit(1)
json_contents = json.loads(response.content)
if not json_contents['ok']:
LOGGER.error(json_contents['error'])
sys.exit(1)
return json_contents
示例3: query
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def query(query, apiKey=None):
"""Send query to Octopart and return results."""
#url = 'http://octopart.com/api/v3/parts/match'
#payload = {'queries': json.dumps(query), 'include\[\]': 'specs', 'apikey': token}
#response = requests.get(url, params=payload)
if apiKey:
url = 'http://octopart.com/api/v3/parts/match?queries=%s' \
% json.dumps(query)
url += '&apikey=' + apiKey
else:
url = 'https://temp-octopart-proxy.kitspace.org/parts/match?queries=%s' \
% json.dumps(query)
url += '&include[]=specs'
url += '&include[]=datasheets'
response = requests.get(url)
if response.status_code == requests.codes['ok']:
results = json.loads(response.text).get('results')
return results
elif response.status_code == requests.codes['not_found']: #404
raise Exception('Octopart server not found.')
elif response.status_code == 403:
raise Exception('Octopart KEY invalid, registre one at "https://www.octopart.com".')
else:
raise Exception('Octopart error: ' + str(response.status_code))
示例4: get
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def get(self, context, key_id, metadata_only=False):
"""Retrieves the key identified by the specified id."""
if not key_id:
raise exception.KeyManagerError('key identifier not provided')
resp = self._do_http_request(self._session.get,
self._get_resource_url(key_id))
if resp.status_code == requests.codes['not_found']:
raise exception.ManagedObjectNotFoundError(uuid=key_id)
record = resp.json()['data']
if self._kv_version > 1:
record = record['data']
key = None if metadata_only else binascii.unhexlify(record['value'])
clazz = None
for type_clazz, type_name in self._secret_type_dict.items():
if type_name == record['type']:
clazz = type_clazz
if clazz is None:
raise exception.KeyManagerError(
"Unknown type : %r" % record['type'])
if hasattr(clazz, 'algorithm') and hasattr(clazz, 'bit_length'):
return clazz(record['algorithm'],
record['bit_length'],
key,
record['name'],
record['created'],
key_id)
else:
return clazz(key,
record['name'],
record['created'],
key_id)
示例5: delete
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def delete(self, context, key_id):
"""Represents deleting the key."""
if not key_id:
raise exception.KeyManagerError('key identifier not provided')
resp = self._do_http_request(self._session.delete,
self._get_resource_url(key_id))
if resp.status_code == requests.codes['not_found']:
raise exception.ManagedObjectNotFoundError(uuid=key_id)
示例6: list
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def list(self, context, object_type=None, metadata_only=False):
"""Lists the managed objects given the criteria."""
if object_type and object_type not in self._secret_type_dict:
msg = _("Invalid secret type: %s") % object_type
raise exception.KeyManagerError(reason=msg)
resp = self._do_http_request(self._session.get,
self._get_resource_url())
if resp.status_code == requests.codes['not_found']:
keys = []
else:
keys = resp.json()['data']['keys']
objects = []
for obj_id in keys:
try:
obj = self.get(context, obj_id, metadata_only=metadata_only)
if object_type is None or isinstance(obj, object_type):
objects.append(obj)
except exception.ManagedObjectNotFoundError as e:
LOG.warning("Error occurred while retrieving object "
"metadata, not adding it to the list: %s", e)
pass
return objects
示例7: send_request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def send_request(self, payload, **kwargs):
# type: (dict, dict) -> dict
kwargs.setdefault('headers', {})
for key, value in iteritems(self.DEFAULT_HEADERS):
kwargs['headers'].setdefault(key, value)
response = self._send_http_request(
# Use a custom JSON encoder that knows how to convert Tryte values.
payload = JsonEncoder().encode(payload),
url = self.node_url,
**kwargs
)
return self._interpret_response(response, payload, {codes['ok']})
示例8: wasNotFound
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def wasNotFound(self):
return self.currentResponse is not None and self.currentResponse.status_code == requests.codes.not_found
示例9: _translate_http_exceptions
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def _translate_http_exceptions(resp: requests.Response) -> None:
if resp.status_code == requests.codes['FORBIDDEN']:
raise RuntimeError('Invalid MAL credentials!')
if not resp.status_code == requests.codes['ALL_GOOD']:
raise RuntimeError('MAL request failure!')
示例10: is_bot_avaliable
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def is_bot_avaliable(user_id):
"""
Returns true if the given user_id is an active bot that is available (i.e. is
not currently 'active' which would mean it is in use by another user).
"""
api_url = 'https://slack.com/api/users.getPresence'
response = requests.get(api_url, params={'token': UQCSTESTING_USER_TOKEN, 'user': user_id})
if response.status_code != requests.codes['ok']:
return False
json_contents = json.loads(response.content)
return json_contents['ok'] and json_contents['presence'] == 'away'
示例11: get_free_test_bot
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def get_free_test_bot():
"""
Pings a channel on the UQCSTesting Slack that contains all the available
bots, and Mitch. We can poll this channel to find bots which are 'away'
(that is, not currently being used by anyone else)
Returns info about the bot
See https://api.slack.com/methods/users.info for the contents of info
"""
api_url = 'https://slack.com/api/conversations.members'
response = requests.get(api_url, params={'token': UQCSTESTING_USER_TOKEN,
'channel': SECRET_BOT_MEETING_ROOM})
if response.status_code != requests.codes['ok']:
LOGGER.error(f'Received status code {response.status.code}')
sys.exit(1)
json_contents = json.loads(response.content)
if not json_contents['ok']:
LOGGER.error(json_contents['error'])
sys.exit(1)
for user_id in json_contents['members']:
info = get_user_info(user_id)
if is_active_bot(info) and is_bot_avaliable(user_id):
return info
return None
示例12: send_notification
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def send_notification(self, message):
try:
provider = self._settings.get(["notification_provider"])
if provider == 'ifttt':
event = self._settings.get(["notification_event_name"])
api_key = self._settings.get(["notification_api_key"])
self._logger.debug("Sending notification to: %s with msg: %s with key: %s", provider, message,
api_key)
try:
res = self.ifttt_notification(message, event, api_key)
except requests.exceptions.ConnectionError:
self._logger.info("Error: Could not connect to IFTTT")
except requests.exceptions.HTTPError:
self._logger.info("Error: Received invalid response")
except requests.exceptions.Timeout:
self._logger.info("Error: Request timed out")
except requests.exceptions.TooManyRedirects:
self._logger.info("Error: Too many redirects")
except requests.exceptions.RequestException as reqe:
self._logger.info("Error: {e}".format(e=reqe))
if res.status_code != requests.codes['ok']:
try:
j = res.json()
except ValueError:
self._logger.info('Error: Could not parse server response. Event not sent')
for err in j['errors']:
self._logger.info('Error: {}'.format(err['message']))
except Exception as ex:
self.log_error(ex)
pass
示例13: transcribe
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def transcribe(self, fp):
sttHeaders = {'Authorization': 'Bearer %s' % self.key,
'accept': 'application/json',
'Content-Type': 'audio/wav'}
audio = fp.read()
sttData = requests.post('https://api.wit.ai/speech?v=20170307',
data=audio,
headers=sttHeaders)
try:
sttData.raise_for_status()
except requests.exceptions.HTTPError:
self._logger.critical('Request failed with http status %d',
sttData.status_code)
return []
if sttData.status_code == requests.codes['forbidden']:
self._logger.warning('Request forbidden, check your API key')
return []
try:
sttResponse = sttData.json()['_text']
if len(sttResponse) == 0:
raise ValueError('Nothing transcribed.')
except ValueError as e:
self._logger.warning('Empty response: %s', e.args[0])
results = []
except (KeyError, IndexError):
self._logger.warning('Cannot parse response.', exc_info=True)
results = []
else:
results = [sttResponse.upper()]
self._logger.info('Transcribed: %r', results)
return results
示例14: query
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def query(query_parts, distributors, query_type=QUERY_MATCH):
'''Send query to server and return results.'''
##TODO this `dist_xlate` have to be better coded into this file.
dist_xlate = distributors_modules_dict['api_partinfo_kitspace']['dist_translation']
def find_key(input_dict, value):
return next((k for k, v in input_dict.items() if v == value), None)
distributors = ([find_key(dist_xlate, d) for d in distributors])
query_type = re.sub('\{DISTRIBUTORS\}', '["'+ '","'.join(distributors) +'"]' , query_type)
#r = requests.post(QUERY_URL, {"query": QUERY_SEARCH, "variables": variables}) #TODO future use for ISSUE #17
variables = re.sub('\'', '\"', str(query_parts))
variables = re.sub('\s', '', variables)
# Python 2 prepends a 'u' before the query strings and this makes PartInfo
# complain, so remove them.
variables = re.sub(':u"', ':"', variables)
variables = re.sub('{u"', '{"', variables)
variables = '{{"input":{}}}'.format(variables)
response = requests.post(QUERY_URL, {'query': query_type, "variables": variables})
if response.status_code == requests.codes['ok']: #200
results = json.loads(response.text)
return results
elif response.status_code == requests.codes['not_found']: #404
raise Exception('Kitspace server not found check your internet connection.')
elif response.status_code == requests.codes['request_timeout']: #408
raise Exception('KitSpace is not responding.')
elif response.status_code == requests.codes['bad_request']: #400
raise Exception('Bad request to Kitspace server probably due to an incorrect string format check your `manf#` codes and contact the suport team.')
elif response.status_code == requests.codes['gateway_timeout']: # 504
raise Exception('One of the internal Kitspace services may experiencing problems. Contact the Kitspace support.')
else:
raise Exception('Kitspace error: ' + str(response.status_code))
示例15: obtener_token
# 需要导入模块: import requests [as 别名]
# 或者: from requests import codes [as 别名]
def obtener_token(self, id=uuid.uuid4()):
soapreq = self.__generar_soapreq__(id)
headers = {
'Content-type': 'text/xml;charset="utf-8"',
'Accept': 'text/xml',
'Cache-Control': 'no-cache',
'SOAPAction': self.SOAP_ACTION
}
response = requests.post(self.SOAP_URL, data=soapreq, headers=headers, verify=True)
if response.status_code != requests.codes['ok']:
if not response.text.startswith('<s:Envelope'):
ex = 'El webservice Autenticacion responde: {}'.format(response.text)
else:
resp_xml = etree.fromstring(response.text)
ex = resp_xml.find('s:Body/s:Fault/faultstring', namespaces=self.NSMAP).text
raise Exception(ex)
if not response.text.startswith('<s:Envelope'):
ex = 'El webservice Autenticacion responde: {}'.format(response.text)
raise Exception(ex)
nsmap= {
's': 'http://schemas.xmlsoap.org/soap/envelope/',
None: 'http://DescargaMasivaTerceros.gob.mx'
}
resp_xml = etree.fromstring(response.text)
token = resp_xml.find('s:Body/AutenticaResponse/AutenticaResult', namespaces=nsmap)
return token.text