简体   繁体   English

如何从 python 代码获取值到 JS 文件中的 Javascript 变量

[英]how to get a value from a python code to a Javascript variable in JS file

I'm trying to develop the frontend in Javascript for a voice bot, which was written in python我正在尝试在 Javascript 中为语音机器人开发前端,它是在 python 中编写的

if hi == 0:
    talk('hello iam kavi')
    print('hello iam kavi Voice assistant')
    talk('How are you buddy!!!')
    print('How are you buddy!!!')
    talk('doing good right?????')
    print('doing good right?????')

In the code above, instead of printing it on the terminal, I want it to be sent to Javascript code, which looks like below在上面的代码中,我希望将它发送到 Javascript 代码,而不是在终端上打印它,如下所示

class MessageParser {
  constructor(ActionProvider, state) {
    this.actionProvider = ActionProvider;
    this.state = state;
  }

  parse(message) {
    const lowerCaseMessage = message.toLowerCase()
    
    if (lowerCaseMessage.includes("hello")) {
      this.actionProvider.greet();
    }
    else{
      this.actionProvider.listening();
    }
  }
}

export default MessageParser;

where the printed text in the python code should be sent as message variable into parse(message) function.其中 python 代码中的打印文本应作为消息变量发送到 parse(message) function。

I'm a beginner at Javascript and React, any help is appreciated.我是 Javascript 和 React 的初学者,感谢任何帮助。

You need to build an API in Python, to send the data to React.你需要在 Python 中构建一个 API,将数据发送给 React。 The fastest way will probably be using flask, it could look like this:最快的方法可能是使用 flask,它可能如下所示:

from flask import Flask

app = Flask(__name__)

@app.route('/talk', methods=['GET'])
def talk():
    return talk("whatever")

Then from react you can get the message using fetch , axios or any other option in the componentDidMount or componentDidUpdate depending on your needs.然后,您可以根据需要使用fetchaxioscomponentDidMountcomponentDidUpdate中的任何其他选项从 React 获取消息。 Please, note that I don't know how your talk function works so you'll have to adapt the code to send the correct message to the frontend.请注意,我不知道您的talk function 是如何工作的,因此您必须调整代码才能将正确的消息发送到前端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM