解压一个文件到s3

Unzip a file to s3

我正在寻找一种简单的方法来将 s3 存储桶中存在的 zip/gzip 提取到同一存储桶位置并删除父 zip/gzip 文件 post 提取。

我目前无法使用任何 API 实现此目的。

尝试过原生boto、pyfilesystem(fs)、s3fs。 源链接和目标链接似乎是这些功能的问题。

(与 Python 2.x/3.x & Boto 2.x 一起使用)

我看到有一个 API 用于 node.js(unzip-to-s3) 来完成这项工作,但是 none 用于 python.

我能想到的几个实现:

  1. 一个简单的 API 提取同一存储桶中的 zip 文件。
  2. 使用 s3 作为文件系统并操作数据
  3. 使用数据管道实现此目的
  4. 将 zip 传输到 ec2,解压并复制回 s3。

选项 4 是最不受欢迎的选项,以最大限度地减少 ec2 插件的架构开销。

在实现此功能方面需要支持,并在稍后阶段集成到 lambda。非常感谢任何指向这些实现的指针。

提前致谢,

孙达

您可以尝试 https://www.cloudzipinc.com/ unzips/expands 几种不同格式的存档从 S3 到您的存储桶中的目标。我用它来将数字目录的组件解压缩到 S3 中。

已使用ec2实例解决。 将 s3 文件复制到 ec2 中的本地目录 并将该目录复制回 S3 存储桶。

示例解压到 ec2 实例中的本地目录

def s3Unzip(srcBucket,dst_dir):  
'''
function to decompress the s3 bucket contents to local machine 

Args:
srcBucket (string): source bucket name 
dst_dir (string): destination location in the local/ec2 local file system

Returns:
None
'''      
#bucket = s3.lookup(bucket)
s3=s3Conn
path=''

bucket = s3.lookup(bucket_name)
for key in bucket:
    path = os.path.join(dst_dir, key.name)
    key.get_contents_to_filename(path)
    if path.endswith('.zip'):
        opener, mode = zipfile.ZipFile, 'r'
    elif path.endswith('.tar.gz') or path.endswith('.tgz'):
        opener, mode = tarfile.open, 'r:gz'
    elif path.endswith('.tar.bz2') or path.endswith('.tbz'):
        opener, mode = tarfile.open, 'r:bz2'
    else: 
        raise ValueError ('unsuppported format')

    try:
        os.mkdir(dst_dir)
        print ("local directories created")
    except Exception:
        logger_s3.warning ("Exception in creating local directories to extract zip file/ folder already existing")    
    cwd = os.getcwd()
    os.chdir(dst_dir)

    try:
        file = opener(path, mode)
        try: file.extractall()
        finally: file.close()
        logger_s3.info('(%s) extracted successfully to %s'%(key ,dst_dir))
    except Exception as e:
        logger_s3.error('failed to extract (%s) to %s'%(key ,dst_dir))
        os.chdir(cwd)   
s3.close

要上传到 mysql 实例的示例代码

使用"LOAD DATA LOCAL INFILE"查询直接上传到mysql

def upload(file_path,timeformat):
'''
function to upload a  csv file data to mysql rds 

Args:
file_path (string): local file path
timeformat (string): destination bucket to copy data

Returns:
None    
'''  
for file in file_path:
    try:
        con = connect()
        cursor = con.cursor()

        qry="""LOAD DATA LOCAL INFILE '%s' INTO TABLE xxxx FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (col1 , col2 ,col3, @datetime , col4 ) set datetime = str_to_date(@datetime,'%s');""" %(file,timeformat)
        cursor.execute(qry)
        con.commit()
        logger_rds.info ("Loading file:"+file)
    except Exception:
        logger_rds.error ("Exception in uploading "+file)
         ##Rollback in case there is any error
        con.rollback()
cursor.close()
# disconnect from server
con.close()