django pobierz plik csv używając linku

Jestem nowy w django i Pythonie. Potrzebujesz wskazówek w tej misji.

Przypadek: gdy użytkownik naciśnie przycisk Wyślij na formularzu, powinien wyświetlić stronę sukcesu i link, z którego może pobrać wyniki. Wyniki są w pliku excel. Mogę utworzyć wyjście do pliku excel za pomocą modułu xlwt i wyświetlić stronę sukcesu indywidualnie, ale nie oba w tym samym czasie.

What I have: Uruchamiam django1. 1. 1 na windows XP z Pythonem 2.6. Podobne pytanie zadano ale nie był w stanie tego zrobić.

Moja strona sukcesu.html ma tę linię

<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

Kiedy klikam na link, wyświetla się błąd ścieżki

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 przykład.xls jest w obu lokalizacjach C:/example.xls i statyczne folder

Struktura:

  • webdb
    • Static
      • przykład.xls
    • Webinput
      • urls.py
      • views.py
      • models.py

Mam te 2 moduły, jak również. Jeśli używam backup_to_csv działa dobrze, ale pobiera bezpośrednio bez linku. Jak zrobić to samo, gdy mam już plik. Jeśli są inne sposoby, w których nie muszę przechowywać pliku, to też jest w porządku.

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
Author: CraigTeegarden, 2009-12-19

3 answers

Teraz działa, ale musiałem zmienić rozszerzenie pliku z Excela (.xls) do csv.

Mój urls.py=url(r'^static/example.txt', send_file)
My HTML link=<a href="../static/example.txt">Download CSV File</a>
My 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
 9
Author: user234850,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-22 07:59:21

W Twoim urls.py Zmień

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

Do

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

W pierwszym przekazujesz również wszystko po / do widoku jako inny parametr, ale twój widok nie akceptuje tego parametru. inną opcją byłoby zaakceptowanie tego parametru w widoku:

def send_file(request, path):
    ...

Ale ponieważ ścieżka do pliku xls jest mocno zakodowana, myślę, że nie potrzebujesz tego.

 2
Author: Ofri Raviv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-12-19 08:49:30

W komentarzach do: wspomniałeś, że daje ci

TypeError: an integer

A to dlatego, że podczas tworzenia FileWrapper u przekazujemy dwa parametry, z których drugi [opcjonalny] ma być liczbą całkowitą, ale u przekazujemy 'rb'

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

Który powinien być zapisany jako ('rb' jest parametrem do pliku)

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

Więc to była tylko niewspółosiowość szelek, ale sprawia, że czasami trudno jest debugować.

 1
Author: Bunny Rabbit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-15 08:15:25