2016-11-07 49 views
0

你好我試圖用博託2.43到Python連接到S3在法蘭克福地區,我想打印區名稱內容... 以下是我的代碼:Python的博託連接到S3投擲的錯誤

from boto.s3.connection import S3Connection 
hostname='s3.eu-central-1.amazonaws.com' 
conn = S3Connection(aws_access_key_id,aws_secret_access_key, host=hostname) 
bucket_name = conn.get_bucket('jd-eu01-isg-analytics-data-from-us01', validate=False) 
for key in bucket_name.list(prefix='EU_Scripts_For_Frankfurt/'): 
    print key 
    continue 

當我執行它時,會拋出以下錯誤:

File "/usr/lib/python2.7/site-packages/boto/s3/bucketlistresultset.py", line 34, in bucket_lister 
    encoding_type=encoding_type) 
    File "/usr/lib/python2.7/site-packages/boto/s3/bucket.py", line 473, in get_all_keys 
    '', headers, **params) 
    File "/usr/lib/python2.7/site-packages/boto/s3/bucket.py", line 399, in _get_all 
    query_args=query_args) 
    File "/usr/lib/python2.7/site-packages/boto/s3/connection.py", line 668, in make_request 
    retry_handler=retry_handler 
    File "/usr/lib/python2.7/site-packages/boto/connection.py", line 1071, in make_request 
    retry_handler=retry_handler) 
    File "/usr/lib/python2.7/site-packages/boto/connection.py", line 927, in _mexe 
    request.authorize(connection=self) 
    File "/usr/lib/python2.7/site-packages/boto/connection.py", line 377, in authorize 
    connection._auth_handler.add_auth(self, **kwargs) 
    File "/usr/lib/python2.7/site-packages/boto/auth.py", line 727, in add_auth 
    **kwargs) 
    File "/usr/lib/python2.7/site-packages/boto/auth.py", line 546, in add_auth 
    string_to_sign = self.string_to_sign(req, canonical_request) 
    File "/usr/lib/python2.7/site-packages/boto/auth.py", line 486, in string_to_sign 
    sts.append(self.credential_scope(http_request)) 
    File "/usr/lib/python2.7/site-packages/boto/auth.py", line 468, in credential_scope 
    region_name = self.determine_region_name(http_request.host) 
    File "/usr/lib/python2.7/site-packages/boto/auth.py", line 662, in determine_region_name 
    return region_name 
UnboundLocalError: local variable 'region_name' referenced before assignment 

如何解決此問題?這是因爲博託版本?任何解決方案請

回答

-1

使用boto3,它更容易。 boto2不被AWS支持,boto已經被棄用,並且不打算使用功能

由於找不到區域而彈出錯誤。 Boto/boto3 API將檢查boto/boto3服務初始化階段內的區域名稱。如果你沒有指定它,它會在憑證文件或環境變量(例如〜/ .aws/config)中查找默認區域名稱定義。

即使您明確指定了S3端點URL,情況也是如此。如果您不想對憑證,區域名稱進行硬編碼,則必須按照此處指定的方式設置AWS憑證:credential configuration

使用憑證文件/環境變量製作boto/boto3將使您的代碼更加清晰和靈活,例如,你甚至可以在不改變代碼的情況下使用STS。例如: -

import boto3 
# You can choose between service resource or service client. 
s3 = boto3.client("s3") 

response = s3.list_objects_v2(
    Bucket="jd-eu01-isg-analytics-data-from-us01", 
    Prefix="EU_Scripts_For_Frankfurt" 
) 

for content in response["Contents"]: 
    print content["Key"] 

儘管如此,你仍然可以通過將參數在初始化博託/ boto3資源硬編碼的訪問密鑰ID,secre_key,區域名稱等。 (boto API是類似的)

import boto3 
s3 = boto3.client(
    "s3", 
    region_name = "eu-central-1", 
    aws_access_key_id = 'xxxxxxxx", 
    aws_secret_access_key= = "yyyyyyy")