You are previewing Flask By Example.
O'Reilly logo
Flask By Example

Book Description

Unleash the full potential of the Flask web framework by creating simple yet powerful web applications

About This Book

  • The most up-to-date book on Flask on the market

  • Create your own world-class applications and master the art of Flask by unravelling its enigma through this journey

  • This step-by-step tutorial is packed with examples on blending different technologies with Flask to get you up and running

  • Who This Book Is For

    Have you looked at PHP and hated the clunky bloated syntax? Or looked at .Net and wished it was more open and flexible? Maybe you’ve tried your hand at GUI libraries in Python and found them hard to use? If your answer to any one of these questions is a yes, then this is just the book for you.

    It is also intended for people who know the basics of Python and want to learn how to use it to build powerful solutions with a web front-end.

    What You Will Learn

  • Build three web applications from the ground up using the powerful Python micro framework, Flask.

  • Dynamically display data to your viewers, based on their requests

  • Store user and static data in SQL and NoSQL databases and use this data to power your web applications

  • Create a good user experience by combining HTML, CSS, and JavaScript

  • Harness the convenience of freely available APIs, including OpenWeatherMap, Open Exchange Rates, and bitly

  • Extend your applications to build advanced functionality, such as a user account control system using Flask-Login

  • Learn about web application security and defend against common attacks, such as SQL injection and XSS

  • In Detail

    This book will take you on a journey from learning about web development using Flask to building fully functional web applications. In the first major project, we develop a dynamic Headlines application that displays the latest news headlines along with up-to-date currency and weather information. In project two, we build a Crime Map application that is backed by a MySQL database, allowing users to submit information on and the location of crimes in order to plot danger zones and other crime trends within an area. In the final project, we combine Flask with more modern technologies, such as Twitter's Bootstrap and the NoSQL database MongoDB, to create a Waiter Caller application that allows restaurant patrons to easily call a waiter to their table. This pragmatic tutorial will keep you engaged as you learn the crux of Flask by working on challenging real-world applications.

    Style and approach

    This book will provide you with rich, practical experience of Flask. Every technology, that is employed along with Flask is comprehensively introduced, while the book focusses on developing web applications. Pointers to educational material are always given if you want to gain in-depth knowledge of the various technologies used.

    Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the code file.

    Table of Contents

    1. Flask By Example
      1. Table of Contents
      2. Flask By Example
      3. Credits
      4. About the Author
      5. Acknowledgements
      6. About the Reviewers
        1. eBooks, discount offers, and more
          1. Why subscribe?
      8. Preface
        1. What this book covers
        2. What you need for this book
        3. Who this book is for
        4. Conventions
        5. Reader feedback
        6. Customer support
          1. Downloading the example code
          2. Downloading the color images of this book
          3. Errata
          4. Piracy
          5. Questions
      9. 1. Hello, World!
        1. Introducing Flask
        2. Creating our development environment
          1. Installing pip
          2. Installing Flask
        3. Writing "Hello, World!"
          1. Writing the code
          2. Running the code
        4. Deploying our application to production
          1. Setting up a Virtual Private Server
          2. Configuring our server
          3. Installing and using Git
          4. Serving our Flask app with WSGI
            1. Configuring Apache to serve our Flask application
        5. Summary
      10. 2. Getting Started with Our Headlines Project
        1. Setting up our project and a Git repository
        2. Creating a new Flask application
        3. Introduction to RSS and RSS feeds
          1. Using RSS from Python
          2. URL routing in Flask
          3. Publishing our Headlines application
        4. Summary
      11. 3. Using Templates in Our Headlines Project
        1. Introducing Jinja
        2. Basic use of Jinja templates
          1. Rendering a basic template
          2. Passing dynamic data to our template
          3. Displaying dynamic data in our template
        3. Advanced use of Jinja templates
          1. Using Jinja objects
          2. Adding looping logic to our template
          3. Adding hyperlinks to our template
          4. Pushing our code to the server
        4. Summary
      12. 4. User Input for Our Headlines Project
        1. Getting user input using HTTP GET
        2. Getting user input using HTTP POST
          1. Creating a branch in Git
          2. Adding POST routes in Flask
          3. Making our HTML form use POST
          4. Reverting our Git repository
        3. Adding weather and currency data
          1. Introducing the OpenWeatherMap API
            1. Signing up with OpenWeatherMap
          2. Retrieving your OpenWeatherMap API key
          3. Parsing JSON with Python
          4. Introducing JSON
          5. Retrieving and parsing JSON in Python
          6. Using our weather code
          7. Displaying the weather data
          8. Allowing the user to customize the city
            1. Adding another search box to our template
            2. Using the user's city search in our Python code
          9. Checking our new functionality
          10. Handling duplicate city names
          11. Currency
            1. Getting an API key for the Open Exchange Rates API
            2. Using the Open Exchange Rates API
            3. Using our currency function
            4. Displaying the currency data in our template
            5. Adding inputs for the user to select currency
            6. Creating an HTML select drop-down element
            7. Adding all the currencies to the select input
            8. Displaying the selected currency in the drop-down input
        4. Summary
      13. 5. Improving the User Experience of Our Headlines Project
        1. Adding cookies to our Headlines application
          1. Using cookies with Flask
            1. Setting cookies in Flask
            2. Retrieving cookies in Flask
              1. Writing the fallback logic to check for cookies
              2. Retrieving the cookies for other data
        2. Adding CSS to our Headlines application
          1. External, internal, and inline CSS
          2. Adding our first CSS
          3. Adding padding to our CSS
            1. Adding more styles to our CSS
            2. Adding the div tags to the template file
          4. Styling our inputs
        3. Summary
      14. 6. Building an Interactive Crime Map
        1. Setting up a new Git repository
        2. Understanding relational databases
        3. Installing and configuring MySQL on our VPS
          1. Installing MySQL on our VPS
          2. Installing Python drivers for MySQL
        4. Creating our Crime Map database in MySQL
          1. Creating a database setup script
            1. Creating the database
            2. Looking at our table columns
            3. Indexing and committing
          2. Using the database setup script
            1. Adding credentials to our setup script
            2. Running our database setup script
        5. Creating a basic database web application
          1. Setting up our directory structure
          2. Looking at our application code
          3. Looking at our SQL code
            1. Reading data
            2. Inserting data
            3. Deleting data
          4. Creating our view code
          5. Running the code on our VPS
          6. Mitigating against SQL injection
            1. Injecting SQL into our database application
            2. Mitigating against SQL injection
        6. Summary
      15. 7. Adding Google Maps to Our Crime Map Project
        1. Running a database application locally
          1. Creating a mock of our database
            1. Adding a test flag
            2. Writing the mock code
            3. Validating our expectations
        2. Adding an embedded Google Maps widget to our application
          1. Adding the map to our template
            1. Introducing JavaScript
            2. The body of our HTML code
            3. Testing and debugging
          2. Making our map interactive
            1. Adding markers
            2. Using a single marker
        3. Adding an input form for new crimes
          1. The HTML code for the form
          2. Adding external CSS to our web application
            1. Creating the CSS file in our directory structure
            2. Adding CSS code
            3. Configuring Flask to use CSS
            4. Viewing the result
            5. Publishing the result
          3. Linking the form to the backend
            1. Setting up the URL to collect POST data
            2. Adding the database methods
            3. Testing the code on the server
        4. Displaying existing crimes on our map
          1. Getting data from SQL
          2. Passing the data to our template
          3. Using the data in our template
          4. Viewing the results
        5. Summary
      16. 8. Validating User Input in Our Crime Map Project
        1. Choosing where to validate
          1. Identifying inputs that require validation
        2. Trying out an XSS example
          1. The potential of persistent XSS
        3. Validating and sanitizing
          1. White and blacklisting
          2. Validating versus sanitizing
          3. Implementing validation
          4. Validating the category
          5. Validating the location
          6. Validating the date
          7. Validating the description
        4. Summary
      17. 9. Building a Waiter Caller App
        1. Setting up a new Git repository
          1. Setting up the new project locally
          2. Setting up the project on our VPS
        2. Using Bootstrap to kick-start our application
          1. Introducing Bootstrap
          2. Downloading Bootstrap
            1. Bootstrap templates
        3. Adding user account control to our application
          1. Introducing Flask-Login
          2. Installing and importing Flask-Login
          3. Using Flask extensions
          4. Adding a restricted route
          5. Authenticating a user
            1. Creating a user class
          6. Mocking our database for users
          7. Logging in a user
            1. Adding imports and configuration
            2. Adding the login functionality
              1. Writing the login function
              2. Creating the load_user function
            3. Checking the login functionality
          8. Logging out a user
          9. Registering a user
            1. Managing passwords with cryptographic hashes
              1. Python hashlib
              2. Reversing hashes
              3. Salting passwords
            2. Implementing secure password storage in Python
              1. Creating the PasswordHelper class
              2. Updating our database code
              3. Updating our application code
        4. Summary
      18. 10. Template Inheritance and WTForms in Waiter Caller Project
        1. Adding the Account and Dashboard pages
          1. Introducing Jinja templates
            1. Creating the base template
            2. Creating the dashboard template
            3. Creating the account template
            4. Creating the home template
            5. Adding the routing code
          2. Creating restaurant tables
            1. Writing the restaurant table code
              1. Adding the create table form
              2. Adding the create table route
              3. Adding the create table database code
              4. Adding the view table database code
              5. Modifying the account route to pass table data
              6. Modifying the template to show the tables
              7. Adding the delete table route to our backend code
            2. Testing the restaurant table code
        2. Shortening URLs using the bitly API
          1. Introducing Bitly
          2. Using the bitly API
          3. Getting a bitly oauth token
          4. Creating the bitlyhelper file
          5. Using the bitly module
        3. Adding functionality to handle attention requests
          1. Writing the attention request code
            1. Adding the attention request route
            2. Adding the attention request database code
            3. Add the get and delete methods for attention requests
            4. Modifying the dashboard route to use attention requests
            5. Modifying the template code to display attention requests
            6. Adding the resolve request application code
            7. Testing the attention request code
            8. Auto-refreshing the dashboard page
        4. Adding user feedback with WTForms
          1. Introducing WTForms
          2. Installing Flask-WTF
          3. Creating the registration form
          4. Rendering the registration form
            1. Updating the application code
            2. Updating the template code
            3. Testing the new form
            4. Using WTForms in our application code
            5. Displaying errors to our user
              1. Displaying the errors in our template
              2. Adding CSS for the errors
            6. Testing the final registration form
            7. Adding a successful registration notification
              1. Passing the message from the application code
              2. Using the message in the template code
          5. Modifying the login form
            1. Creating the new LoginForm in the application code
            2. Using the new LoginForm in the template
          6. Modifying the create table form
        5. Summary
      19. 11. Using MongoDB with Our Waiter Caller Project
        1. Introducing MongoDB
        2. Installing MongoDB
        3. Using the MongoDB shell
          1. Starting the MongoDB shell
          2. Running commands in the MongoDB shell
            1. Creating data with MongoDB
            2. Reading data with MongoDB
            3. Updating data with MongoDB
            4. Deleting data with MongoDB
        4. Introducing PyMongo
          1. Writing the DBHelper class
            1. Adding the user methods
            2. Adding the table methods
            3. Adding the request methods
          2. Changing the application code
        5. Testing our application in production
        6. Adding some finishing touches
          1. Adding indices to MongoDB
            1. Where do we add indices?
          2. Adding a favicon
        7. Summary
      20. A. A Sneak Peek into the Future
        1. Expanding the projects
          1. Adding a domain name
          2. Adding HTTPS
          3. E-mail confirmation for new registrations
          4. Google Analytics
          5. Scalability
        2. Expanding your Flask knowledge
          1. VirtualEnv
          2. Flask Blueprints
          3. Flask extensions
            1. Flask-SQLAlchemy
            2. Flask MongoDB extensions
              1. Flask-MongoAlchemy
              2. Flask-PyMongo
            3. Flask-MongoEngine
            4. Flask-Mail
            5. Flask-Security
            6. Other Flask extensions
        3. Expanding your web development knowledge
        4. Summary
      21. Index