如何使用url访问Python中的s3文件?

2024-04-28 23:49:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编写一个Python脚本,使用它们的url从s3读取和写入文件,例如:“s3:/mybucket/file”。它需要在本地和云中运行,而无需更改任何代码。有办法吗?

编辑:这里有一些好的建议,但我真正想要的是能让我做到这一点:

 myfile = open("s3://mybucket/file", "r")

然后像使用其他文件对象一样使用该文件对象。那会很酷的。如果不存在的话,我可以自己写这样的东西。我可以在simples3或boto上构建抽象层。


Tags: 文件对象代码脚本url编辑s3open
3条回答

对于开场白,应该简单到:

import urllib
opener = urllib.URLopener()
myurl = "https://s3.amazonaws.com/skyl/fake.xyz"
myfile = opener.open(myurl)

如果文件是公共的,这将适用于s3。

要使用boto编写文件,可以这样做:

from boto.s3.connection import S3Connection
conn = S3Connection(AWS_KEY, AWS_SECRET)
bucket = conn.get_bucket(BUCKET)
destination = bucket.new_key()
destination.name = filename
destination.set_contents_from_file(myfile)
destination.make_public()

让我知道这对你是否有效:)

我还没有看到可以直接使用s3url的东西,但是可以使用S3 access librarysimples3看起来不错)和一些简单的字符串操作:

>>> url = "s3:/bucket/path/"
>>> _, path = url.split(":", 1)
>>> path = path.lstrip("/")
>>> bucket, path = path.split("/", 1)
>>> print bucket
'bucket'
>>> print path
'path/'

Here's how they doawscli中:

def find_bucket_key(s3_path):
    """
    This is a helper function that given an s3 path such that the path is of
    the form: bucket/key
    It will return the bucket and the key represented by the s3 path
    """
    s3_components = s3_path.split('/')
    bucket = s3_components[0]
    s3_key = ""
    if len(s3_components) > 1:
        s3_key = '/'.join(s3_components[1:])
    return bucket, s3_key


def split_s3_bucket_key(s3_path):
    """Split s3 path into bucket and key prefix.
    This will also handle the s3:// prefix.
    :return: Tuple of ('bucketname', 'keyname')
    """
    if s3_path.startswith('s3://'):
        s3_path = s3_path[5:]
    return find_bucket_key(s3_path)

你可以用这样的代码

from awscli.customizations.s3.utils import split_s3_bucket_key
import boto3
client = boto3.client('s3')
bucket_name, key_name = split_s3_bucket_key(
    's3://example-bucket-name/path/to/example.txt')
response = client.get_object(Bucket=bucket_name, Key=key_name)

这并没有将与s3键交互作为file like object的目标,但这是朝着这个方向迈出的一步。

相关问题 更多 >