2013-05-14 113 views
0

我是新來的Django框架,我試圖生成一個鏈接,從下載文件亞馬遜S3。我得到這個錯誤,當我試圖加載模板頁面:使用django從亞馬遜S3下載文件

Reverse for 'myapp.views.handles3downloads' with arguments '(u'README.md',)' 
and keyword arguments '{}' not found. 

urls.py

urlpatterns = patterns('', 
    url(r'^handles3downloads/(\d+)/$', handles3downloads), 
) 

views.py

def handles3downloads(request, fname): 
    bucket_name = 'bucketname' 
    key = s.get_bucket(bucket_name).get_key(fname) 
    dfilename = key.get_contents_to_filename(fname) 

    wrapper = HttpResponse(file(dfilename)) 
    response = HttpResponse(wrapper, content_type='text/plain') 
    response['Content-Length'] = os.path.getsize(dfilename) 
    return response 

模板文件

<a href="{% url 'myapp.views.handles3downloads' sfile.linkUrl %}">{{sfile.linkUrl}}</a> 

我看了一些類似錯誤的解決方案,但它沒有幫助我。任何人都可以幫助我。

先感謝

+0

看看這有助於:http://stackoverflow.com/questions/625047/django-newbie-reverse-not-found – themanatuf 2013-05-14 11:32:43

回答

0

urls.py

url(r'^handles3downloads/', handles3downloads), 

views.py

def handles3downloads(request): 
    fname = request.GET['filename'] 
    bucket_name = 'bucketname' 
    key = s.get_bucket(bucket_name).get_key(fname) 
    key.get_contents_to_filename('/tmp/'+key.name) 
    wrapper = FileWrapper(open('/tmp/'+fname, 'rb')) 
    content_type = mimetypes.guess_type('/tmp/'+fname)[0] 
    response = HttpResponse(wrapper,content_type=content_type) 
    response['Content-Length'] = os.path.getsize('/tmp/'+fname) 
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(fname) 

模板

<a href="/handles3downloads/?filename=file1.jpg" rel="external">Download</a> 
+0

如果您告訴我們變量「s」來自何處,那將會很好。還需要回復,對。 謝謝。 – Joepreludian 2017-06-16 13:59:04

+0

's'變量就像這個例子中的's3_connection'變量來自boto 2: http://boto3.readthedocs.io/en/latest/guide/migrations3.html#accessing-a-bucket '進口boto s3_connection = boto.connect_s3()' 'bucket = s3_connection.get_bucket('mybucket',validate = False)' – 2017-12-12 15:46:24

1

urls.py文件您的正則表達式似乎是錯誤的。嘗試使用這個:

url(r'^handles3downloads/(\w+)/$', handles3downloads), 

你傳遞參數字符串的視圖和regex是匹配的整數。

+0

嗨,我還在更改正則表達式後得到相同的錯誤 – Niya 2013-05-14 09:11:41

+0

然後可能你沒有這樣的名稱的URL模式。 [考慮命名你的視圖](https://docs.djangoproject.com/en/dev/topics/http/urls/),而不是使用'myapp.views.handles3downloads'。 – 2013-05-14 09:13:58

0

約旦是正確的,您的urls.py存在問題。你可以通過錯誤來判斷。您正試圖在'myapp.views.handles3downloads'上獲得相反的結果,但是確定了反向字符串?嘗試這個。

urlpatterns = patterns('', 
    url(r'^handles3downloads/([^/]+)/$', handles3downloads, 
    name='myapp.views.handles3downloads'), 
)