django aws S3动态定义上传文件路径和文件

时间:2017-11-19 13:20:36

标签: python django amazon-web-services amazon-s3 path

在我的Django应用中, 我想在保存到AWS S3时动态定义上传路径和文件。到目前为止,我能够直接将文件保存到S3,但是我想自己设置路径和文件名。

因此,例如,在上传时我希望它在S3路径中 bucketname \雇员\ file_randomnumber.png

我该怎么办?

以下是我的代码:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

@api_view(['POST'])
def update_employee_image(request):
    # ----- YAML below for Swagger -----
    """
    description: update employee image.
    parameters:
      - name: employee_id
        type: integer
        required: true
        location: form
      - name: face_image
        type: file
        required: true
        location: form
    """
    parser_classes = (FileUploadParser,)
    employee_id = request.POST['employee_id']
    face_image_obj = request.data['face_image']

    employee = Employee.objects.get(id = employee_id)
    logging.debug(f"API employee username {employee.username}")
    #employee.face_image = face_image_obj
    employee.upload = face_image_obj <--- here is where it assign the file to S3
    employee.save()
    return Response("Employee Updated!", status=status.HTTP_200_OK)

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    username = models.CharField(max_length=30, blank=False)
    upload = models.FileField(blank=True) <--- S3 field

https://gitlab.com/firdausmah/railercom/blob/master/railercom/settings.py(AWS设置)

AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}

DEFAULT_FILE_STORAGE = 'railercomapp.storage_backends.MediaStorage'

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/storage_backends.py     来自storages.backends.s3boto3导入S3Boto3Storage

class MediaStorage(S3Boto3Storage):
    location = 'media/yy'
    file_overwrite = False

我已将{django aws S3解决方案基于https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html

1 个答案:

答案 0 :(得分:0)

您可以覆盖存储get_available_name方法。

这是一个例子。修改以获得所需的确切文件名方案。

class MediaStorage(S3Boto3Storage):
    location = 'media/yy'
    file_overwrite = False

    def get_available_name(self, name, max_length=None):
        custom_name = f'/employeeid/{name}_randomnumber.png'
        return super().get_available_name(custom_name, max_length)

文档:Writing a custom storage system