如何使用python(3.x)将图像从MySql传输到AWS S3存储桶?

时间:2018-11-01 06:59:01

标签: python-3.x amazon-s3 boto3

我在mysql数据库中有一些图像,需要将这些图像传输到aws s3存储桶。我能够从磁盘成功上传文件,但不能直接从数据库上传文件。当前代码如下:

import pymysql
import PIL.Image
import boto3
import botocore
from datetime import datetime

db = pymysql.connect('localhost', 'root', '123456', 'test_db')  
cursor = db.cursor()

query = """select user_id, doc_type, images_pic from user_data where images_pic <> '' limit 5;"""        
data = cursor.execute(query)  
r = cursor.fetchall()
r = list(r)

bucket_name = 'my_buck'
s3 = boto3.client('s3')
#s3.upload_file('testfile.txt', bucket_name, 'testfile.txt') uploads successfully

for row in r:
    folder = "%s" % row[0]
    doc_type = ("%s" % row[1]).lower()
    uimg = io.BytesIO(row[2])
    img_final = PIL.Image.open(uimg)
    #folder = bucket_name.new_key(user_id) this gives error "str object has no attribute 'new_key'"
    s3.upload_file((folder + '/' + img_final + '.' + doc_type), bucket_name, (folder + '/' + img_final + '.' + doc_type))

我可以将图像从数据库保存到磁盘,然后上传到存储桶中,但我想直接执行而不保存到磁盘。

任何帮助表示赞赏。

0 个答案:

没有答案