2009-12-18 38 views
7

Tôi là người mới dùng django và python. Cần một số hướng dẫn trong nhiệm vụ này.django tải xuống tệp csv bằng liên kết

Trường hợp: Khi người dùng nhấn nút gửi trên biểu mẫu, trang sẽ hiển thị trang Thành công và liên kết nơi họ có thể tải xuống kết quả. Kết quả là trong tập tin excel. Tôi có thể tạo đầu ra để excel tập tin bằng cách sử dụng mô-đun xlwt và hiển thị các trang thành công riêng lẻ nhưng không phải cả hai cùng một lúc.

Tôi có gì: Tôi đang chạy django1.1.1 trên Windows XP với python 2.6. Có câu hỏi tương tự được yêu cầu nhưng không thể làm cho nó hoạt động.

page.html thành công của tôi có dòng này

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

urls.py:

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

views.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 

Khi tôi bấm vào liên kết, nó mang lại cho lỗi đường dẫn

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' 

BTW example.xls là ở cả những vị trí C: /example.xls và trong thư mục tĩnh

Cấu trúc:

  • webdb
    • tĩnh
      • example.xls
    • Webinput
      • urls.py
      • views.py
      • models.py

Tôi có những 2 module là tốt. Nếu tôi sử dụng backup_to_csv nó hoạt động tốt nhưng nó downlods trực tiếp mà không có liên kết. Làm thế nào để làm tương tự khi tôi đã có một tập tin. Nếu có những cách khác mà tôi không phải lưu trữ tập tin, đó là tốt quá.

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 (yêu cầu, hàng):

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 

Trả lời

7

Bây giờ nó hoạt động nhưng tôi đã phải thay đổi phần mở rộng tập tin từ excel (.xls) thành csv.

urls.py My = url(r'^static/example.txt', send_file)
liên kết HTML My = <a href="../static/example.txt">Download CSV File</a>
view.py My

def send_file(request): 

    import os, tempfile, zipfile 
    from django.core.servers.basehttp 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 
2

Trong url của bạn.py thay đổi

urls.py url(r'^static/(?P.*)$', send_file) 

để

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

Trong giai đoạn đầu, bạn cũng đang đi qua tất cả mọi thứ sau/đến xem như tham số khác, nhưng quan điểm của bạn không chấp nhận tham số này. một tùy chọn khác là chấp nhận thông số này trong chế độ xem:

def send_file(request, path): 
    ... 

nhưng vì đường dẫn đến tệp xls của bạn được mã hóa cứng, tôi không nghĩ bạn cần điều đó.

+0

Cảm ơn, nhưng nó mang lại cho lỗi này Traceback (cuộc gọi gần đây nhất cuối cùng): File "C: \ Python26 \ lib \ site-packages \ django \ core \ server \ basehttp.py", dòng 280, trong chạy self.finish_response() file "C: \ Python26 \ lib \ site-packages \ django \ core \ server \ basehttp.py", dòng 319, trong finish_response cho dữ liệu trong self.result: file "C : \ Python26 \ lib \ site-packages \ django \ http \ __ init__.py ", dòng 378, trong tiếp theo chunk = self._iterator.next() Tệp" C: \ Python26 \ lib \ site-packages \ django \ core \ servers \ basehttp.py ", dòng 50, trong tiếp theo dữ liệu = self.filelike.read (self.blksize) LoạiError: số nguyên là bắt buộc – user234850

1

Trong những ý kiến ​​Ofri Raviv. bạn nói rằng nó đem lại cho bạn một

TypeError: an integer

đó là vì trong khi tạo FileWrapper u đang đi qua hai tham số trong đó điều thứ hai [tùy chọn] được coi là số nguyên nhưng u qua 'rb'

wrapper = FileWrapper(file(filename),"rb")

nào thực sự cần được viết như sau ('rb' là tham số file)

wrapper = FileWrapper (file (filename, "rb"))

vì vậy, nó chỉ là một misali gnment của niềng răng, nhưng làm cho nó khó khăn để gỡ lỗi đôi khi.

Các vấn đề liên quan