[英]How do I respond to a get request with Flask?
如何回應Flask的獲取請求? 我在文檔中什么都沒找到,很難理解,我也在網上搜索,卻一無所獲。
我有一個形式,這是代碼的一部分:
<input type="radio" name="topic" value="{{ topic }}" id="{{ topic }}" onclick="submit()">
現在,您可以從中看到,輸入在提交時將發送“ topic”的值。
如何使用Flask響應任何類似該輸入的GET請求? 像這樣:
@app.route('/topic/[any 'topic' value from form]', methods=['GET'])
def topic():
topic = request.form['topic']
return render_template('topic.html', topic=topic)
謝謝。
更新:
因此,我決定按照建議使用post。 我試圖用以下代碼測試帖子:
@app.route('/topic/', methods=['POST'])
def topic():
chosenTopic = request.form['chosenTopic']
return render_template('topic.html', chosenTopic=chosenTopic)
和這種形式:
<input type="radio" name="chosenTopic" value="{{ topic[3:topic|length-4:] }}" id="chosenTopic" onclick="submit()">
我使用簡單的{{selectedTopic}}在/ topic頁面上對其進行了測試,但沒有顯示任何內容? 有人對為什么有任何建議嗎?
這樣的例子顯示了一個簡單的例子。
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)
您在POST請求中接受參數,然后重定向到GET。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.