gpt4 book ai didi

django - 亚马逊 s3 提供的文件速度慢得难以忍受

转载 作者:行者123 更新时间:2023-12-02 06:24:03 27 4
gpt4 key购买 nike

我在heroku上有一个django应用程序,它提供来自亚马逊s3存储桶的静态文件。我使用 boto 库并按照网站上的指南进行操作。我可以做什么来加快文件传输速度?

部分代码:

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = 'xxxx'
AWS_SECRET_ACCESS_KEY = 'xxxx'
AWS_STORAGE_BUCKET_NAME = 'boxitwebservicebucket'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
STATIC_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/'

View

class GetFileContent(View):
def get(self,request, userName, pk):
user = User.objects.filter(username = userName)
filtered = Contentfile.objects.filter(pk = pk, published=True, file_owner = user)
data = filtered[0].content
filename = filtered[0].title + "." + filtered[0].file_type
response = HttpResponse(data, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
return response
pass

我怀疑 django 正在提供该文件,即使它位于 s3 服务器上,我如何直接将用户定向到 s3 链接?

最佳答案

这是我的做法 - 我觉得并不慢:

模型.py:

class Document(models.Model):
id = UUIDField(primary_key = True)
extension = models.CharField(max_length = 5)
created_on = CreationDateTimeField()
labels = models.ManyToManyField(Label)

def url(self, bucket):
url = get_s3_url(bucket, '' + str(self.id) + str(self.extension) + '')
return 'https' + url[4:]

views.py:

import urllib2


@login_required
def view(request, document_id):
document = Document.objects.get(id = document_id)

response_file = urllib2.urlopen(document.url(request.user.profile.aws_documents_bucket_name))

response = HttpResponse(response_file.read(), mimetype = document.mimetype)
response['Content-Disposition'] = 'inline; filename=' + str(document.id) + document.extension

return response

utils.py:

from boto.s3.connection import S3Connection
from boto.s3.key import Key
from django.conf import settings


def get_s3_url(bucket, filename):
s3 = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
key = s3.create_bucket(bucket).get_key('' + filename + '')
return key.generate_url(3600, "GET", None, True, True) # This gives an authenticated url available for only a short time period (by design)

我的个人用户或用户组已指定配置文件对象中引用的存储桶。 AWS凭证存储在settings.py中。

关于django - 亚马逊 s3 提供的文件速度慢得难以忍受,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20700890/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com