【发布时间】:2021-10-29 15:07:28
【问题描述】:
我想在上传并运行 pandas 脚本并保存该脚本时保存文档,但还要转发给用户下载它。怎么做?
这就是我尝试的方式,上传和保存上传工作,但熊猫脚本不起作用。
def my_view(request):
message = 'Upload as many files as you want!'
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
#This part is doing calculations for uploaded file
dfs = pd.read_excel(newdoc, sheet_name=None)
with pd.ExcelWriter('output_' + newdoc + 'xlsx') as writer:
for name, df in dfs.items():
print(name)
data = df.eval('d = column1 / column2')
ooutput = data.eval('e = column1 / d')
ooutput.to_excel(writer, sheet_name=name)
output = io.BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
newdoc.to_excel(writer, index=False)
writer.save()
output.seek(0)
response = HttpResponse(output,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download'
return response
return redirect('results')
else:
message = 'The form is not valid. Fix the following error:'
else:
form = DocumentForm()
documents = Document.objects.all()
context = {'documents': documents, 'form': form, 'message': message}
return render(request, 'list.html', context)
def results(request):
documents = Document.objects.all()
context = {'documents': documents}
return render(request, 'results.html', context)
【问题讨论】:
-
你能给出Documents的执行吗?这是一个自定义的 django 模型吧?
标签: python django django-views django-forms