我正在使用handle_uploaded_file通过多线程异步将CSV文件保存到文本文件,但是一旦home函数返回HTTP响应,传递给函数的file参数就会关闭。我不想保存文件并从该位置使用它,但是想在内存中可用它时使用它。
ValueError:寻求关闭的文件
def handle_uploaded_file(f):
destination = open('name.txt', 'ab+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
def home(request):
if request.method=="POST":
file = UploadForm(request.POST, request.FILES)
if file.is_valid():
g = request.FILES.dict()
File = g['file']
print(File)
uploader_thread = Thread(target=handle_uploaded_file, args=[File])
uploader_thread.start()
file.save()
return HttpResponseRedirect(reverse('imageupload'))
else:
file=UploadForm()
files=Upload.objects.all().order_by('-upload_date')
return render(request,'home.html',{'form':file}) #,'files':files})
答案 0 :(得分:0)
尝试这样。
import copy
def upload_handler(inmemory_file):
with open(inmemory_file.name, 'wb+') as destination:
for chunk in inmemory_file.chunks():
destination.write(chunk)
def home(request):
if request.method=="POST":
file = UploadForm(data=request.POST, files=request.FILES)
if file.is_valid():
memory_file = copy.deepcopy(request.FILES['file'])
upload_thread = Thread(target=upload_handler, args=(memory_file,))
upload_thread.start()
file.save()
return HttpResponseRedirect(reverse('imageupload'))
else:
file=UploadForm()
files=Upload.objects.all().order_by('-upload_date')
return render(request,'home.html',{'form':file}) #,'files':files})