[英]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.