The Fetch - Flask combo
While I was messing around with Flask to use Python for an online AI hobby-app (here), I ran across a problem with time-outs. The way I was using Flask was to submit an HTML form, which then technomagically sent a request to Flask to run the Python that got a response from the AI via the API and then generated the new webpage. The problem was that the API took so long that the server timed out before Flask could get to opening the new webpage.
After flailing around trying to find ways to make that overall method work, I found out about the fetch() command in JavaScript. I didn't know about it, but it turned out to be an improved AJAX query that lets you, from JavaScript, asynchronously, without loading a new page, get data from another file. The question was - would it work to point the fetch command at a Flask entry point? If so, the AI could take its time retrieving a response, and I could just use JavaScript to update stuff on the webpage.
And it turned out that does just work! So I'm spreading the good news. The main bits of code were, in the JavaScript:
let data = new URLSearchParams();
data.append('query', document.getElementById("query").value); // This refers to a TextArea
let file = "fetch_info"
fetch(file, {
method: 'POST',
body:data
}).then(response => response.json()).then(json => {
document.getElementById("resptext0").innerText = json.response // This refers to a div
})
and in the app.py for Flask, the fetch_info entry point used as the "file name" in fetch():
@app.route('/fetch_info', methods=['GET', 'POST'])
def f_fetch():
query = request.form['query']
input = funcs.create_input(query) // Converts the query to input for the AI API
response = funcs.query_AI(input) // Gets the response from the AI - the slow bit
jsonResp = {'response': response}
return jsonify(jsonResp)
And that's it!