Django使用链接下载CSV文件

10

我是django和python的新手。需要在这个问题上获得一些指导。

场景:当用户在表单上点击提交按钮时,应该显示成功页面和一个链接,在链接上他们可以下载结果。结果是excel文件。我可以使用xlwt模块创建excel文件输出并单独显示成功页面,但无法同时实现两者。

我有以下内容: 我在Windows XP上运行django1.1.1,并使用python 2.6。以前有类似的问题被问到,但我不能使它工作。

我的success page.html文件中有这一行:

<a href="../static/example.xls">Download CSV File</a>

urls.py:

url(r'^static/(?P<path>.*)$', send_file), 

视图.py:

def send_file(request):

import os, tempfile, zipfile
from django.core.servers.basehttp import FileWrapper

"""                                                                         
Send a file through Django without loading the whole file into              
memory at once. The FileWrapper will turn the file object into an           
iterator for chunks of 8KB.                                                 
"""
filename = "C:/example.xls" # Select your file here.                                
wrapper = FileWrapper(file(filename),"rb")
response = HttpResponse(wrapper, content_type='text/plain')
#response['Content-Length'] = os.path.getsize(filename)
return response

当我点击链接时,它显示路径错误。

send_file() got an unexpected keyword argument 'path'
Request Method: GET
Request URL:    localhost:8000/webinput/static/example.xls
Exception Type: TypeError
Exception Value:    
send_file() got an unexpected keyword argument 'path'

顺便说一下,example.xls同时位于C:/example.xls和静态文件夹中。

结构:

  • webdb
    • Static
      • example.xls
    • Webinput
      • urls.py
      • views.py
      • models.py

我也有这两个模块。如果我使用backup_to_csv,它可以正常工作,但是没有链接直接下载。当我已经有一个文件时如何做相同的事情。如果有其他不需要存储文件的方法,那也可以。

def xls_to_response(xls, fname):

response = HttpResponse(mimetype="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename=%s' % fname
xls.save(response)
return response

def backup_to_csv(request,row):

response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename="backup.csv"'
writer = csv.writer(response, dialect='excel')    
#code for writing csv file go here...
for i in row:
    writer.writerow(i)
return response
3个回答

10

现在它能工作了,但是我不得不将文件扩展名从excel (.xls) 改为 csv。

我的urls.py:url(r'^static/example.txt', send_file)
我的HTML链接: <a href="../static/example.txt">下载CSV文件</a>
我的view.py

def send_file(request):

  import os, tempfile, zipfile
  from wsgiref.util import FileWrapper
  from django.conf import settings
  import mimetypes

  filename     = "C:\ex2.csv" # Select your file here.
  download_name ="example.csv"
  wrapper      = FileWrapper(open(filename))
  content_type = mimetypes.guess_type(filename)[0]
  response     = HttpResponse(wrapper,content_type=content_type)
  response['Content-Length']      = os.path.getsize(filename)    
  response['Content-Disposition'] = "attachment; filename=%s"%download_name
  return response

3
在你的urls.py文件中修改
urls.py url(r'^static/(?P.*)$', send_file)

to

urls.py url(r'^static/example.xls$', send_file)

在第一个选项中,您将“/”后的所有内容作为另一个参数传递给视图,但是您的视图不接受此参数。另一个选项是在视图中接受此参数:

def send_file(request, path):
    ...

但是由于你的xls文件路径是硬编码的,所以我认为你不需要它。


谢谢,但是它会出现以下错误Traceback (most recent call last): File "C:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 280, in run self.finish_response() File "C:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 319, in finish_response for data in self.result: File "C:\Python26\lib\site-packages\django\http_init_.py", line 378, in next chunk = self._iterator.next() File "C:\Python26\lib\site-packages\django\core\servers\basehttp.py", line 50, in next data = self.filelike.read(self.blksize)TypeError: 需要一个整数 - user234850

1
在Ofri Raviv的评论中,您提到它给了您一个TypeError: an integer。这是因为在创建FileWrapper时,您传递了两个参数,其中第二个[可选]应该是整数,但您传递了'rb'。
wrapper = FileWrapper(file(filename),"rb")
实际上应该写成('rb'是File的参数)
wrapper = FileWrapper(file(filename,"rb"))
所以这只是括号的错位,但有时很难调试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接