Preface

Flask stands out from other frameworks because it lets developers take the driver’s seat and have full creative control of their applications. Maybe you have heard the phrase “fighting the framework” before. This happens with most frameworks when you decide to solve a problem with a solution that isn’t the official one. It could be that you want to use a different database engine, or maybe a different method of authenticating users. Deviating from the path set by the framework’s developers will give you lots of headaches.

Flask is not like that. Do you like relational databases? Great. Flask supports them all. Maybe you prefer a NoSQL database? No problem at all. Flask works with them too. Want to use your own homegrown database engine? Don’t need a database at all? Still fine. With Flask you can choose the components of your application, or even write your own if that’s what you want. No questions asked!

The key to this freedom is that Flask was designed from the start to be extended. It comes with a robust core that includes the basic functionality that all web applications need and expects the rest to be provided by some of the many third-party extensions in the ecosystem—and, of course, by you.

In this book I present my workflow for developing web applications with Flask. I don’t claim this to be the only true way to build applications with this framework. You should take my choices as recommendations and not as gospel.

Most software development books provide small and focused code examples that demonstrate the different features of the target technology in isolation, leaving the “glue” code that is necessary to transform these different features into a fully working application to be figured out by the reader. I take a completely different approach. All the examples I present are part of a single application that starts out very simple and is expanded in each successive chapter. This application begins life with just a few lines of code and ends as a nicely featured blogging and social networking application.

Who This Book Is For

You should have some level of Python coding experience to make the most of this book. Although the book assumes no previous Flask knowledge, Python concepts such as packages, modules, functions, decorators, and object-oriented programming are assumed to be well understood. Some familiarity with exceptions and diagnosing issues from stack traces will be very useful.

While working through the examples in this book, you will spend a great deal of time in the command line. You should feel comfortable using the command line of your operating system.

Modern web applications cannot avoid the use of HTML, CSS, and JavaScript. The example application that is developed throughout the book obviously makes use of these, but the book itself does not go into a lot of detail regarding these technologies and how they are used. Some degree of familiarity with these languages is recommended if you intend to develop complete applications without the help of a developer versed in client-side techniques.

I released the companion application to this book as open source on GitHub. Although GitHub makes it possible to download applications as regular ZIP or TAR files, I strongly recommend that you install a Git client and familiarize yourself with source code version control (at least with the basic commands to clone and check out the different versions of the application directly from the repository). The short list of commands that you’ll need is shown in “How to Work with the Example Code”. You will want to use version control for your own projects as well, so use this book as an excuse to learn Git!

Finally, this book is not a complete and exhaustive reference on the Flask framework. Most features are covered, but you should complement this book with the official Flask documentation.

How This Book Is Organized

This book is divided into three parts.

Part I, Introduction to Flask, explores the basics of web application development with the Flask framework and some of its extensions:

  • Chapter 1 describes the installation and setup of the Flask framework.

  • Chapter 2 dives straight into Flask with a basic application.

  • Chapter 3 introduces the use of templates in Flask applications.

  • Chapter 4 introduces web forms.

  • Chapter 5 introduces databases.

  • Chapter 6 introduces email support.

  • Chapter 7 presents an application structure that is appropriate for medium and large applications.

Part II, Example: A Social Blogging Application, builds Flasky, the open source blogging and social networking application that I developed for this book:

Part III, The Last Mile, describes some important tasks not directly related to application coding that need to be considered before publishing an application:

  • Chapter 15 describes different unit testing strategies in detail.

  • Chapter 16 gives an overview of performance analysis techniques.

  • Chapter 17 describes deployment options for Flask applications, including traditional, cloud-based, and container-based solutions.

  • Chapter 18 lists additional resources.

How to Work with the Example Code

The code examples presented in this book are available for download at https://github.com/miguelgrinberg/flasky.

The commit history in this repository was carefully created to match the order in which concepts are presented in the book. The recommended way to work with the code is to check out the commits starting from the oldest, then move forward through the commit list as you make progress with the book. As an alternative, GitHub will also let you download each commit as a ZIP or TAR file.

If you decide to use Git to work with the source code, then you need to install the Git client, which you can download from http://git-scm.com. The following command downloads the example code using Git:

$ git clone https://github.com/miguelgrinberg/flasky.git

The git clone command installs the source code from GitHub into a flasky2 folder that is created in the current directory. This folder does not contain just source code; a copy of the Git repository with the entire history of changes made to the application is also included.

In the first chapter you will be asked to check out the initial release of the application, and then, at the proper places, you will be instructed to move forward in the history. The Git command that lets you move through the change history is git checkout. Here is an example:

$ git checkout 1a

The 1a referenced in the command is a tag: a named point in the commit history of the project. This repository is tagged according to the chapters of the book, so the 1a tag used in the example sets the application files to the initial version used in Chapter 1. Most chapters have more than one tag associated with them, so, for example, tags 5a, 5b, and so on are incremental versions presented in Chapter 5.

When you run a git checkout command as just shown, Git will display a warning message that informs you that you are in a “detached HEAD” state. This means that you are not in any specific code branch that can accept new commits, but instead are looking at a particular commit in the middle of the change history of the project. There is no reason to be alarmed by this message, but you should keep in mind that if you make modifications to any files while in this state, issuing another git checkout is going to fail, because Git will not know what to do with the changes you’ve made. So, to be able to continue working with the project you will need to revert the files that you changed back to their original state. The easiest way to do this is with the git reset command:

$ git reset --hard

This command will destroy any local changes you have made, so you should save anything you don’t want to lose before you use this command.

As well as checking out the source files for a version of the application, at certain points you will need to perform additional setup tasks. For example, in some cases you will need to install new Python packages, or apply updates to the database. You will be told when these are necessary.

From time to time, you may want to refresh your local repository from the one on GitHub, where bug fixes and improvements may have been applied. The commands that achieve this are:

$ git fetch --all
$ git fetch --tags
$ git reset --hard origin/master

The git fetch commands are used to update the commit history and the tags in your local repository from the remote one on GitHub, but none of this affects the actual source files, which are updated with the git reset command that follows. Once again, be aware that any time git reset is used you will lose any local changes you have made.

Another useful operation is to view all the differences between two versions of the application. This can be very useful to understand a change in detail. From the command line, the git diff command can do this. For example, to see the difference between revisions 2a and 2b, use:

$ git diff 2a 2b

The differences are shown as a patch, which is not a very intuitive format to review changes if you are not used to working with patch files. You may find that the graphical comparisons shown by GitHub are much easier to read. For example, the differences between revisions 2a and 2b can be viewed on GitHub at https://github.com/miguelgrinberg/flasky/compare/2a...2b.

Using Code Examples

This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Flask Web Development, 2nd Edition, by Miguel Grinberg (O’Reilly). Copyright 2018 Miguel Grinberg, 978-1-491-99173-2.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, email addresses, filenames, and file extensions.

Constant width

Used for command-line output and program listings, as well as within paragraphs to refer to commands and to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic or angle brackets (<>)

Indicates text that should be replaced with user-supplied values or by values determined by context.

Tip

This element signifies a tip or suggestion.

Note

This element signifies a general note.

Warning

This element indicates a warning or caution.

O’Reilly Safari

Note

Safari (formerly Safari Books Online) is a membership-based training and reference platform for enterprise, government, educators, and individuals.

Members have access to thousands of books, training videos, Learning Paths, interactive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and Course Technology, among others.

For more information, please visit http://oreilly.com/safari.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

  • O’Reilly Media, Inc.
  • 1005 Gravenstein Highway North
  • Sebastopol, CA 95472
  • 800-998-9938 (in the United States or Canada)
  • 707-829-0515 (international or local)
  • 707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/flask-web-dev2.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments

I could not have written this book alone. I have received a lot of help from family, co-workers, old friends, and new friends I’ve made along the way.

I’d like to thank Brendan Kohler for his detailed technical review and for his help in giving shape to the chapter on application programming interfaces. I’m also in debt to David Baumgold, Todd Brunhoff, Cecil Rock, and Matthew Hugues, who reviewed the manuscript at different stages of completion and gave me very useful advice regarding what to cover and how to organize the material.

Writing the code examples for this book was a considerable effort. I appreciate the help of Daniel Hofmann, who did a thorough code review of the application and pointed out several improvements. I’m also thankful to my teenage son, Dylan Grinberg, who suspended his Minecraft addiction for a few weekends and helped me test the code under several platforms.

O’Reilly has a wonderful program called Early Release that allows impatient readers to have access to books while they are being written. Some of my Early Release readers went the extra mile and engaged in useful conversations regarding their experience working through the book, leading to significant improvements. I’d like to acknowledge Sundeep Gupta, Dan Caron, Brian Wisti, and Cody Scott in particular for the contributions they’ve made to this book.

The staff at O’Reilly Media have always been there for me. Above all I’d like to recognize my wonderful editor, Meghan Blanchette, for her support, advice, and assistance from the very first day we met. Meg made the experience of writing my first book a memorable one.

To conclude, I would like to give a big thank you to the awesome Flask community.

Additional Thanks for the Second Edition

I’d like to thank Ally MacDonald, my editor for the second edition of this book, and also Susan Conant, Rachel Roumeliotis, and the whole team at O’Reilly Media for their continued support.

The technical reviewers for this edition did a wonderful job pointing out areas to improve and providing me with new perspectives. I’d like to recognize Lorena Mesa, Diane Chen, and Jesse Smith for their great contributions through their feedback and suggestions. I also greatly appreciate the help of my son, Dylan Grinberg, who painstakingly tested all the code examples.

Get Flask Web Development, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.