jjzjj

javascript - 从 AJAX 请求调用 django View (解析 celery task_id)

coder 2024-07-25 原文

我正在尝试将 celery 任务中的数据输出到单独的窗口中。我是 JavaScriptAJAX 的新手,这就是我当前的问题所在。执行 View 后,将启动 celery 任务并呈现下一个 html 页面(success.html):

成功.html

{% block content %}
  <body>
    {% if task_id %}
      <h1>task_id has been called: {{ task_id }}</h1>

    <script src="{% static 'MyAPP/bootstrap/js/task_output_retrieval.js' %}"></script>
    <script type='text/javascript'> task_state("{{ task_id }}"); </script>

    <script src="{% static 'MyAPP/bootstrap/js/update-hello-user.js' %}"></script>
    <script type='text/javascript'> second(); </script>

      <h1> END </h1>

    {% endif %}
  </body>
{% endblock content %}

我知道 JavaScript 被调用了,因为至少打开了一个窗口。这是 .js:

task_output_retrieval.js

function task_state (task_id) {
    var taskID = task_id; 
    var newWin = window.open('', 'new window', 'width=200, height=100');

    $.ajax({
            url: '{% url validate_task_state %}', 
            data: {'taskID':taskID},
            method: 'POST',
            dataType : "json",
            success: function(data){
                $(newWin.document.body).html(data);
                newWin.document.write(data);
                newWin.document.close();
                newWin.focus();
                newWin.print();
                newWin.close();
            },
            error: function (){ alert('An error occured'); }
    });
}

task_state(task_id);

url.py:

url(r'^ajax/task_state/$', task_state, name='validate_task_state'), # for ajax

和 View :

admin_scripts.py

def task_state(request):
    print ("You reached the task_state function")
    data = 'Fail' 
    task_id = request.GET.get('task_id') 
    #task_id = request.session['task_id']
    try:
        async_result = AsyncResult(task_id)
    except KeyError:
        ret = {'error':'No optimisation (or you may have disabled cookies).'}
        return HttpResponse(json.dumps(ret))

    print ("request.is_ajax(): {0}".format(request.is_ajax()))
    if request.is_ajax():
        if 'task_id' in request.POST.keys() and request.POST['task_id']:
            task_id = request.POST['task_id']
            async_result.get() 
            data = {
            'state': async_result.state,
            'result': async_result.result,
            }
            #data = async_result.result or async_result.state
            print ("data: {0}".format(data))
        else:
            data = 'No task_id in the request'
    else:
        raise SuspiciousOperation("This is not an ajax request.")

    json_data = json.dumps(data)
    return HttpResponse(json_data, content_type='application/json')

task_state 中仍有许多 Unresolved 问题我不完全理解,通过反复试验我会到达那里,但现在,task_state 是没有被调用。我怀疑问题出在 AJAX 调用(“url”)上,但我不知道为什么。我哪里错了?

更新:选中“JS Test Stuff”复选框后,success.html 被渲染,没有错误。 AJAX JavaScript (task_output_retrieval.js) 是从 success.html 中调用的,这是经过验证的,因为从 success.html 我是调用 2 个 JavaScript 文件(另一个是 update-hello-user.js)。 task_output_retrieval.js 的窗口打开,update-hello-user.js 的弹出窗口也会显示。它在我调用 View 的 task_output_retrieval.js 中:

    $.ajax({
                url: query_url,
)

但这并没有被渲染。

这是控制台的输出:

[17/Aug/2018 04:59:12] INFO [django.server:124] "GET /MyApp/opt/ HTTP/1.1" 200 6631
async_result f2224e67-3e47-4980-9dc8-58622928e090
TASK_ID f2224e67-3e47-4980-9dc8-58622928e090
[17/Aug/2018 04:59:14] INFO [django.server:124] "POST /MyApp/opt/ HTTP/1.1" 200 6412
[17/Aug/2018 04:59:14] INFO [django.server:124] "GET /MyAppsite-static/MyApp/bootstrap/js/update-hello-user.js HTTP/1.1" 200 52
[17/Aug/2018 04:59:14] INFO [django.server:124] "GET /MyAppsite-static/MyApp/bootstrap/js/task_output_retrieval.js HTTP/1.1" 200 640

最佳答案

在查看您的代码时,我突然想到的问题是您在 JavaScript 文件中使用了 {% url validate_task_state %}。如果您按照最常见的推荐方法设置 Django 并提供其静态内容,您的 JavaScript 文件将不会被模板引擎处理,并且该模板标签将不会被处理。此外,它的参数需要引号,所以 {% 'url validate_task_state' %}

您应该更改您的 success.html 模板以将所需的 URL 传递给您的 task_state 函数,如下所示:

<script src="{% static 'MyAPP/bootstrap/js/task_output_retrieval.js' %}"></script>
<script type='text/javascript'> task_state("{% url 'validate_task_state' %}", "{{ task_id }}"); </script>

然后修改您的函数以接受新参数:

function task_state (query_url, task_id) {
    var taskID = task_id; 
    var newWin = window.open('', 'new window', 'width=200, height=100');

    $.ajax({
            url: query_url, 
            data: {'taskID':taskID},
            method: 'POST',
            dataType : "json",
            success: function(data){
                $(newWin.document.body).html(data);
                newWin.document.write(data);
                newWin.document.close();
                newWin.focus();
                newWin.print();
                newWin.close();
            },
            error: function (){ alert('An error occured'); }
    });
}

您在评论中说过 Django 没有看到请求。一个常见的问题是 CSRF 保护:自定义 POST 请求需要传递 CSRF token ,否则将被拒绝。如何执行此操作的细节部分取决于您的特定配置,但通常我会这样做:

// Grab the CSRF token from the cookie.
var csrftoken = $.cookie('csrftoken');
$.ajax({
  type: "POST",
  url: "... my url ...",
  headers: {
    // Pass the token with the query.
    'X-CSRFToken': csrftoken
  },
  // other ajax options...
});

关于javascript - 从 AJAX 请求调用 django View (解析 celery task_id),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51632570/

有关javascript - 从 AJAX 请求调用 django View (解析 celery task_id)的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  4. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  5. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  6. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  7. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. ruby - 调用其他方法的 TDD 方法的正确方法 - 2

    我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent

  10. ruby-on-rails - 我更新了 ruby​​ gems,现在到处都收到解析树错误和弃用警告! - 2

    简而言之错误:NOTE:Gem::SourceIndex#add_specisdeprecated,useSpecification.add_spec.Itwillberemovedonorafter2011-11-01.Gem::SourceIndex#add_speccalledfrom/opt/local/lib/ruby/site_ruby/1.8/rubygems/source_index.rb:91./opt/local/lib/ruby/gems/1.8/gems/rails-2.3.8/lib/rails/gem_dependency.rb:275:in`==':und

随机推荐