在相同的Flask视图中处理GET和POST

时间:2017-02-03 07:07:48

标签: python flask

例如,当我输入request.form["name"]来从POST提交的表单中检索名称时,我是否还必须编写一个类似于request.form.get["name"]的单独分支?如果我想支持这两种方法,是否需要为所有POST和所有GET请求编写单独的语句?

@app.route("/register", methods=["GET", "POST"])
def register():
    """Register user."""

我的问题与Obtaining values of request variables using python and Flask切线相关。

3 个答案:

答案 0 :(得分:27)

您可以使用此处概述的request.method来区分使用GET的实际方法:http://flask.pocoo.org/docs/0.10/quickstart/#http-methods

我认为你想:

  • 使用POST方法
  • 触发路线时呈现模板
  • 读取表单输入并在使用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)
  • 触发路由时注册用户

因此,您的案例类似于文档(上面链接)中描述的案例:

heroku pg:reset -r heroku  --confirm your_heroku_app_name

答案 1 :(得分:1)

你可以治疗" POST"方法通过调用validate_on_submit()来检查表单是否提交有效数据,否则您的函数将默认响应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... 

答案 2 :(得分:1)

在此示例中,您可以轻松找到使用Post,GET方法的方法,并使用相同的方法添加其他凝乳操作。.

#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....... :)