为了账号安全,请及时绑定邮箱和手机立即绑定

“return render_template()”不起作用

“return render_template()”不起作用

慕哥6287543 2022-07-19 15:44:13
我想意识到这一点。用户对 Web 浏览器说话。网络浏览器(谷歌浏览器)将用户的声音记录为 WAV 文件(Recorder.js)并将其发送到 python-flask 服务器。Python 服务器调用 Google Cloud 文本转语音 API 并转录 WAV 文件。将转录的文本发送到 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.responseText在XMLHttpRequest.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多篇文章并尝试了它们,但我的困难并没有解决。请告诉我如何更改我的代码?
查看完整描述

1 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

它的发生是因为您更改正在调用更改 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 处理前端的响应


查看完整回答
反对 回复 2022-07-19
  • 1 回答
  • 0 关注
  • 166 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号