[英]Upload video to amazon s3 using django and python
我正在嘗試的只是將視頻上傳到Amazon s3,而不是像Django那樣定期保存在媒體中。 因此創建了一個下面的模型
def upload_to_amazon_s3(instance, filename):
aws_access_key_id = settings.AWS_ACCESS_KEY_ID
aws_secret_access_key = settings.AWS_SECRET_ACCESS_KEY
file_name = 'videos/{0}_{1}/{2}'.format(instance.user.id, instance.user.username, filename)
conn = boto.connect_s3(aws_access_key_id, aws_secret_access_key)
try:
bucket = conn.get_bucket("ipitch_videos", validate=True)
except S3ResponseError:
bucket = conn.create_bucket('ipitch_videos')
#Get the Key object of the bucket
k = Key(bucket)
#Crete a new key with id as the name of the file
k.key=file_name
#Upload the file
result = k.set_contents_from_file(instance.video_file)
# we need to make it public so it can be accessed publicly
# using a URL like http://s3.amazonaws.com/bucket_name/key
k.make_public()
get_s3_obj = Key(bucket,file_name)
endpoint_url = get_s3_obj.generate_url(expires_in=0, query_auth=False)
return endpoint_url
class Video(DateTimeModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
video_file = models.FileField(upload_to=upload_to_amazon_s3)
我正在從Amazon s3 Url獲取endpoint_url
值,例如https://ipitch_videos.s3.amazonaws.com/videos/1_username/super.mpg
因此,當我從前端表單或具有所有字段user, name, video_file
的API上傳視頻時,一條記錄已成功創建到數據庫中,但是會發生以下三個問題
endpoint_url
https://之后分割/
,並且僅使用https:/
而不是https://
,如下所示 https://ipitch_videos.s3.amazonaws.com/videos/1_username/super.mpg
django正在如下媒體下創建以下文件夾 那么如何避免django也在本地創建視頻文件呢?
您可以使用S3BotoStorage。
$ pip install django-storages boto將'storages'添加到INSTALLED_APPS:
INSTALLED_APPS = (
...,
'storages',
)
添加另一個存儲類:
class MediaStorage(S3BotoStorage):
location = settings.MEDIAFILES_LOCATION
並在settings.py中:
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.