Flask-Web-Development.pdf - www.allitebooks.com www.allitebooks.com Flask Web Development Miguel Grinberg www.allitebooks.com Flask Web Development by

Flask-Web-Development.pdf - www.allitebooks.com...

This preview shows page 1 out of 258 pages.

Unformatted text preview: Flask Web Development Miguel Grinberg Flask Web Development by Miguel Grinberg Copyright © 2014 Miguel Grinberg. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles ( ). For more information, contact our corporate/ institutional sales department: 800-998-9938 or [email protected] Editors: Meghan Blanchette and Rachel Roumeliotis Production Editor: Nicole Shelby Copyeditor: Nancy Kotary Proofreader: Charles Roumeliotis May 2014: Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest First Edition Revision History for the First Edition: 2014-04-25: First release See for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Flask Web Development, the picture of a Pyrenean Mastiff, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-449-37262-0 [LSI] For Alicia. Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Part I. Introduction to Flask 1. Installation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Using Virtual Environments Installing Python Packages with pip 4 6 2. Basic Application Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Initialization Routes and View Functions Server Startup A Complete Application The Request-Response Cycle Application and Request Contexts Request Dispatching Request Hooks Responses Flask Extensions Command-Line Options with Flask-Script 7 8 9 9 12 12 14 14 15 16 17 3. Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 The Jinja2 Template Engine Rendering Templates Variables Control Structures Twitter Bootstrap Integration with Flask-Bootstrap Custom Error Pages Links 22 22 23 24 26 29 31 v Static Files Localization of Dates and Times with Flask-Moment 32 33 4. Web Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Cross-Site Request Forgery (CSRF) Protection Form Classes HTML Rendering of Forms Form Handling in View Functions Redirects and User Sessions Message Flashing 37 38 40 41 44 46 5. Databases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 SQL Databases NoSQL Databases SQL or NoSQL? Python Database Frameworks Database Management with Flask-SQLAlchemy Model Definition Relationships Database Operations Creating the Tables Inserting Rows Modifying Rows Deleting Rows Querying Rows Database Use in View Functions Integration with the Python Shell Database Migrations with Flask-Migrate Creating a Migration Repository Creating a Migration Script Upgrading the Database 49 50 51 51 52 54 56 57 58 58 60 60 60 62 63 64 64 65 66 6. Email. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Email Support with Flask-Mail Sending Email from the Python Shell Integrating Emails with the Application Sending Asynchronous Email 69 70 71 72 7. Large Application Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Project Structure Configuration Options Application Package vi | 75 76 78 Table of Contents Using an Application Factory Implementing Application Functionality in a Blueprint Launch Script Requirements File Unit Tests Database Setup Part II. 78 79 81 82 83 85 Example: A Social Blogging Application 8. User Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 Authentication Extensions for Flask Password Security Hashing Passwords with Werkzeug Creating an Authentication Blueprint User Authentication with Flask-Login Preparing the User Model for Logins Protecting Routes Adding a Login Form Signing Users In Signing Users Out Testing Logins New User Registration Adding a User Registration Form Registering New Users Account Confirmation Generating Confirmation Tokens with itsdangerous Sending Confirmation Emails Account Management 89 90 90 92 94 94 95 96 97 99 99 100 100 102 103 103 105 109 9. User Roles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Database Representation of Roles Role Assignment Role Verification 111 113 114 10. User Profiles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Profile Information User Profile Page Profile Editor User-Level Profile Editor Administrator-Level Profile Editor 119 120 122 122 124 Table of Contents | vii User Avatars 127 11. Blog Posts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Blog Post Submission and Display Blog Posts on Profile Pages Paginating Long Blog Post Lists Creating Fake Blog Post Data Rendering Data on Pages Adding a Pagination Widget Rich-Text Posts with Markdown and Flask-PageDown Using Flask-PageDown Handling Rich Text on the Server Permanent Links to Blog Posts Blog Post Editor 131 134 135 135 137 138 141 141 143 145 146 12. Followers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 Database Relationships Revisited Many-to-Many Relationships Self-Referential Relationships Advanced Many-to-Many Relationships Followers on the Profile Page Query Followed Posts Using a Database Join Show Followed Posts on the Home Page 149 150 151 152 155 158 160 13. User Comments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Database Representation of Comments Comment Submission and Display Comment Moderation 165 167 169 14. Application Programming Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175 Introduction to REST Resources Are Everything Request Methods Request and Response Bodies Versioning RESTful Web Services with Flask Creating an API Blueprint Error Handling User Authentication with Flask-HTTPAuth Token-Based Authentication Serializing Resources to and from JSON Implementing Resource Endpoints viii | Table of Contents 175 176 177 177 178 179 179 180 181 184 186 188 Pagination of Large Resource Collections Testing Web Services with HTTPie Part III. 191 192 The Last Mile 15. Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Obtaining Code Coverage Reports The Flask Test Client Testing Web Applications Testing Web Services End-to-End Testing with Selenium Is It Worth It? 197 200 200 204 205 209 16. Performance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 Logging Slow Database Performance Source Code Profiling 211 213 17. Deployment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 Deployment Workflow Logging of Errors During Production Cloud Deployment The Heroku Platform Preparing the Application Testing with Foreman Enabling Secure HTTP with Flask-SSLify Deploying with git push Reviewing Logs Deploying an Upgrade Traditional Hosting Server Setup Importing Environment Variables Setting Up Logging 215 216 217 218 218 222 223 225 226 227 227 227 228 228 18. Additional Resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 Using an Integrated Development Environment (IDE) Finding Flask Extensions Getting Involved with Flask 231 232 232 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235 Table of Contents | ix 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 is 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 to have 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 appli‐ cations 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. xi 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 as‐ sumed 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 ” on page xiii. 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. xii | Preface • 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: • Chapter 8 implements a user authentication system. • Chapter 9 implements user roles and permissions. • Chapter 10 implements user profile pages. • Chapter 11 creates the blogging interface. • Chapter 12 implements followers. • Chapter 13 implements user comments for blog posts. • Chapter 14 implements an Application Programming Interface (API). 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, both traditional and cloud based. • Chapter 18 lists additional resources. How to Work with the Example Code The code examples presented in this book are available from GitHub 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 . The following command downloads the example code using Git: $ git clone Preface | xiii The git clone command installs the source code from GitHub into a flasky 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 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. In addition to checking out the source files for a version of the application, you may need to perform some setup. For example, in some cases you will need to install addi‐ tional Python packages or apply updates to the database. You will be told when these are necessary. You will normally not modify the source files of the application, but if you do, then Git will not let you check out a different revision, as that would cause your local changes to be lost. Before you can check out a different revision, you will need to revert the files to their original state. The easiest way to do this is with the git reset command: $ git reset --hard This command will destroy your local changes, so you should save anything you don’t want to lose before you use this command. 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 xiv | Preface 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 berg/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 ex‐ ample 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 by Miguel Grinberg (O’Reilly). Copyright 2014 Miguel Grinberg, 978-1-449-3726-2.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at [email protected] 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 program listings, as well as within paragraphs to refer 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. Preface | xv Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a tip or suggestion. This element signifies a general note. This el...
View Full Document

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture