【问题标题】:Upload video to amazon s3 using django and python使用 django 和 python 将视频上传到 amazon s3
【发布时间】:2017-08-05 18:58:24
【问题描述】:

我正在尝试的只是将视频上传到亚马逊 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://,如下所示

  1. 随着亚马逊上传过程,一个视频文件也在本地创建,其路径来自 endpoint_url,例如,如果端点 url 是 https://ipitch_videos.s3.amazonaws.com/videos/1_username/super.mpg django 正在媒体下创建以下文件夹,如下所示

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

【问题讨论】:

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


    【解决方案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'
    

    【讨论】:

    • 这是什么AWS_S3_CUSTOM_DOMAIN ,我们需要生成它吗?
    猜你喜欢
    • 2014-08-06
    • 2012-02-11
    • 1970-01-01
    • 2020-11-15
    • 2012-12-24
    • 1970-01-01
    • 2013-05-19
    • 2010-10-14
    • 1970-01-01
    相关资源
    最近更新 更多