如何做三个功能由一个提交按钮只有一个表单文档?



我有一个问题,调用多个函数在一次点击提交按钮。我有一个表单,用户需要附加一个文件(exls文档),我需要一个文档用于3个功能。我需要保存文档,做一些熊猫的东西,我需要在html中显示它。我能把它放到课堂上吗?我不关心它是如何工作的,只需要当文件提交保存,做熊猫的工作人员和熊猫的东西显示在html中。我真的需要帮助,提前谢谢你。

def save_exls(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
return redirect('html_exls')
else:
form = DocumentForm()
documents = Document.objects.all()
context = {'documents': documents, 'form': form,}
return render(request, 'list.html', context)

def pandas_exls(request):
if request.method == "POST":
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
output = io.BytesIO()
newdoc = request.FILES['docfile']
dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0])
writer = pd.ExcelWriter(output)
for name, df in dfs.items():
#pandas stuff
done.to_excel(writer, sheet_name=name)
output.seek(0)
response = HttpResponse(
output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
else:
form = DocumentForm()
return render(request, 'list.html', {'form': form})

def html_exls(request):
if request.method == "POST":
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
output = io.BytesIO()
newdoc = request.FILES['docfile']
dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0])
writer = pd.ExcelWriter(output)
for name, df in dfs.items():
#pandas stuff for html 
done.to_excel(writer, sheet_name=name)
html = done.to_html()
print(html)
output.seek(0)
response = HttpResponse(
output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
else:
form = DocumentForm()
return render(request, 'list.html', {'form': form})

您可能想要探索的一些选项:

  1. 如果所有的API实际上都是相互耦合的,你可能想把它转换成一个API,而不是执行所有3个API。然后,为了仍然单独支持每个API,重构代码,这样您就不必在组合API中重复相同的代码以及单个API。
  2. 在HTML模板的顶部,添加JavaScript (AJAX),它将拦截表单提交,您将执行3次HTTP POST请求到不同的url。
  3. 应用发布/订阅(Pub/Sub)模式(生产者/消费者)。这个想法是将3x url订阅到resource-x。现在,将数据发布/发布到resource-x。然后,Pub/Sub系统应该转发数据并调用所有订阅的消费者,即3x url。
    • 一种方法是通过AWS SNS等服务,您可以在其中设置主题,订阅该主题的3x url,然后更改表单以发布该主题。
    • 另一种方法是通过实现任务队列,如芹菜。将3x url转换为芹菜任务。然后准备一个HTTP URL,它将接收到的请求排队到3个任务。然后修改你的表单,把它发送到HTTP URL。
  4. 不值得推荐的。这将是最简单的,但是是一个肮脏的hack并且是高度同步的。以一种方式将每个视图链接在一起,在一个视图完成后,调用下一个视图。