且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用django-storages和boto3获取AWS S3对象密钥

更新时间:2021-09-28 21:32:19

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

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)