2017-08-17 39 views
0

我想将内容写入CSV文件,在这里我需要下载该文件并将同一文件保存到upload文件夹中。我在下面解释我的代码。如何使用Django和Python下载文件并将其保存在上传文件夹中

if request.method == 'POST': 
     param = request.POST.get('param') 
     report = Reactor.objects.all() 
     response = HttpResponse(content_type='text/csv') 
     response['Content-Disposition'] = 'attachment; filename='+uuid.uuid4()+'.csv' 
     writer = csv.writer(response) 
     writer.writerow(['Name', 'Status', 'Date']) 
     for rec in report: 
      if rec.status == 1: 
       status = 'Start' 
      if rec.status == 0: 
       status = 'Stop' 
      if rec.status == 2: 
       status = 'Suspend' 
      writer.writerow([rec.rname, status, rec.date]) 
     #return response 
     u = urllib.URLopener() 
     f = u.open(param) 
     open("down.txt","w").write(f.read()) 
     pers = User.objects.get(pk=request.session['id']) 
     root = [] 
     user_name = pers.uname 
     count = 1 
     root.append(
      {'username': user_name, 
      'count': count 
      }) 
    return render(request, 'plant/home.html', 
        {'user': root, 'count': 1}) 

这里我将数据库值设置在一个CSV文件中,并且该文件被命名为唯一ID。这里我需要将该文件保存在Upload文件夹中,该文件夹路径将在settings.py文件内设置,同样也会下载相同的文件。

回答

0

您应该尝试将CS​​V生成到缓冲区,然后使用它将其保存到文件系统并再次使用它作为响应返回CSV。像这样的东西

import csv 
import os 
import shutil 
from io import StringIO 

from django.http import HttpResponse 
from django.conf import settings 

def my_view(request): 
    csvbuffer = StringIO 

    writer = csv.writer(csvbuffer) 
    # Write data from the DB here into the CSV buffer 

    # Write the file to the file system 
    path = os.path.join(settings.FILE_PATH, "%s.csv" % uuid.uuid4()) 
    with(path, 'w') as fd: 
     csvbuffer.seek(0) 
     shutil.copyfileobj(csvbuffer, fd) 


    response = HttpResponse(content_type='text/csv') 
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' 

    csvbuffer.seek(0) 
    response.write(csvbuffer) 

    return response 

我很肯定这不是最优化的方式来做到这一点,但至少它应该工作。

+0

好的,我需要将该文件也保存到文件夹中。我这样做'打开(settings.FILE_PATH +文件名,'W')',但得到这个'全球名称'文件名'未定义'错误。 – satya

+0

你应该这样做:例如,os.path.join(settings.FILE_PATH,“%s.csv”%uuid.uuid4())。 – Thom

+0

我已经在settings.py文件中设置了像这样的'FILE_PATH = os.path.join(BASE_DIR,'/ upload /')'的路径,我需要保存该确切的下载文件。 – satya

相关问题