gpt4 book ai didi

python - 如何在模板中为文件列表请求 GET 参数?(Django Zip 文件下载问题)

转载 作者:行者123 更新时间:2023-12-04 01:08:05 26 4
gpt4 key购买 nike

我想通过压缩的方式下载函数创建的所有单个或多个文件。

问题出在模板上。请正确建议传递文件列表的 GET 参数我收到一个错误:

FileNotFoundError at /test/
[Errno 2] No such file or directory: '['

这是错误放置引用文件列表的查询字符串的错误。

我的看法如下:

def submit(request):
def file_conversion(input_file,output_file_pattern,chunk_size):
output_filenames = []
with open(input_file,"r+") as fin:
# ignore headers of input files
for i in range(1):
fin.__next__()

reader = csv.reader(fin, delimiter=',')


for i, chunk in enumerate(chunked(reader, chunk_size)):
output_filename = output_file_pattern.format(i)
with open(output_filename, 'w', newline='') as fout:
output_filenames.append(output_filename)
writer = csv.writer(fout, reader, delimiter='^')
writer.writerow(fed_headers)
writer.writerows(chunk)
# print("Successfully converted into", output_file)
return output_filenames

paths = file_conversion(input_file,output_file+'{01}.csv',10000)
# paths return a list of filenames that are created like output_file1.csv,output_file2.csv can be of any limit
# when i tried paths[0], it returns output_file1.csv
context = {'paths' :paths}

def test_download(request):
paths = request.GET.get('paths')
context ={'paths': paths}
response = HttpResponse(content_type='application/zip')
zip_file = zipfile.ZipFile(response, 'w')
for filename in paths:
zip_file.write(filename)
zip_file.close()
response['Content-Disposition'] = 'attachment; filename='+'converted files'
return response

模板

<p> 
<a href ="{% url 'test_download' %}?paths={{ paths|urlencode }} " download>Converted Files</a> </p>
<br>

帮我找到这里的问题。

问题: enter image description here

?path 正在寻找文件,但它已找到列表。

然后我尝试了:

def test_download(request):
paths = request.GET.getlist('paths')
context ={'paths': paths}
response = HttpResponse(content_type='application/zip')
zip_file = zipfile.ZipFile(response, 'w')
for filename in paths:
zip_file.write(filename)
zip_file.close()
response['Content-Disposition'] = 'attachment; filename='+'converted files'
return response

模板:

<p> <a href ="{% url 'test_download' %}?paths=path1 " download>Converted Files</a> </p>
<br>

它查找文件为

FileNotFoundError at /test/
[Errno 2] No such file or directory: '/home/rikesh/Projects/FedMall/main/temp/47QSHA19D003A_UPDATE_20210113_{:01}.csv'

enter image description here

enter image description here

文件路径应该是:

/home/rikesh/Projects/FedMall/main/temp/47QSHA19D003A_UPDATE_20210113_0.csv

最佳答案

request.GET.get('paths') 返回路径列表的字符串表示,而不是列表对象。返回值将像这样 "['/path/file1', 'path/file2']"。当您遍历路径时,它实际上遍历了字符串中的每个字符。这就是为什么它首先尝试查找名称为 [ 的目录。

要将文件路径列表传递给 GET 请求,您需要将 url 更改为此

<your_url>?paths=path1&paths=path2&paths=path3...

在您的 Python 代码中,使用此获取文件路径

request.GET.getlist('paths')

关于python - 如何在模板中为文件列表请求 GET 参数?(Django Zip 文件下载问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65679286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com