使用 Flask 发送和接收 GET 请求的问题
Issues sending and receiving a GET request using Flask
我在使用 GET 请求正确发送和接收变量时遇到问题。我也无法在网上找到任何信息。从下面的 HTML 表单中,您可以看到我正在发送 'question' 的值,但我也从表单中的单选按钮接收 'topic' (尽管代码是为了那个不在下面)。
我想使用 POST 发送 'topic',但对 'question' 使用 GET。我知道表单方法是 POST 虽然我不确定如何同时满足 POST 和 GET.
HTML 形式:
<form method="POST" action="{{ url_for('topic', question=1) }}">
我的第二个问题是我不确定如何从表单中接收 'topic' 和 'question'。我已成功收到 'topic',如下所示,但我不太确定如何收到 'question'。 URL 最好是这样:
www.website.com/topic/SomeTopic?question=1
下面的代码是我在网上查到的request.args[]是用来接收GET请求的,不知道对不对。
烧瓶:
@app.route('/topic/<topic>', methods=['POST', 'GET'])
def questions(topic):
question = request.args['questions']
return render_template('page.html')
问题是
- 如何使用 GET 和 POST 从表单发送两个变量同时用于不同的变量。
- 我将如何接收这两个变量?
对您的问题的简短回答是您不能使用相同的表单同时发送 GET 和 POST。
但是如果您希望 url 看起来像您指定的那样:
www.website.com/topic/SomeTopic?question=1
那么你就快完成了。首先,您需要知道主题的名称,因为您必须在调用 url_for()
的问题 url 中指定该名称。
<form method="GET" action="{{ url_for('questions', topic_name="cars") }}">
# Your url will be generated as www.website.com/topic/cars
烧瓶
# Note that I changed the variable name here so you can see how
# its related to what's passed into url_for
@app.route('/topic/<topic_name>')
def questions(topic_name):
question = request.args['question']
return render_template('page.html')
现在,当您提交表单时,您的输入将作为 GET 发送,假设您有一个名称为 question
的输入字段,您将能够获取该字段的值。
我在使用 GET 请求正确发送和接收变量时遇到问题。我也无法在网上找到任何信息。从下面的 HTML 表单中,您可以看到我正在发送 'question' 的值,但我也从表单中的单选按钮接收 'topic' (尽管代码是为了那个不在下面)。
我想使用 POST 发送 'topic',但对 'question' 使用 GET。我知道表单方法是 POST 虽然我不确定如何同时满足 POST 和 GET.
HTML 形式:
<form method="POST" action="{{ url_for('topic', question=1) }}">
我的第二个问题是我不确定如何从表单中接收 'topic' 和 'question'。我已成功收到 'topic',如下所示,但我不太确定如何收到 'question'。 URL 最好是这样:
www.website.com/topic/SomeTopic?question=1
下面的代码是我在网上查到的request.args[]是用来接收GET请求的,不知道对不对。
烧瓶:
@app.route('/topic/<topic>', methods=['POST', 'GET'])
def questions(topic):
question = request.args['questions']
return render_template('page.html')
问题是
- 如何使用 GET 和 POST 从表单发送两个变量同时用于不同的变量。
- 我将如何接收这两个变量?
对您的问题的简短回答是您不能使用相同的表单同时发送 GET 和 POST。
但是如果您希望 url 看起来像您指定的那样:
www.website.com/topic/SomeTopic?question=1
那么你就快完成了。首先,您需要知道主题的名称,因为您必须在调用 url_for()
的问题 url 中指定该名称。
<form method="GET" action="{{ url_for('questions', topic_name="cars") }}">
# Your url will be generated as www.website.com/topic/cars
烧瓶
# Note that I changed the variable name here so you can see how
# its related to what's passed into url_for
@app.route('/topic/<topic_name>')
def questions(topic_name):
question = request.args['question']
return render_template('page.html')
现在,当您提交表单时,您的输入将作为 GET 发送,假设您有一个名称为 question
的输入字段,您将能够获取该字段的值。