Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy file from one path to other using django-storages and amazon S3?

im = storage.open('old_path_filename', 'r')
strorage.save('new_path_with_old_filename', im)

In my django proect I am using django-storages and amazon S3 for my static and media files. I nead to save old file with new path in amazon and old filename. Could you help me?

like image 298
pmoniq Avatar asked Jun 03 '13 14:06

pmoniq


2 Answers

this way you do not download content to save it

# Bucket: bucket name
# Key: file path
from storages.backends.s3boto3 import S3Boto3Storage
s3 = S3Boto3Storage()

def copy(Bucket_A, Bucket_B, Key_A, Key_B):
    copy_source = {'Bucket': Bucket_A, 'Key': Key_A}
    s3.bucket.meta.client.copy(copy_source, Bucket_B, Key_B)
    s3.delete(Key_A)
    return Key_B

def move(Bucket_A, Bucket_B, Key_A, Key_B):
    copy(Bucket_A, Bucket_B, Key_A, Key_B)
    s3.delete(Key_A)
    return Key_B
like image 142
Sorker Avatar answered Oct 05 '22 08:10

Sorker


You can use Django's ContentFile to do this

from django.core.files.base import ContentFile

new_file = ContentFile(original_file.read())
new_file.name = original_file.name

example = Example()
example.file = new_file
example.save()
like image 21
ravi404 Avatar answered Oct 05 '22 09:10

ravi404