Bicheng
Bicheng

Reputation: 727

How does web forms be processed by the web server?

I am learning flask through the book Flask Web Development. I am confused about how web forms be processed by the web server. More concretely, how POSt request be processed in the web server?

Here is code snippet for generating response to the main index request:

@app.route('/', methods=['GET', 'POST'])
def index():
    name = None
    form = NameForm()
    if form.validate_on_submit():
        name = form.name.data
        form.name.data = ''
    return render_template('index.html', form=form, name=name)

In my opinion, when the client visit the main index for the first time, flask app will receive a GET request. This GET request will be processed by the index view function. form will be constructed from NameForm(), and it will be empty at that time. So form.validate_on_submit() will return false.

Then, when user submits the form with data through a POST request, it will also be processed by the index view function. So another form will be constructed from NameFrom(), and I think it will be empty too, which make form.validate_on_submit() still return false.

Obviously, my thinking is wrong.

My question is: how does form.validate_on_submit() evaluated to be true when user submit the form through a POST?

Thanks in advance!

Upvotes: 0

Views: 52

Answers (1)

Tim
Tim

Reputation: 2637

When using Flask the current request context can be obtained from flask.request. The request object includes the current method and POST variables (along with headers/cookies/path etc from the HTTP protocol).

When a call is made to form.validate_on_submit() this method uses the current request object to first check if the request method is POST before extracting and validating the POST variables.

Upvotes: 1

Related Questions