如何下载文件并使用Django和Python将其保存在上传文件夹中

时间:2017-08-17 09:37:47

标签: python django csv

我正在尝试将内容写入CSV文件,在这里我需要下载该文件并将该文件保存到(obj?.Name)文件夹中。我在下面解释我的代码。

upload

这里我将数据库值设置在一个CSV文件中,该文件被命名为唯一ID。在这里,我需要将该文件保存在 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}) 文件夹中,该文件夹路径将设置在Upload文件中,同样也会下载相同的文件。

1 个答案:

答案 0 :(得分:0)

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

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

我很确定这不是最优化的方法,但至少它应该有用。