本文整理汇总了Python中boto.exception方法的典型用法代码示例。如果您正苦于以下问题:Python boto.exception方法的具体用法?Python boto.exception怎么用?Python boto.exception使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类boto
的用法示例。
在下文中一共展示了boto.exception方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def setUp(self):
import boto
from boto.exception import NoAuthHandlerFound
from boto.s3.key import Key
keys = ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY']
try:
for k in keys:
os.environ[k]
self.bucket_name = os.environ.get('AWS_TEST_BUCKET', 'drf-to-s3-test')
except KeyError:
self.skipTest('To test s3, set %s in .env' % ' and '.join(keys))
conn = boto.connect_s3()
bucket = conn.get_bucket(self.bucket_name)
k = Key(bucket)
k.key = "%s%s.txt" % (str(uuid.uuid4()), self.prefix)
k.set_contents_from_string('This is a test of S3')
self.existing_key = k.key
self.existing_key_etag = k.etag
self.bucket = bucket
self.nonexisting_key = "%s%s.txt" % (str(uuid.uuid4()), self.prefix)
self.new_key = None
示例2: upload_template
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def upload_template(config, tpl, stack_name):
"""Upload a template to S3 bucket and returns S3 key url"""
bn = config.get('templates_bucket_name', '{}-stacks-{}'.format(config['env'], config['region']))
try:
b = config['s3_conn'].get_bucket(bn)
except boto.exception.S3ResponseError as err:
if err.code == 'NoSuchBucket':
print('Bucket {} does not exist.'.format(bn))
else:
print(err)
sys.exit(1)
h = _calc_md5(tpl)
k = boto.s3.key.Key(b)
k.key = '{}/{}/{}'.format(config['env'], stack_name, h)
k.set_contents_from_string(tpl)
url = k.generate_url(expires_in=30)
return url
示例3: get_domain
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def get_domain(self, domain_name, validate=True):
"""
Retrieves a :py:class:`boto.sdb.domain.Domain` object whose name
matches ``domain_name``.
:param str domain_name: The name of the domain to retrieve
:keyword bool validate: When ``True``, check to see if the domain
actually exists. If ``False``, blindly return a
:py:class:`Domain <boto.sdb.domain.Domain>` object with the
specified name set.
:raises:
:py:class:`boto.exception.SDBResponseError` if ``validate`` is
``True`` and no match could be found.
:rtype: :py:class:`boto.sdb.domain.Domain`
:return: The requested domain
"""
domain = Domain(self, domain_name)
if validate:
self.select(domain, """select * from `%s` limit 1""" % domain_name)
return domain
示例4: lookup
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def lookup(self, domain_name, validate=True):
"""
Lookup an existing SimpleDB domain. This differs from
:py:meth:`get_domain` in that ``None`` is returned if ``validate`` is
``True`` and no match was found (instead of raising an exception).
:param str domain_name: The name of the domain to retrieve
:param bool validate: If ``True``, a ``None`` value will be returned
if the specified domain can't be found. If ``False``, a
:py:class:`Domain <boto.sdb.domain.Domain>` object will be dumbly
returned, regardless of whether it actually exists.
:rtype: :class:`boto.sdb.domain.Domain` object or ``None``
:return: The Domain object or ``None`` if the domain does not exist.
"""
try:
domain = self.get_domain(domain_name, validate)
except:
domain = None
return domain
示例5: get_domain_and_name
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def get_domain_and_name(self, domain_or_name):
"""
Given a ``str`` or :class:`boto.sdb.domain.Domain`, return a
``tuple`` with the following members (in order):
* In instance of :class:`boto.sdb.domain.Domain` for the requested
domain
* The domain's name as a ``str``
:type domain_or_name: ``str`` or :class:`boto.sdb.domain.Domain`
:param domain_or_name: The domain or domain name to get the domain
and name for.
:raises: :class:`boto.exception.SDBResponseError` when an invalid
domain name is specified.
:rtype: tuple
:return: A ``tuple`` with contents outlined as per above.
"""
if (isinstance(domain_or_name, Domain)):
return (domain_or_name, domain_or_name.name)
else:
return (self.get_domain(domain_or_name), domain_or_name)
示例6: __init__
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def __init__(self, **args):
self.args = args
self.check_for_credential_file()
self.check_for_env_url()
if 'host' not in self.args:
if self.Regions:
region_name = self.args.get('region_name',
self.Regions[0]['name'])
for region in self.Regions:
if region['name'] == region_name:
self.args['host'] = region['endpoint']
if 'path' not in self.args:
self.args['path'] = self.Path
if 'port' not in self.args:
self.args['port'] = self.Port
try:
super(AWSQueryService, self).__init__(**self.args)
self.aws_response = None
except boto.exception.NoAuthHandlerFound:
raise NoCredentialsError()
示例7: set_xml_logging
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def set_xml_logging(self, logging_str, headers=None):
"""
Set logging on a bucket directly to the given xml string.
:type logging_str: unicode string
:param logging_str: The XML for the bucketloggingstatus which
will be set. The string will be converted to utf-8 before
it is sent. Usually, you will obtain this XML from the
BucketLogging object.
:rtype: bool
:return: True if ok or raises an exception.
"""
body = logging_str
if not isinstance(body, bytes):
body = body.encode('utf-8')
response = self.connection.make_request('PUT', self.name, data=body,
query_args='logging', headers=headers)
body = response.read()
if response.status == 200:
return True
else:
raise self.connection.provider.storage_response_error(
response.status, response.reason, body)
示例8: _check_num_ops
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def _check_num_ops(self, type_, response_num):
"""Raise exception if number of ops in response doesn't match commit
:type type_: str
:param type_: Type of commit operation: 'add' or 'delete'
:type response_num: int
:param response_num: Number of adds or deletes in the response.
:raises: :class:`boto.cloudsearch.document.CommitMismatchError`
"""
commit_num = len([d for d in self.doc_service.documents_batch
if d['type'] == type_])
if response_num != commit_num:
raise CommitMismatchError(
'Incorrect number of {0}s returned. Commit: {1} Response: {2}'\
.format(type_, commit_num, response_num))
示例9: __init__
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def __init__(self, **args):
self.args = args
self.check_for_credential_file()
self.check_for_env_url()
if 'host' not in self.args:
if self.Regions:
region_name = self.args.get('region_name',
self.Regions[0]['name'])
for region in self.Regions:
if region['name'] == region_name:
self.args['host'] = region['endpoint']
if 'path' not in self.args:
self.args['path'] = self.Path
if 'port' not in self.args:
self.args['port'] = self.Port
try:
boto.connection.AWSQueryConnection.__init__(self, **self.args)
self.aws_response = None
except boto.exception.NoAuthHandlerFound:
raise NoCredentialsError()
示例10: validate
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def validate(self, quiet=False, full=False):
error = False
for name, data in self.templates.iteritems():
if 'error' in data:
error = True
print("{} error: {}".format(name, data['error'][1]))
continue
if full:
# Run server-based validation
# Trying to use template_body fails randomly, probably due to
# length limits.
bucket = self.s3.get_bucket('balanced-cfn-us-east-1')
key = bucket.get_key('validation_tmp', validate=False)
key.set_contents_from_string(data['json'])
try:
self.cfn.validate_template(template_url='https://balanced-cfn-us-east-1.s3.amazonaws.com/validation_tmp')
except boto.exception.BotoServerError, e:
if e.status != 400:
raise
error = True
print("{} error: {}".format(name, e.message))
continue
finally:
示例11: copy
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def copy(src_bucket, src_key, dst_bucket, dst_key, src_etag=None, validate_src_etag=False):
'''
Copy a key from one bucket to another.
If validate_etag is True, the ETag must match. Raises
ObjectNotFoundException if the key does not exist,
or the ETag doesn't match.
We return the same error in either case, since a mismatched
ETag might mean the user wasn't the last to upload the object.
If the bucket is private they may not even know it exists.
By returning the same error, we avoid giving out extra
information.
'''
import boto
from boto.exception import S3ResponseError
conn = boto.connect_s3()
bucket = conn.get_bucket(dst_bucket)
if validate_src_etag:
headers = {
'x-amz-copy-source-if-match': src_etag,
}
else:
headers = {}
try:
bucket.copy_key(
new_key_name=dst_key,
src_bucket_name=src_bucket,
src_key_name=src_key,
headers=headers
)
except S3ResponseError as e:
if e.status in [status.HTTP_404_NOT_FOUND, status.HTTP_412_PRECONDITION_FAILED]:
raise ObjectNotFoundException()
else:
raise
示例12: _get_s3_bucket
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def _get_s3_bucket(conn, bucket_name):
from boto.exception import S3ResponseError
try:
bucket = conn.get_bucket(bucket_name)
except S3ResponseError as e:
if e.status == 404:
bucket = conn.create_bucket(bucket_name)
else:
raise
return bucket
示例13: delete_stream
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def delete_stream(self, stream_name):
"""
Deletes a stream and all its shards and data. You must shut
down any applications that are operating on the stream before
you delete the stream. If an application attempts to operate
on a deleted stream, it will receive the exception
`ResourceNotFoundException`.
If the stream is in the `ACTIVE` state, you can delete it.
After a `DeleteStream` request, the specified stream is in the
`DELETING` state until Amazon Kinesis completes the deletion.
**Note:** Amazon Kinesis might continue to accept data read
and write operations, such as PutRecord, PutRecords, and
GetRecords, on a stream in the `DELETING` state until the
stream deletion is complete.
When you delete a stream, any shards in that stream are also
deleted, and any tags are dissociated from the stream.
You can use the DescribeStream operation to check the state of
the stream, which is returned in `StreamStatus`.
`DeleteStream` has a limit of 5 transactions per second per
account.
:type stream_name: string
:param stream_name: The name of the stream to delete.
"""
params = {'StreamName': stream_name, }
return self.make_request(action='DeleteStream',
body=json.dumps(params))
示例14: encode_string
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def encode_string(self, value):
"""Convert ASCII, Latin-1 or UTF-8 to pure Unicode"""
if not isinstance(value, str):
return value
try:
return six.text_type(value, 'utf-8')
except:
# really, this should throw an exception.
# in the interest of not breaking current
# systems, however:
arr = []
for ch in value:
arr.append(six.unichr(ord(ch)))
return u"".join(arr)
示例15: __init__
# 需要导入模块: import boto [as 别名]
# 或者: from boto import exception [as 别名]
def __init__(self, response, doc_service, sdf, signed_request=False):
self.response = response
self.doc_service = doc_service
self.sdf = sdf
self.signed_request = signed_request
if self.signed_request:
self.content = response
else:
_body = response.content.decode('utf-8')
try:
self.content = json.loads(_body)
except:
boto.log.error('Error indexing documents.\nResponse Content:\n{0}'
'\n\nSDF:\n{1}'.format(_body, self.sdf))
raise boto.exception.BotoServerError(self.response.status_code, '',
body=_body)
self.status = self.content['status']
if self.status == 'error':
self.errors = [e.get('message') for e in self.content.get('errors',
[])]
for e in self.errors:
if "Illegal Unicode character" in e:
raise EncodingError("Illegal Unicode character in document")
elif e == "The Content-Length is too long":
raise ContentTooLongError("Content was too long")
else:
self.errors = []
self.adds = self.content['adds']
self.deletes = self.content['deletes']
self._check_num_ops('add', self.adds)
self._check_num_ops('delete', self.deletes)