使用django和python将视频上传到amazon s3

时间:2017-03-15 06:56:09

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

我正在尝试的是将视频上传到亚马逊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上传视频时,会成功在数据库中创建记录,但会出现以下三个问题

  1. 视频记录实例正在保存,但在https://来自亚马逊的/后仅endpoint_url而不是https:/分割https://
  2. enter image description here

    1. 除了亚马逊上传过程外,还在本地创建了一个视频文件,其中包含来自endpoint_url的路径,例如,如果终点网址为https://ipitch_videos.s3.amazonaws.com/videos/1_username/super.mpg,则django正在媒体下创建以下文件夹,如下所示
    2. enter image description here

      那么如何避免django在本地创建视频文件呢?

1 个答案:

答案 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'