简体   繁体   中英

How download file and save it inside the upload folder using Django and Python

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. My code is below.

 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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM