[英]How to request GET parameters in templates for a list of files?(Django Zip File Download Issue)
我想通過壓縮下載 function 創建的所有單個或多個文件。
問題出在模板上。 請正確建議為我收到錯誤的文件列表傳遞 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>
幫我在這里找到問題。
the?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'
文件路徑應該是:
/home/rikesh/Projects/FedMall/main/temp/47QSHA19D003A_UPDATE_20210113_0.csv
request.GET.get('paths')
返回路徑列表的字符串表示形式,而不是列表 object。 返回的值將是這樣"['/path/file1', 'path/file2']"
。 當您遍歷路徑時,它實際上會遍歷字符串中的每個字符。 這就是為什么它首先嘗試查找名稱為[
的目錄。
要將文件路徑列表傳遞給GET
請求,您需要將 url 更改為此
<your_url>?paths=path1&paths=path2&paths=path3...
在您的 Python 代碼中,使用此獲取文件路徑
request.GET.getlist('paths')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.