Issue
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.
Solution
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)
Answered By - jbndlr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.