Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - Handling GET and POST in same Flask view

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."""

My question is tangentially related to Obtaining values of request variables using python and Flask.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can distinguish between the actual method using 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

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...