Reader small image

You're reading from  Building Web Applications with Flask

Product typeBook
Published inJun 2015
Reading LevelBeginner
Publisher
ISBN-139781784396152
Edition1st Edition
Languages
Tools
Right arrow
Authors (4):
Italo M Campelo Maia
Italo M Campelo Maia
author image
Italo M Campelo Maia

Italo Maia is a full-stack developer with 10 years of experience in creating software for the mobile, Web, and desktop environments, having dedicated most of the last few years to development with Python and web technologies. Author of Flask-Empty, a popular skeleton for Flask projects that aggregates good practices and recipes for quick prototyping, he is active in the Brazilian Python communities, having open source tools and libraries available in GitHub and Bitbucket.
Read more about Italo M Campelo Maia

Jack Stouffer
Jack Stouffer
author image
Jack Stouffer

Jack Stouffer is a programmer who has several years of experience in designing web applications. He switched to Flask three years ago for all his projects. He currently works for Apollo America in Auburn Hills, Michigan, and writes internal business tools and software using Python, Flask, and JavaScript. Jack is a believer and supporter of open source technology. When he released his Flask examples with the recommended best practices on GitHub (https://github.com/JackStouffer), it became one of the most popular Flask repositories on the site. Jack has also worked as a reviewer for Flask Framework Cookbook, Packt Publishing.
Read more about Jack Stouffer

Gareth Dwyer
Gareth Dwyer
author image
Gareth Dwyer

Gareth Dwyer hails from South Africa but now lives in Europe. He is a software engineer and author and is currently serving as the CTO at the largest coding education provider in Africa. Gareth is passionate about technology, education, and sharing knowledge through mentorship. He holds four university degrees in computer science and machine learning, with a specialization in natural language processing. He has worked with companies such as Amazon Web Services and has published many online tutorials as well as the book Flask by Example.
Read more about Gareth Dwyer

Italo Maia
Italo Maia
author image
Italo Maia

Italo Maia is a full-stack developer with 10 years of experience in creating software for the mobile, Web, and desktop environments, having dedicated most of the last few years to development with Python and web technologies. Author of Flask-Empty, a popular skeleton for Flask projects that aggregates good practices and recipes for quick prototyping, he is active in the Brazilian Python communities, having open source tools and libraries available in GitHub and Bitbucket.
Read more about Italo Maia

View More author details
Right arrow

Chapter 4. Please Fill in This Form, Madam

Have you ever imagined what happens when you fill in a form on a website and click on that fancy Send button at the end of it? Well, all the data you wrote—comment, name, checkbox, or whatever—is encoded and sent through a protocol to the server, which then routes that information to the Web application. The Web application will validate the data origin, read the form, validate the data syntactically then semantically, and then decide what to do with it. Do you see that long chain of events where every link might be the cause of a problem? That's forms for you.

In any case, there is nothing to fear! Flask can help you in those steps but there are also tools specifically designed for this purpose. In this chapter, we will learn:

  • How to write and handle forms with Flask

  • How to validate form data

  • How to use WTForms to validate forms with Flask

  • How to implement cross-site request forgery protection

This will actually be a fairly smooth chapter, with lots...

HTML forms for the faint of heart


HTML is, pretty much, the language in which the Web is written. With the help of special markups called tags, it's possible to add meaning and context to plain text, turning it into HTML. For us, HTML is a means to an end. So, if you want to learn more about it, please open http://www.w3schools.com/html/ in your preferred browser. We are not covering HTML syntax fully, nor all the beautiful magic involved in the process.

Although we will not cover HTML extensively, we will cover HTML specifically; by this, I refer to the <form> tag. Here is the deal: every time you open a webpage and there are a few blank fields for you to fill in, you're most likely filling in an HTML form. That's the plainest way to transfer data from your browser to a server. How does that work? Let's see an example:

<!-- example 1 -->
<form method='post' action='.'>
<input type='text' name='username' />
<input type='password' name='passwd' />
<input type...

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

WTForms and you


WTForms (https://github.com/wtforms/wtforms) is a standalone robust form handling library that allows you to generate HTML forms from form-like classes, implement fields and form validation, and include cross-source forgery protection (a nasty vulnerability that crackers may try to exploit in your Web applications). We certainly don't want that!

First, to install WTForms library, use the following:

pip install wtforms

Now let's write some forms. A WTForms form is a class that extends the Form class. As plain as that! Let's create a login form that could be used with our previous login example:

from wtforms import Form, StringField, PasswordField
class LoginForm(Form):
    username = StringField(u'Username:')
    passwd = PasswordField(u'Password:')

In the preceding code, we have a form with two fields, username and passwd, with no validation. It is just enough to build a form in a template, like this:

<form method='post'>
{% for field in form %}
    {{ field.label }}
 ...

Flask-WTF


Flask uses extensions in order to integrate transparently with third party libraries. WTForms with Flask-WTF is a good example of that as we will soon see. And, by the way, a Flask extension is a piece of code that integrates its configuration, context, and usage with Flask in a predictable way. That means extension usage is pretty similar. Now make sure Flask-WTF is installed in your virtual environment before continuing:

# oh god, so hard... not!
pip flask-wtf

From http://flask-wtf.readthedocs.org/, the project website, we have the following list of features offered by Flask-WTF:

  • Integration with WTForms

  • Secure form with a CSRF token

  • File upload that works with Flask-Uploads

  • Global CSRF protection

  • Recaptcha support

  • Internationalization integration

We'll see the first two features in this chapter while the third will be discussed in Chapter 10, What Now?. The last three features will not be covered in this book. We advise you to explore them as homework.

Integration with WTForms

Flask...

Summary


So much learned... What can I say! No harm trying, right? Well, we have seen how to write HTML forms; read forms with Flask; write WTForms forms; validate form data with plain Python and form validators; and write custom validators. We also saw how to use Flask-WTF to write and validate our forms and how to protect our applications against CSRF attacks.

In the next chapter, we'll look at how to store our Web application data in relational and non-relational databases using great, easy-to-use libraries and how to integrate them with Flask. A brief overview on databases will also take place to make for smoother knowledge absorption.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building Web Applications with Flask
Published in: Jun 2015Publisher: ISBN-13: 9781784396152
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (4)

author image
Italo M Campelo Maia

Italo Maia is a full-stack developer with 10 years of experience in creating software for the mobile, Web, and desktop environments, having dedicated most of the last few years to development with Python and web technologies. Author of Flask-Empty, a popular skeleton for Flask projects that aggregates good practices and recipes for quick prototyping, he is active in the Brazilian Python communities, having open source tools and libraries available in GitHub and Bitbucket.
Read more about Italo M Campelo Maia

author image
Jack Stouffer

Jack Stouffer is a programmer who has several years of experience in designing web applications. He switched to Flask three years ago for all his projects. He currently works for Apollo America in Auburn Hills, Michigan, and writes internal business tools and software using Python, Flask, and JavaScript. Jack is a believer and supporter of open source technology. When he released his Flask examples with the recommended best practices on GitHub (https://github.com/JackStouffer), it became one of the most popular Flask repositories on the site. Jack has also worked as a reviewer for Flask Framework Cookbook, Packt Publishing.
Read more about Jack Stouffer

author image
Gareth Dwyer

Gareth Dwyer hails from South Africa but now lives in Europe. He is a software engineer and author and is currently serving as the CTO at the largest coding education provider in Africa. Gareth is passionate about technology, education, and sharing knowledge through mentorship. He holds four university degrees in computer science and machine learning, with a specialization in natural language processing. He has worked with companies such as Amazon Web Services and has published many online tutorials as well as the book Flask by Example.
Read more about Gareth Dwyer

author image
Italo Maia

Italo Maia is a full-stack developer with 10 years of experience in creating software for the mobile, Web, and desktop environments, having dedicated most of the last few years to development with Python and web technologies. Author of Flask-Empty, a popular skeleton for Flask projects that aggregates good practices and recipes for quick prototyping, he is active in the Brazilian Python communities, having open source tools and libraries available in GitHub and Bitbucket.
Read more about Italo Maia