I am in trouble saving my local file to s3bucket.
I have a corn job in my Django project, after a certain time, it generates a pdf
file. And I want to save the file in s3bucket.
Currently, Django s3bucket is working very well like saving my uploaded file to s3bucket and lots more thing is working.
But I am not getting how to copy local file and save in s3bucket.
CURRENTLY I AM SAVING THIS IN MY LOCAL MACHINE LIKE THIS WAY:
shutil.copyfile('/var/www/local.pdf' ,'media/newfileins3bucket.pdf')
But it will not works that way i want to save it directly to s3bucket.
Can anyone help me in this case?
I am using this and it has no point to save directly pdf to s3bucket: https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html
There are several ways to do this but I think one of the following should work for you.
Note: I'm assuming (as you mentioned) you have Django Storages with the S3 backend set up in your settings as the default storage.
Upload using FileField on a model
If you have a model set up that saves a references to the generated report, you can do something like this:
Note that you have to wrap your local file in a Django
File
object.Calling
save()
on the file field automatically saves the model in the database as well, unless you addsave=False
to the call. For more info see the documentation on FileField.save()Direct upload without a model
If you just want to upload the file to S3 without saving it in a model, you can do something like this:
Disclaimer: I have used something similar but have not tested the exact code above. It should point you in the right direction though.