在同一Flask视图中处理GET和POST [英] Handling GET and POST in same Flask view

查看:130
本文介绍了在同一Flask视图中处理GET和POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

我的问题与获得相关使用python和Flask的请求变量的值.

推荐答案

您可以使用request.method区分实际方法.

You can distinguish between the actual method using request.method.

我假设您要

  • 使用GET方法触发路线时呈现模板
  • 如果使用POST
  • 触发了路线,则读取表单输入并注册用户
  • Render a template when the route is triggered with GET method
  • Read form inputs and register a user if route is triggered with POST

因此,您的情况类似于文档中所述的情况: Flask快速入门-HTTP方法

So your case is similar to the one described in the docs: 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)

这篇关于在同一Flask视图中处理GET和POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆