我正在尝试的是将视频上传到亚马逊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上传视频时,会成功在数据库中创建记录,但会出现以下三个问题
答案 0 :(得分:1)
您可以使用S3BotoStorage。
$ pip install django-storages boto 添加存储空间'到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'