簡體   English   中英

如何使用Django和Python下載文件並將其保存在上載文件夾中

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

我正在嘗試將內容寫入CSV文件,在這里我需要下載該文件並將該文件保存到upload文件夾中。 我的代碼如下。

 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文件中settings.py並且還將下載相同的文件。

您應該嘗試將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

我很確定這不是最優化的方法,但至少應該可以。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM