【发布时间】:2018-06-27 19:17:24
【问题描述】:
我创建了一个自定义命令,它接受一个位置参数和一个命名的可选参数。它会进行许多检查、下载文件、解压缩并使用解压缩的数据填充数据库。
为了让用户更方便,我创建了一个简单的表单并创建了一个视图:
from django.views.generic.edit import FormView
from django.core import management
from .forms import DownloadForm
class DownloadFormView(FormView):
template_name = 'frontend/download.html'
form_class = DownloadForm
success_url = '.'
def form_valid(self, form):
country = form.cleaned_data['country'][:3]
levels = int(form.cleaned_data['country'][-1:])
management.call_command('download_shapefile', country, levels=levels)
return super(DownloadView, self).form_valid(form)
效果很好,现在我想向用户提供反馈,因为该命令可能会运行一段时间。
是否有可能将命令输出(或使其可用)重定向到模板并在浏览器中显示?
在我的命令中我使用:
self.stdout.write(self.style.SUCCESS('some success message'))
self.stdout.write(self.style.WARNING('some warning message'))
输出消息,不直接使用print 方法打印。
【问题讨论】:
-
听起来您需要了解 API 的工作原理,或许还需要研究 django rest 框架。在浏览器中向模板提供命令输出不会是一种简单的单行方式。您的浏览器可能需要以给定的时间间隔访问 API 以查看响应是否已准备好。另一种选择是查看渠道。
-
@DataSwede 我经常使用 Django REST Framework,但我认为它不是完成这项任务的正确工具。感谢您提及
Channels。那可能会提供一些东西。我去看看。
标签: python django django-commands