'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
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
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.
I'm a beginner at Javascript and React, any help is appreciated.
Solution 1:[1]
You need to build an API in Python, to send the data to React. The fastest way will probably be using flask, it could look like this:
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. 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gamopo |