猿问

“return render_template()”不起作用

我想意识到这一点。

  1. 用户对 Web 浏览器说话。

  2. 网络浏览器(谷歌浏览器)将用户的声音记录为 WAV 文件(Recorder.js)并将其发送到 python-flask 服务器。

  3. Python 服务器调用 Google Cloud 文本转语音 API 并转录 WAV 文件。

  4. 将转录的文本发送到 Web 浏览器。

我使用 Windows 10、WSL、Debian 10/buster、python3.7.6 和 Google Chrome 在本地开发此应用程序。

我实现了第 1、2、3 步,但没有实现第 4 步。在第 2 步中,我曾经XMLHttpRequest()将 WAV 文件发送到 python-flask 服务器。所以,在第4步中,我不能return render_template()以普通方式使用。

我搜索了“XMLHttpRequest() flask return render_template()”并找到了一个解决方案(如何获得 XMLHttpRequest 的响应?)使用

XMLHttpRequest.responseTextXMLHttpRequest.onreadystatechange什么时候XMLHttpRequest.readyState等于XMLHttpRequest.DONE

xhr.onreadystatechange = function() {

    if (xhr.readyState == XMLHttpRequest.DONE) {

        alert(xhr.responseText);

    }

}

因此,我将此代码添加到我的 app.js 中,但仍然无法获取return render_template(). 这是终端的结果。


127.0.0.1 - - [04/Feb/2020 16:55:58] "GET / HTTP/1.1" 200 -

['Transcript: 明日雪が降らないといいです。']

127.0.0.1 - - [04/Feb/2020 16:56:25] "POST / HTTP/1.1" 200 -

你能给我任何信息或建议吗?我知道stackoverflow中有很多类似的问答。我看了10多篇文章并尝试了它们,但我的困难并没有解决。请告诉我如何更改我的代码?


慕哥6287543
浏览 167回答 1
1回答

明月笑刀无情

它的发生是因为您更改正在调用更改 Ajax 请求(XMLHttpRequest)内部 HTML 的路由,因此您有两个选择,第一个是更改 HTML 以响应如下:xhr.onreadystatechange = function() {    if (xhr.readyState == XMLHttpRequest.DONE) {        document.write(xhr.responseText);    }}// or using query(its better to me)$.ajax({        type: "POST",        contentType: 'application/json',        url: "/",        data: {audio_data: blob}        success:function(response){            document.write(response);        }    });另一种是做API,不需要调用render_template,只需要在index函数中返回resultsentence(这个result需要是dict格式)@app.route("/", methods=['POST', 'GET'])def index():    if request.method == "POST":        #the image logic...        return make_response(resultsentence)    else:        return render_template("index.html")这样,您将需要使用 javascript 处理前端的响应
随时随地看视频慕课网APP

相关分类

Python
我要回答