Answer the question
In order to leave comments, you need to log in
How to call a Python function from JavaScript?
Hello!
Please help me solve the following problem.
I am implementing a simple chat bot with DialogFlow. On a python I am connected to it and I receive the answer according to the text of the user.
It is necessary to call a Python function from JavaScript, which, in turn, must return the result back. I understand that you need to use Ajax, right? But how exactly? Please explain
here is the python code
import dialogflow_v2 as dialogflow
from dialogflow_v2.types import TextInput, QueryInput
import os
def detect_intent_texts(project_id, session_id, texts, language_code):
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'tratata.json'
session_client = dialogflow.SessionsClient()
session = session_client.session_path(project_id, session_id)
print('Session path: {}\n'.format(session))
for text in texts:
text_input = TextInput(text=text, language_code=language_code)
query_input = QueryInput(text=text_input)
response = session_client.detect_intent(session=session, query_input=query_input)
print('Fulfillment text: {}\n'.format(response.query_result.fulfillment_text))
detect_intent_texts("token", "session_id", ["Здесь должнен быть текст, переданный из JS"], "ru")
Answer the question
In order to leave comments, you need to log in
Well, in fact, you need to create a web application
where the backend will call your ready-made function, and on the front a form of a pair of input fields and a button on which a JS handler is hung
for the backend, I would use FastAPI
something like this:
from fastapi import FastAPI
app = FastAPI()
@app.get("/dialog/")
def read_item(message: str, lang: str = 'ru'):
return {'message': detect_intent_texts(TOKEN, SESSION_ID, message, lang)
document.querySelector("#button").addEventListener("click", (event) => {
const msg = document.querySelector("#message").value;
const lang = document.querySelector("#lang").value;
fetch('/dialog/?' + new URLSearchParams({
message: msg,
lang: lang,
}))
.then((response) => {
if (!response.ok) {
throw new Error("HTTP error, status = " + response.status);
}
return response.json();
})
.then((data) => {
alert(data.message);
})
.catch((error) => {
alert(error);
});
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question