简体   繁体   中英

get parameter input from website, run python script and get output to server

I'd like to preface this by saying that I have ZERO javascript or flask knowledge.

Basically, I have made an html interface from which I am retrieving some user input. I would like to use this input as a parameter in a python function, run this function and then somehow retrieve the output of this function (which is a string btw) to display it on the website.

Here is my code (which obviously doesn't work):

python:

import get_response

app= Flask(__name__)

@app.route('/rep_bot',methods=['GET','POST'])
def bot_rep_py():
    outputpy=get_response(request.data)
    return render_template("output.html",output=outputpy)

the javascript function that I want to perform the sending and retrieving of information:

function bot_rep_js(input) {
  $.post("http://127.0.0.1:5000/rep_bot", {
    js_input:input
  });

  return console.log(data)
}

I have tried a few other things that didn't work anyway so I'm not gonna write them here so as not to hurt your eyes anymore. If anyone would be so kind as to show and explain to me what I have to change in order for my code to behave the way I want it to I'd be very grateful.

$.post has option to assign function which will be executed when it get response. And inside this function you should get data and use it to (re)place it in HTML.

  $.post("http://127.0.0.1:5000/rep_bot",
         {js_input: input},
         function(data){console.log(data);}
  )

Minimal working example

$.post sends POST data with "Hi" to flask and flask sends back JSON data with answer "Hello World!" which $.post gets in assigned function and it puts this answer in <div>

I used render_template_string instead of render_template so all data are in one file and everyone can simply copy and run it.

from flask import Flask, request, render_template_string, jsonify

app= Flask(__name__)

def get_response(data):
    print('data:', data)  # "Hi"
    return "Hello World!"

@app.route('/rep_bot', methods=['GET','POST'])
def bot_rep_py():
    if request.method == 'POST':
        input_text  = request.form["js_input"]
        print('input_text :', input_text)
        
        output_text = get_response(input_text)
        print('output_text:', output_text)
        
        return jsonify({'answer': output_text})
    else:
        return "???"
    
@app.route('/')
def index():
    return render_template_string('''
<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>

<button>Send "Hi"</button>

<div id="answer"></div>

<script>
$(function(){

console.log("ready 1");

function bot_rep_js(input) {
  console.log(input)
  $.post("http://127.0.0.1:5000/rep_bot",
         {js_input: "Hi"},
         function(data){
            console.log(data);
            $("#answer").text(data.answer);
         },
        );
}

$("button").click(bot_rep_js);

console.log("ready 2");

});

</script>
</body>
</html>
''')

if __name__ == '__main__':    
    app.run(debug=True)#, use_reloader=False)

EDIT:

The same without jQuery using standard fetch() and .then() to execute function when it gets response from server.

from flask import Flask, request, render_template_string, jsonify

app= Flask(__name__)

def get_response(data):
    print('data:', data)  # "Hi"
    return "Hello World!"

@app.route('/rep_bot', methods=['GET','POST'])
def bot_rep_py():
    if request.method == 'POST':
        input_text  = request.form["js_input"]
        print('input_text :', input_text)
        
        output_text = get_response(input_text)
        print('output_text:', output_text)
        
        return jsonify({'answer': output_text})
    else:
        return "???"
    
@app.route('/')
def index():
    return render_template_string('''
<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">
</head>

<body>

<script>
// function `bot_rep_js` has to be before `onclick="bot_rep_js()"`

console.log("ready 1");

function bot_rep_js(input) {
  console.log("input: " + input)
  
  // create form and add file
  var formdata = new FormData();
  formdata.append("js_input", "Hi");

  // create AJAX connection
  fetch("http://127.0.0.1:5000/rep_bot", {
    method: 'POST',
    body: formdata,
    //headers: {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"}  // makes only problem
  }).then(function(response) {
    return response.json();   // get JSON from response
  }).then(function(data) {
    console.log(data);
    document.querySelector("#answer").innerText = data.answer;
  }).catch(function(err) {
    console.log("Fetch problem: " + err.message);
  });
}

console.log("ready 2");

</script>

<button onclick="bot_rep_js()">Send "Hi"</button>

<div id="answer"></div>

</body>
</html>
''')

if __name__ == '__main__':    
    app.run(debug=True)#, use_reloader=False)    

fetch() could send data as JSON but I send as FORM to make it similar to previous code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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