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

时间:2021-07-17 07:22:46

I am trying to write the content in CSV file and Here I need to download that file and save that same file into upload folder. I am explaining my code below.

我试图在CSV文件中写入内容,在这里我需要下载该文件并将该文件保存到上传文件夹中。我在下面解释我的代码。

 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})

Here I am setting the database values inside one CSV file and that file is named as unique id. Here I need to save that file inside Upload folder and that folder path will set inside settings.py file and also same file will be downloaded as well.

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

1 个解决方案

#1


0  

You should try to generate your CSV into a buffer an then use it to save it to the file system and use it again to return the CSV as the respone. Something like this

您应该尝试将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

I am quite sure this not the most optimized way to do it, but at least it should works.

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

#1


0  

You should try to generate your CSV into a buffer an then use it to save it to the file system and use it again to return the CSV as the respone. Something like this

您应该尝试将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

I am quite sure this not the most optimized way to do it, but at least it should works.

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