2013-12-20 57 views
4

我有一個django應用程序在heroku服務從亞馬遜s3桶的靜態文件。我使用博託圖書館,並遵循網站上的指南。 我能做些什麼來加速文件傳輸?從亞馬遜S3服務無法忍受的文件緩慢

某些代碼:

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/' 

認爲

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直接鏈接?

+0

我會推薦通過CloudFront從S3提供服務​​文件。 – Brandon

+0

目前,我在演示階段,我想保持一切自由。但林不知道這是問題,我開始懷疑,即使我使用亞馬遜s3存儲,Django服務的文件,而不是亞馬遜,因爲當我看着我的網絡流量,我看不到任何鏈接導致亞馬遜。 –

+0

CloudFront每月首10 TB只花費0.12美元。這是相當實惠:)。如果您的網絡流量表示您的文件由Django提供服務,那完全是另一回事。 – Brandon

回答

4

這裏是我如何做到這一點 - 它不覺得慢,我說:

models.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) 

我的個人用戶或用戶組s具有在配置文件對象中引用的指定桶。存儲在settings.py中的AWS證書。