Book Image

Flask By Example

By : Gareth Dwyer
Book Image

Flask By Example

By: Gareth Dwyer

Overview of this book

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.
Table of Contents (20 chapters)
Flask By Example
Credits
About the Author
Acknowledgements
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

In theory, nothing works, but everyone knows why. In practice, everything works but no one knows why. Here, we combine theory and practice; nothing works and no one knows why!

Learning computer science must always be a combination of theory and practice; you need to know what you're doing (theory), but you also need to know how to do it (practice). My experience of learning how to create web applications was that few teachers found a sweet spot for this balance; either I read pages and pages about inheritance, virtual environments, and test-driven development, wondering how it all applied to me, or I installed a bunch of tools and frameworks and libraries and watched the magic happen with no idea how it worked.

What follows is, I hope, a good balance. From the first chapter, you'll have a Flask web application running that the whole world can visit, which is quite practical even if it doesn't do anything but greet visitors with "Hello, World!". In the chapters that follow, we'll walk through building three interesting and useful projects together. In general, we'll build things ourselves wherever possible. While it's not good to reinvent the wheel, it is good to be exposed to a problem before you're exposed to the solution. Learning a CSS framework before you write a single line of CSS leaves you in a confused state, in which you would wonder, "But why do I actually need this?", and the same goes for many other frameworks and tools. So, we'll start from scratch, take a look at why it's difficult, and then introduce tools to make our lives easier. I think this is the ideal balance between theory and practice.

When I told people I was writing a book on Flask, the common response was "Why? There are already so many books and tutorials on Flask." This is a valid question, and the answer to it provides a nice outline for what to expect from this book. Flask By Example is different from other Flask educational material and here's why.

We won't leave you stranded

Many Flask tutorials show you how to develop a Flask application and run it locally on your own machine, and then they end. This is great as a first step, but if you're interested in building web applications, you probably want them to be accessible on the Web so that your friends, family, coworkers, and customers can admire your handiwork without popping by your house. From our first project onward, our applications will run on a Virtual Private Server (VPS) and be accessible to the world.

We won't build a blogging application

If you've read any web application development tutorials, you must have noticed that nearly every one of them is about how to build a blog using x and y. I'm pretty tired of the blog example (actually, I never want to see anyone show me how to build a blog again). Instead, you'll create some interesting, original, and possibly even useful projects while learning how to develop web applications with Flask.

We will focus on security

Cybercrime has become something of a buzzword of late. Arguably, the reason that we read about major web applications being hacked on an almost daily basis is because so many developers do not know about SQL Injection, CSRF, XSS, how to store passwords, and so many other things that should really be considered basic knowledge. As we develop the three projects in this book, we'll take the time to explain some core security concepts in detail and show you how to harden our applications against potentially malicious attackers.

We will give in-depth explanations

We won't just give you some code and tell you to run it. Wherever possible, we will explain what we're doing, why we're doing it, and how we're doing it. This means that you'll be able to take ideas from all of the projects, combine them with your own ideas, and get started with building original content right after working through this book.

Therefore, I hope that this book will be of use to you, no matter whether you are beginning to cut your teeth in the world of computer science and programming or have a computer science degree from a famous university and have compiler theory pouring out of your ears but now want to build something practical and fun. May you have as much fun working through the projects as I did while putting them together!

What this book covers

Chapter 1, Hello, World!, teaches you to set up our development environment and a web server and write our first Flask application.

Chapter 2, Getting Started with Our Headlines Project, shows you how to run Python code when the user visits a URL and how to return basic data to the user. We will also look at fetching the latest headlines automatically using RSS feeds.

Chapter 3, Using Templates in Our Headlines Project, introduces Jinja templates and integrates them into our Headlines project. We will show how to serve dynamic HTML content by passing data from our Python code to template files.

Chapter 4, User Input for Our Headlines Project, shows how to get input from our users over the Internet and use this input to customize what we will show our users. We will look at how to access currenct weather information through JSON APIs and include this information in our Headlines project.

Chapter 5, Improving the User Experience of Our Headlines Project, instructs you to add cookies to our Headlines project so that our application can remember our users' choices. We will also style our application by adding some basic CSS.

Chapter 6, Building an Interactive Crime Map, introduces our new project, which is a crime map. We will introduce relational databases, install MySQL on our server, and look at how to interact with our database from our Flask application.

Chapter 7, Adding Google Maps to our Crime Map Project, instructs you on adding a Google Maps widget and shows how to add and remove markers from the map based on our database. We will add an HTML form with various inputs for users to submit new crimes and also display the existing crimes.

Chapter 8, Validating User Input in Our Crime Map Project, polishes off our second project by making sure that users can't break it accidentally or through maliciously crafted input.

Chapter 9, Building a Waiter Caller App, introduces our final project, which is an application to call a waiter to the table at a restaurant. We will introduce Bootstrap and set up a basic User Account Control system that uses Bootstrap as the frontend.

Chapter 10, Template Inheritance and WTForms in Waiter Caller Project, introduces Jinja's template inheritance features so that we can add similar pages without duplicating code. We will use the WTForms library to make our web forms easier to build and validate.

Chapter 11, Using MongoDB with Our Waiter Caller Project, discusses how to install and configure MongoDB on our server and links it to our Waiter Caller project. We will finish off our final project by adding indices to our database and a favicon to our application.

Appendix, A Sneak Peek into the Future, outlines some important topics and technologies that we weren't able to cover in detail and gives pointers on where more can be learned about these.

What you need for this book

All the examples we will use assume that you use the Ubuntu operating system on your development machine and that you have access to a server that runs Ubuntu Server (we will discuss how to set the latter up in the first chapter). If you strongly prefer another operating system and already have a Python environment set up (including the Python package manger pip), then the examples will be easily translatable.

All other software and libraries used in the book are freely available, and we will demonstrate how to install and configure them in detail as the need arises.

Who this book is for

Have you looked at PHP and hated the clunky bloated syntax? Or, have you looked at .Net and wished that it was more open and flexible? Have you tried your hand at GUI libraries in Python and found them hard to use? If your answer to any one of these questions is 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 frontend.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

@app.route("/")
def get_news():
return "no news is good news"

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

import feedparserfrom flask import Flask
app = Flask(__name__)BBC_FEED = "http://feeds.bbci.co.uk/news/rss.xml"

Any command-line input or output is written as follows:

sudo apt-get update
sudo apt-get install git

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/FlaskByExample_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.