Handling forms

Now let's see how to integrate our form from example 1 with an application:

# coding:utf-8

from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/', methods=['get', 'post'])
def login_view():
    # the methods that handle requests are called views, in flask
    msg = ''

    # form is a dictionary like attribute that holds the form data
    if request.method == 'POST':
      username = request.form["username"]
        passwd = request.form["passwd"]

        # static useless validation
        if username == 'you' and passwd == 'flask':
            msg = 'Username and password are correct'
        else:
            msg = 'Username or password are incorrect'
    return render_template('form.html', message=msg)

if __name__=='__main__':
    app.run()

In the preceding example, we define a view called login_view that accepts get or post requests; when the request is post (we ignore the form if it was sent by a get request), we fetch the values for username and passwd; then we run a very simple validation and change the value of msg accordingly.

Tip

Beware: a view, in Flask, is not the same as a view in MVC. In Flask, a view is the component that receives a request and returns a response, which may be a function or a class.

Did you see the request variable we are handling in our example? That's a proxy to the current active request context. That's why request.form points to the sent form data.

Now, what if you're receiving a parameter encoded in the URL? How will you get it, given that the request URL is http://localhost:5000/?page=10?

# inside a flask view
def some_view():
    try:
        page = int(request.args.get('page', 1))
        assert page == 10
    except ValueError:
        page = 1
    ...

The preceding example is pretty common when paginating. Just as before, request.args is related to the current user request only. Easy!

So far, we have handled form validation pretty poorly with inline validation. No more! Let's try something fancier from now on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.10.246