我可以在任务当前执行时渲染视图吗?

假设我在 views.py 中有这个视图:

def wait_and_print(request):      
      print(5)  
      time.sleep(90)  
      return render(request, 'view.html')

我想在 time.sleep(90) 任务完成之前显示 view.html(让它在后台执行,因为我的视图不需要它)。我读过有关同步-异步任务的信息,但我似乎不太了解如何执行此操作。

谢谢,


墨色风雨
浏览 81回答 1
1回答

犯罪嫌疑人X

您可以通过在指向呈现空 HTTP 响应的 URL 下添加 AJAX 函数来完成此操作view.html:URL /run_ajax(应包含在您的 中urls.py)应如下所示:```re_path(r'^run_ajax', views.function_to_call_with_ajax)```function_to_call_with_ajax 是这样的(在 view.py 中):def wait_and_print(request):&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; print(5)&nbsp;&nbsp;&nbsp; time.sleep(90)&nbsp;&nbsp;&nbsp; return HttpResponse("")AJAX 功能:<script type="text/javascript">$( document ).ready(function() {&nbsp; &nbsp; console.log("ready!");&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url: '/run_ajax', //The URL you defined in urls.py&nbsp; &nbsp; &nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('data ', data)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //If you wish you can do additional data manipulation here.&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error: function (error) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('error', error)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python