简体   繁体   中英

Returning an input sentence on html with Flask and Python

I am totally new to Flask, so I am just experimenting for the moment. I simply want to read in a sentence from the user interface and then return the sentence. However, I get the error:

BadRequestKeyError(key)

My code looks as follows:

from flask import Flask, render_template, request, redirect

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/query', methods=['GET', 'POST'])
def do_query():
    query = request.form['query']
    if request.method == 'POST':
        return redirect('/query')
    else:
        return render_template('query.html', query=query)

if __name__ == '__main__':
    app.run(debug=True)

And the query.html is like this:

{% extends 'base.html' %}
{% block body%}
    <form action="/query" method=”POST”>
        <label> Enter your Query Sentence: </label>
        <input type=”text” name=”query” id="query" >
        <input type="submit" value="Submit">
    </form>

    <p>Here is your sentence: {{query}}</p>

{% endblock %}

I think the problem might be, that the query variable is not initialized, but I don't know how to fix it. Can anyone help me?

If you rewrite you route thus:

@app.route('/query', methods=['GET', 'POST'])
def do_query():
    query = request.form['query'] if request.method == 'POST' else ''
    return render_template('query.html', query=query)

You will not be trying to access non-existing request data (ie, form data of a non-POST request). This will mean that when you first navigate to the /query page, the template will display something like:

Here is your sentence:

(ie, no value for query )

The wrong request type issue, however, will be gone, as will the redundant redirection. Try to minimize the use of redirection, since they significantly slow down interactions, and hurt the user experience.

Solution:

The code didn't work, because I used the wrong quotes in the html file. By default, html chooses the correct quotes and (at least within PyCharm), it is not possible to make any mistakes. However, I copied the html code from a stackoverflow source. Once I fixed that, the answer provided by @Amitai Irron was working:)

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