如何将文件保存到s3存储桶

时间:2020-06-27 18:05:47

标签: django amazon-web-services amazon-s3 filepath

我正在尝试创建一个条形码图像文件,该文件将保存到我的aws s3存储桶中的路径。我不知道如何链接到它。我的媒体和静态文件已经在aws上,并且可以正常运行,但是我不知道如何设置此条形码生成器功能的路径以保存到aws s3存储桶中。

感谢您的耐心配合和指导。

我的条形码功能在我看来

def barcodemaker():
    barcodemodel = apps.get_model('barcoder', 'barcodeModel')
    employee = apps.get_model('employees', 'Employee')
    data = employee.objects.filter(id=1)
    try:
        data2 = barcodemodel.objects.latest('id')
    except:   
        data2 = 1002390000
    naa = str(data2)
    naa = int(naa[-10:])
    for i in data:
        id_name= str(i.id)
    naa += random.randint(500, 900)
    mocode = 'M-'+ id_name + '-'+ str(naa)
    b = barcodemodel(barcode_num=str(mocode))
    b.save()
    
    path = (>>>PATH to aws<<<,'static','media','barcodes', mocode+'.png')
    with open(path, 'wb') as f:
        Code128(mocode, writer=ImageWriter()).write(f)
        barcode_context = {
            'mocode':mocode, 'f':f
        }
        return barcode_context


我的设置文件中的我的静态文件设置

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR,"static")
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')


MEDIA_URL = '/profile_image/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')


#S3 BUCKETS CONFIG
# S3 logins Data
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')

AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

1 个答案:

答案 0 :(得分:0)

来自documentation

import logging
import boto3
from botocore.exceptions import ClientError


def upload_file(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = file_name

    # Upload the file
    s3_client = boto3.client('s3')
    try:
        response = s3_client.upload_file(file_name, bucket, object_name)
    except ClientError as e:
        logging.error(e)
        return False
    return True

然后(此处f处于二进制模式):

s3.upload_fileobj(f, "BUCKET_NAME", "OBJECT_NAME")

代码将使用您的环境变量作为访问键。另外,您可以使用以下语法:

client = boto3.client(
    's3',
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY,
    aws_session_token=SESSION_TOKEN,
)