如何使用django-storages和boto3获取AWS S3对象密钥 [英] How to get the aws s3 object key using django-storages and boto3

查看:136
本文介绍了如何使用django-storages和boto3获取AWS S3对象密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用aws s3将django-storage和boto3用于媒体和静态文件.我需要获取aws s3存储桶的对象密钥,以便可以为该对象生成一个URL.

I am using django-storage and boto3 for media and static files using aws s3. I need to get the object key of aws s3 bucket, so that I can generate a url for that object.

client = boto3.client('s3')
bucket_name = 'django-bucket'

key = ???

u = client.generate_presigned_url('get_object', Params = {'Bucket': bucket_name, 'Key': key,'ResponseContentType':'image/jpeg', 'ResponseContentDisposition': 'attachment; filename="your-filename.jpeg"'}, ExpiresIn = 1000)

这些是我的设置:

STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'
STATICFILES_STORAGE = 'myproject.custom_storages.StaticStorage'
DEFAULT_FILE_STORAGE = 'myproject.custom_storages.MediaStorage'
AWS_ACCESS_KEY_ID = "my_access_key_id"
AWS_SECRET_ACCESS_KEY = "my_secret_access_key"
AWS_STORAGE_BUCKET_NAME = "django-bucket"
AWS_QUERYSTRING_AUTH = False
AWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com"
# static media settings
STATIC_URL = "https://" + AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com/"
MEDIA_URL = STATIC_URL + "media/"
ADMIN_MEDIA_PREFIX = STATIC_URL + "admin/"

我可以获取图像文件的文件路径

I can get the file path of the image file

ui = UserImage.objects.get(user=user_id, image=image_id)
url = ui.image.url

'https://django-bucket.s3.amazonaws.com/media/user_image/1497598249_49.jpeg'

但是我不知道如何获取s3对象密钥,以便为该对象生成一个url.

But I don't know how to get the s3 object key so that I can generate a url for that object.

推荐答案

似乎可以从文件字段存储"位置值和文件名称"(这是位置"的路径)构造前缀到文件-它包括我们大多数人认为的文件名称").

It would seem the prefix can be constructed from the file field 'storage' location value and the file 'name' (which is a path from the 'location' to the file - it includes what most of us think of as the file 'name').

以下是应该完成工作的功能的快速演示:

Here's a quick demo of a function that should get the job done:

import os

def get_file_key(file_field):
    return os.path.join(file_field.storage.location, file_field.name)

用法如下:

prefix = get_file_key(my_model_instance.relevant_file_field)

注意:

您可能需要根据需要在函数中/周围实现错误捕获的健全性检查-例如,如果file_field为None,该函数将引发AttributeError-在大多数情况下,您几乎肯定不希望如果由于某种原因field.name由于错误或由于某种原因保存了空字符串而返回了空字符串(或者如果未设置位置则为'/'),则只能以该位置结尾

You'll probably want to implement error catching sanity checking in/around the function as appropriate for your needs - for example the function will raise an AttributeError if the file_field is None - and in most scenarios you almost certainly wouldn't want to end up with just the location if for some reason the field.name returned an empty string as a result of a bug or just because that was saved somehow (or '/' if the location wasn't set)

这篇关于如何使用django-storages和boto3获取AWS S3对象密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆