Book Image

Building Web Applications with Flask

By : Italo M Campelo Maia, Jack Stouffer, Gareth Dwyer, Italo Maia
Book Image

Building Web Applications with Flask

By: Italo M Campelo Maia, Jack Stouffer, Gareth Dwyer, Italo Maia

Overview of this book

Table of Contents (17 chapters)
Building Web Applications with Flask
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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