简体   繁体   中英

how can i do a return render_template() with different variables for the same page - flask python & html

I want to do a return with the ans variable only when i get the "question" variable from the HTML page, Otherwise, do it without the variable. But even though that the code enter to the if statment (when i'm print the 'question' or the 'ans'), the second return is still being made (the one sent without the extra variable) Is there another way to render each time with a different variable? What am I doing wrong?

app = Flask(__name__)

@app.route("/")
def home():
    if 'question' in request.args:
        question= request.args.get('question')
        print(question)
        print(respond(question))
        return render_template("HTML.html" , ans=respond(question))
    else:
        return render_template("HTML.html", ans =respond(""))

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    if port == 5000:
        app.debug = True

    app.run(host='0.0.0.0', port=port)

I would recommend making a POST request from the client since its not recommended practice to send data in the body of a GET request. So you could try the following:

Can you try:

$.ajax({
        url:"/",
        type:"POST",
        data: { question: "question_text" },
        success: function(response) {
            //Do Something
        },
        error: function(xhr) {
            //Do Something to handle error
        }               
    });

Then change your Flask to accept a POST request:

@app.route("/", methods=['POST'])
def home():
    json = request.json
    if 'question' in json:
        question = json['question']
        print(question)
        print(respond(question))
        return render_template("HTML.html" , ans=respond(question))
    else:
        return render_template("HTML.html", ans =respond(""))

I am guessing that you get the input of question by a post request? If so you could do:

if request.method == 'POST' and 'question' in request.arg.get('question'):
    ## Do something
    return  return render_template("HTML.html" , ans=respond(question))
else:
    ## do something else
    return  return render_template("HTML.html")

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