Reputation: 109
How do I respond to a get request with Flask? I found nothing in the documentation, I find it hard to understand, I've also searched online and found nothing.
I have a form here's part of the code:
<input type="radio" name="topic" value="{{ topic }}" id="{{ topic }}" onclick="submit()">
Now as you can see from this, the input sends the value of 'topic' when submitted.
How can I use Flask to respond to any GET request like that input? Something like this:
@app.route('/topic/[any 'topic' value from form]', methods=['GET'])
def topic():
topic = request.form['topic']
return render_template('topic.html', topic=topic)
Thanks.
UPDATE:
So I decided to use post as suggested. I tried to test post with this code:
@app.route('/topic/', methods=['POST'])
def topic():
chosenTopic = request.form['chosenTopic']
return render_template('topic.html', chosenTopic=chosenTopic)
and this form:
<input type="radio" name="chosenTopic" value="{{ topic[3:topic|length-4:] }}" id="chosenTopic" onclick="submit()">
I tested it out on the /topic page with a simple {{ chosenTopic }} but nothing appears? Does anyone have any suggestions as to why?
Upvotes: 0
Views: 2948
Reputation: 21609
Something like this shows a simple example.
from flask import Flask, request, redirect
app = Flask(__name__)
# really look in db here or do whatever you need to do to validate this as a valid topic.
def is_valid_topic(topic):
if topic == "foo":
return False
else:
return True
@app.route('/')
def index():
return '<html><form action="topic/" method="post"><input name="topic" type="text"><input type="submit"/></form></html>'
@app.route('/topic/', methods=['POST'])
def find_topic():
t = request.form['topic']
if is_valid_topic(t):
return redirect('topic/%s' % t)
else:
return "404 error INVALID TOPIC", 404
@app.route('/topic/<topic>')
def show_topic(topic):
if is_valid_topic(topic):
return '''<html><h1>The topic is %s</h1></html>''' % topic
else:
return "404 error INVALID TOPIC", 404
if __name__ == '__main__':
app.run(debug=True)
You accept the params in a POST request and redirect to the GET afterwards.
Upvotes: 2