Python 在同一个 Flask 视图中处理 GET 和 POST
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42018603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handling GET and POST in same Flask view
提问by Ryan
When I type request.form["name"]
, for example, to retrieve the name from a form submitted by POST, must I also write a separate branch that looks something like request.form.get["name"]
? If I want to support both methods, need I write separate statements for all POST and all GET requests?
request.form["name"]
例如,当我键入以从 POST 提交的表单中检索名称时,是否还必须编写一个类似于 的单独分支request.form.get["name"]
?如果我想同时支持这两种方法,是否需要为所有 POST 和所有 GET 请求编写单独的语句?
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user."""
My question is tangentially related to Obtaining values of request variables using python and Flask.
我的问题与使用 python 和 Flask 获取请求变量的值密切相关。
回答by jbndlr
You can distinguish between the actual method using request.method
.
您可以使用 区分实际方法request.method
。
I assume that you want to:
我假设你想:
- Render a template when the route is triggered with
GET
method - Read form inputs and register a user if route is triggered with
POST
- 使用
GET
方法触发路由时渲染模板 - 如果路由被触发,则读取表单输入并注册用户
POST
So your case is similar to the one described in the docs: Flask Quickstart - HTTP Methods
所以你的情况类似于文档中描述的情况:Flask Quickstart - HTTP Methods
import flask
app = flask.Flask('your_flask_env')
@app.route('/register', methods=['GET', 'POST'])
def register():
if flask.request.method == 'POST':
username = flask.request.values.get('user') # Your form's
password = flask.request.values.get('pass') # input names
your_register_routine(username, password)
else:
# You probably don't have args at this route with GET
# method, but if you do, you can access them like so:
yourarg = flask.request.args.get('argname')
your_register_template_rendering(yourarg)
回答by Shahzaib Ali
Here is the example in which you can easily find the way to use Post,GET method and use the same way to add other curd operations as well..
这是一个示例,您可以在其中轻松找到使用 Post,GET 方法的方法,并使用相同的方法添加其他 curd 操作。
#libraries to include
import os
from flask import request, jsonify
from app import app, mongo
import logger
ROOT_PATH = os.environ.get('ROOT_PATH')<br>
@app.route('/get/questions/', methods=['GET', 'POST','DELETE', 'PATCH'])<br>
def question():
# request.args is to get urls arguments
if request.method == 'GET':
start = request.args.get('start', default=0, type=int)
limit_url = request.args.get('limit', default=20, type=int)
questions = mongo.db.questions.find().limit(limit_url).skip(start);
data = [doc for doc in questions]
return jsonify(isError= False,
message= "Success",
statusCode= 200,
data= data), 200
# request.form to get form parameter
if request.method == 'POST':
average_time = request.form.get('average_time')
choices = request.form.get('choices')
created_by = request.form.get('created_by')
difficulty_level = request.form.get('difficulty_level')
question = request.form.get('question')
topics = request.form.get('topics')
##Do something like insert in DB or Render somewhere etc. it's up to you....... :)
回答by thangtn
You could treat "POST" method by calling the validate_on_submit() to check if the form is submitted with valid data, otherwise your function will response to GET request by default. Your function will be like this:
您可以通过调用 validate_on_submit() 来处理“POST”方法以检查表单是否使用有效数据提交,否则您的函数将默认响应 GET 请求。你的函数将是这样的:
@app.route("/register", methods=["GET", "POST"])
def register():
"""Register user."""
form = SomeForm()
# treat POST request
if form.validate_on_submit():
# do something ...
# return redirect ...
# else response to GET request
# return render_template...