【问题标题】:How to use Post-save Signal when uploading document, and saving before and after altering document?上传文件时如何使用Post-save Signal,修改文件前后保存?
【发布时间】: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


【解决方案1】:

这不是答案,而是我的建议,您遵循错误的实施方式。

  1. 您可以在 Celery 中设置后台进程
  2. Celery 中完成工作后,您可以通过下载 URL 邮寄/通知用户。

上面给出的解决方案将很长,但也可扩展且面向性能。

【讨论】:

  • 您在发布请求时完成了这么多任务,这不会阻止其他人的处理时间。 @Hardik 定义的 Celery 和任务管理将是一种更好的方法。只是说。
【解决方案2】:
dfs = pd.read_excel(newdoc, sheet_name=None)

您在此处传递 newdoc,这是您的模型,而不是 IO 对象。

试试

dfs = pd.read_excel(newdoc.docfile, sheet_name=None)

 dfs = pd.read_excel(newdoc.docfile.file, sheet_name=None)

【讨论】:

  • 这部分工作正常,如果我这样做,我得到AttributeError at / 'InMemoryUploadedFile' object has no attribute 'docfile'
  • 你能从日志中给出更多的行吗?
  • 日志是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 2014-07-28
相关资源
最近更新 更多