本文整理匯總了Python中botocore.awsrequest.AWSRequest方法的典型用法代碼示例。如果您正苦於以下問題:Python awsrequest.AWSRequest方法的具體用法?Python awsrequest.AWSRequest怎麽用?Python awsrequest.AWSRequest使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類botocore.awsrequest
的用法示例。
在下文中一共展示了awsrequest.AWSRequest方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: base_signer_setup_s3v4
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def base_signer_setup_s3v4() -> dict:
emitter = mock.AsyncMock()
emitter.emit_until_response.return_value = (None, None)
credentials = aiobotocore.credentials.AioCredentials('key', 'secret')
request_signer = aiobotocore.signers.AioRequestSigner(ServiceId('service_name'),
'region_name', 'signing_name',
's3v4', credentials, emitter)
signer = aiobotocore.signers.AioS3PostPresigner(request_signer)
return {
'credentials': credentials,
'emitter': emitter,
'signer': signer,
'fixed_credentials': await credentials.get_frozen_credentials(),
'request': AWSRequest()
}
示例2: test_patch_http_requests_send
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def test_patch_http_requests_send(mock_context_wrapper):
if sys.version_info[0] != 3:
pytest.skip("this test requires python 3+, skipping")
patch_http_requests(mock_context_wrapper, None, None)
assert hasattr(BotocoreSession.send, "__wrapped__")
assert hasattr(BotocoreVendoredSession.send, "__wrapped__")
botocore_session = BotocoreSession()
botocore_session.send(AWSRequest(method="GET", url="https://www.iopipe.com"))
botocore_vendored_session = BotocoreVendoredSession()
request = PreparedRequest()
request.prepare(method="GET", url="https://www.iopipe.com")
botocore_vendored_session.send(request)
示例3: test_make_api_call_throws_when_retries_exhausted
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def test_make_api_call_throws_when_retries_exhausted(self, client_mock):
prepared_request = AWSRequest('GET', 'http://lyft.com').prepare()
send_mock = client_mock._endpoint.http_session.send
send_mock.side_effect = [
botocore.exceptions.ConnectionError(error="problems"),
botocore.exceptions.ConnectionError(error="problems"),
botocore.exceptions.ConnectionError(error="problems"),
botocore.exceptions.ReadTimeoutError(endpoint_url="http://lyft.com"),
]
c = Connection()
c._max_retry_attempts_exception = 3
c._create_prepared_request = mock.Mock()
c._create_prepared_request.return_value = prepared_request
with self.assertRaises(botocore.exceptions.ReadTimeoutError):
c._make_api_call('DescribeTable', {'TableName': 'MyTable'})
self.assertEqual(len(send_mock.mock_calls), 4)
for call in send_mock.mock_calls:
self.assertEqual(call[1][0], prepared_request)
示例4: test_make_api_call_throws_retry_disabled
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def test_make_api_call_throws_retry_disabled(self, client_mock, rand_int_mock):
prepared_request = AWSRequest('GET', 'http://lyft.com').prepare()
send_mock = client_mock._endpoint.http_session.send
send_mock.side_effect = [
botocore.exceptions.ReadTimeoutError(endpoint_url='http://lyft.com'),
]
c = Connection(read_timeout_seconds=11, base_backoff_ms=3, max_retry_attempts=0)
c._create_prepared_request = mock.Mock()
c._create_prepared_request.return_value = prepared_request
assert c._base_backoff_ms == 3
with self.assertRaises(botocore.exceptions.ReadTimeoutError):
c._make_api_call('DescribeTable', {'TableName': 'MyTable'})
self.assertEqual(len(send_mock.mock_calls), 1)
rand_int_mock.assert_not_called()
for call in send_mock.mock_calls:
self.assertEqual(call[1][0], prepared_request)
示例5: sign_request
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def sign_request(self, region, url_to_sign):
credentials = self._session.get_credentials()
signer = SigV4Auth(credentials, 'codecommit', region)
request = AWSRequest()
request.url = url_to_sign
request.method = 'GIT'
now = datetime.datetime.utcnow()
request.context['timestamp'] = now.strftime('%Y%m%dT%H%M%S')
split = urlsplit(request.url)
# we don't want to include the port number in the signature
hostname = split.netloc.split(':')[0]
canonical_request = '{0}\n{1}\n\nhost:{2}\n\nhost\n'.format(
request.method,
split.path,
hostname)
logger.debug("Calculating signature using v4 auth.")
logger.debug('CanonicalRequest:\n%s', canonical_request)
string_to_sign = signer.string_to_sign(request, canonical_request)
logger.debug('StringToSign:\n%s', string_to_sign)
signature = signer.signature(string_to_sign, request)
logger.debug('Signature:\n%s', signature)
return '{0}Z{1}'.format(request.context['timestamp'], signature)
示例6: post_data_to_es
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def post_data_to_es(
payload, region, creds, host,
path, method='POST', proto='https://'):
print("URL:{}".format(proto+host+path))
req = AWSRequest(
method=method,
url=proto+host+path,
data=payload,
headers={'Host': host, 'Content-Type': 'application/json'})
SigV4Auth(creds, 'es', region).add_auth(req)
http_session = BotocoreHTTPSession()
res = http_session.send(req.prepare())
print("STATUS_CODE:{}".format(res.status_code))
print("CONTENT:{}".format(res._content))
print("ALL:{}".format(res))
if res.status_code >= 200 and res.status_code <= 299:
return res._content
else:
raise ES_Exception(res.status_code, res._content)
# Extracts the DynamoDB table from an ARN
示例7: _get_v4_signed_headers
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def _get_v4_signed_headers(self):
"""Returns V4 signed get-caller-identity request headers"""
if self.aws_session is None:
boto_session = session.Session()
creds = boto_session.get_credentials()
else:
creds = self.aws_session.get_credentials()
if creds is None:
raise CerberusClientException("Unable to locate AWS credentials")
readonly_credentials = creds.get_frozen_credentials()
# hardcode get-caller-identity request
data = OrderedDict((('Action', 'GetCallerIdentity'), ('Version', '2011-06-15')))
url = 'https://sts.{}.amazonaws.com/'.format(self.region)
request_object = awsrequest.AWSRequest(method='POST', url=url, data=data)
signer = auth.SigV4Auth(readonly_credentials, 'sts', self.region)
signer.add_auth(request_object)
return request_object.headers
示例8: base_signer_setup
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def base_signer_setup() -> dict:
emitter = mock.AsyncMock()
emitter.emit_until_response.return_value = (None, None)
credentials = aiobotocore.credentials.AioCredentials('key', 'secret')
signer = aiobotocore.signers.AioRequestSigner(ServiceId('service_name'),
'region_name', 'signing_name',
'v4', credentials, emitter)
return {
'credentials': credentials,
'emitter': emitter,
'signer': signer,
'fixed_credentials': await credentials.get_frozen_credentials(),
'request': AWSRequest()
}
示例9: test_make_api_call_retries_properly
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def test_make_api_call_retries_properly(self, client_mock):
deserializable_response = AWSResponse(
url='',
status_code=200,
headers={},
raw='',
)
deserializable_response._content = json.dumps({'hello': 'world'}).encode('utf-8')
bad_response = AWSResponse(
url='',
status_code=503,
headers={},
raw='',
)
bad_response._content = 'not_json'.encode('utf-8')
prepared_request = AWSRequest('GET', 'http://lyft.com').prepare()
send_mock = client_mock._endpoint.http_session.send
send_mock.side_effect = [
bad_response,
botocore.exceptions.ReadTimeoutError(endpoint_url='http://lyft.com'),
bad_response,
deserializable_response,
]
c = Connection()
c._max_retry_attempts_exception = 3
c._create_prepared_request = mock.Mock()
c._create_prepared_request.return_value = prepared_request
c._make_api_call('DescribeTable', {'TableName': 'MyTable'})
self.assertEqual(len(send_mock.mock_calls), 4)
for call in send_mock.mock_calls:
self.assertEqual(call[1][0], prepared_request)
示例10: test_sign_request
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def test_sign_request(self):
request = AWSRequest(method='POST', url='http://localhost:8000/', headers={}, data={'foo': 'bar'})
c = Connection(region='us-west-1')
c._sign_request(request)
assert 'X-Amz-Date' in request.headers
assert 'Authorization' in request.headers
assert 'us-west-1' in request.headers['Authorization']
assert request.headers['Authorization'].startswith('AWS4-HMAC-SHA256')
示例11: get_uri
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def get_uri(prefix, uri):
try:
session = URLLib3Session()
r = session.send(AWSRequest('GET', uri).prepare())
if r.status_code == 200:
return r.text
else:
raise ResourceLoadingError(
"received non 200 status code of %s" % (
r.status_code))
except Exception as e:
raise ResourceLoadingError('Unable to retrieve %s: %s' % (uri, e))
示例12: __call__
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def __call__(self, r):
url = urlparse(r.url)
path = url.path or '/'
querystring = ''
if url.query:
querystring = '?' + urlencode(parse_qs(url.query, keep_blank_values=True), doseq=True)
headers = {k.lower():v for k,v in r.headers.items()}
location = headers.get('host') or url.netloc
safe_url = url.scheme + '://' + location.split(':')[0] + path + querystring
request = AWSRequest(method=r.method.upper(), url=safe_url, data=r.body)
SigV4Auth(self.credentials, self.service, self.region).add_auth(request)
r.headers.update(dict(request.headers.items()))
return r
示例13: sign_headers
# 需要導入模塊: from botocore import awsrequest [as 別名]
# 或者: from botocore.awsrequest import AWSRequest [as 別名]
def sign_headers(*, url: str, payload: Dict):
'''Sign AWS API request headers'''
segments = urllib.parse.urlparse(url).netloc.split('.')
service = segments[0]
region = segments[1]
request = awsrequest.AWSRequest(
method='POST',
url=url,
data=json.dumps(payload),
)
auth.SigV4Auth(AWS_CREDENTIALS, service, region).add_auth(request)
return dict(request.headers.items())