2013-05-14 88 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'), 
)