Mastering Flask Web Development Second Edition
Total Page:16
File Type:pdf, Size:1020Kb
Mastering Flask Web Development Second Edition Build enterprise-grade, scalable Python web applications Daniel Gaspar Jack Stouffer BIRMINGHAM - MUMBAI Mastering Flask Web Development Second Edition Copyright © 2018 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Commissioning Editor: Amarabha Banerjee Acquisition Editor: Devanshi Doshi Content Development Editor: Onkar Wani Technical Editor: Diksha Wakode Copy Editor: Safis Editing Project Coordinator: Sheejal Shah Proofreader: Safis Editing Indexer: Rekha Nair Graphics: Alishon Mendonsa Production Coordinator: Aparna Bhagat First published: September 2015 Second Edition: October 2018 Production reference: 1301018 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78899-540-5 www.packtpub.com mapt.io Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Mapt is fully searchable Copy and paste, print, and bookmark content Packt.com Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. Contributors About the authors Daniel Gaspar is a programmer and DevOps engineer with more than 20 years' experience. He has worked in a wide range of sectors, including government and finance. He is currently working at Miniclip (the global leader in digital games). He uses a wide range of tools in his daily work, but Flask caught his attention because of its excellently designed API and simplicity. Daniel is an OSS and Python enthusiast, and has developed a widely used extension/framework named Flask-AppBuilder, used by Airbnb on Superset and AirFlow. First, I would like to thank my wife, Susana, and my beautiful children, Mariana and Pedro, for their amazing support, enthusiasm, and patience. Also, a big thank you to everyone at Packt Publishing, especially to Onkar Wani, with whom it was a pleasure to work. Jack Stouffer is a programmer who has several years of experience in designing web applications. He switched to Flask two 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, it became one of the most popular Flask repositories on the site. Jack has also worked as a reviewer for Flask Framework Cookbook, Packt. About the reviewer Damyan Bogoev is based in Bulgaria, where he currently works at Gtmhub as a software engineer. Prior to Gtmhub, Damyan worked at Telerik. His background is in developing backend server applications and tools for infrastructure automation, management, and monitoring. Damyan is also technical reviewer for the Web API Development with Flask video course. Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Table of Contents Preface 1 Chapter 1: Getting Started 6 Version control with Git 7 Installing Git 7 Git on Windows 7 Git basics 7 Git branches and flow 11 Python package management with pip 15 Installing the Python package manager on Windows 15 Installing pip Python package manager on macOS X and Linux 16 Pip basics 17 Dependency sandboxing with virtualenv 18 Virtualenv basics 19 Setting up Docker 19 The beginning of our project 20 Simple application 21 Project structure 22 Using Flask's command-line interface 22 Summary 23 Chapter 2: Creating Models with SQLAlchemy 24 Setting up SQLAlchemy 25 Python packages 25 Flask SQLAlchemy 26 Our first model 26 Creating the user table 29 CRUD 30 Creating models 30 Reading models 30 Filtering queries 32 Updating models 34 Deleting models 34 Relationships between models 34 One-to-many relationship 35 Many-to-many relationship 38 Constraints and indexing 40 The convenience of SQLAlchemy sessions 42 Database migrations with Alembic 43 Summary 46 Table of Contents Chapter 3: Creating Views with Templates 47 Jinja's syntax 47 Filters 48 The default filter 49 The escape filter 49 The float filter 49 The int filter 49 The join filter 50 The length filter 50 The round filter 50 The safe filter 51 The title filter 51 The tojson filter 51 The truncate filter 52 Custom filters 52 Comments 53 Using if statements 53 Loops 53 Macros 55 Flask-specific variables and functions 55 The config object 56 The request object 56 The session object 56 The url_for() function 56 The get_flashed_messages() function 57 Creating our views 58 The view function 58 Writing the templates and inheritance 60 The base template 61 The child templates 64 Writing the other templates 67 Flask WTForms 68 WTForms basics 69 Custom validations 70 Posting comments 71 Summary 74 Chapter 4: Creating Controllers with Blueprints 75 Sessions and globals 75 Request setup and teardown 76 Error pages 77 Class-based views 78 Method class views 81 Blueprints 81 Summary 84 Chapter 5: Advanced Application Structure 85 [ ii ] Table of Contents Modular application 85 Refactoring the code 87 Application factories 89 Summary 91 Chapter 6: Securing Your App 92 Authentication methods 93 Basic authentication 93 Remote-user authentication 94 LDAP authentication 95 Database user model authentication 97 OpenID and OAuth 97 Flask-Login overview 100 Setting up 101 Updating the models 103 Creating the forms 106 Protecting your form from spam 107 Creating views 109 OpenID 114 OAuth 117 Role-based access control (RBAC) 119 Summary 122 Chapter 7: Using NoSQL with Flask 123 Types of NoSQL database 124 Key-value stores 124 Document stores 125 Column family stores 125 Graph databases 128 RDBMS versus NoSQL 129 The strengths of RDBMS databases 129 Data integrity 130 Speed and scale 130 Tools 131 The strengths of NoSQL databases 131 CAP theorem 132 What database to use and when 135 MongoDB in Flask 136 Installing MongoDB 136 Setting up MongoEngine 137 Defining documents 138 Field types 139 Types of documents 141 The meta attribute 141 CRUD 143 Create 143 [ iii ] Table of Contents Write safety 144 Read 144 Filtering 146 Update 147 Delete 148 Relationships in NoSQL 148 One-to-many relationships 149 Many-to-many relationships 150 Leveraging the power of NoSQL 151 Summary 156 Chapter 8: Building RESTful APIs 157 What is REST? 157 HTTP 158 REST definition and best practices 160 Setting up a RESTful Flask API 164 JWT authentication 167 Get requests 170 Output formatting 170 Request arguments 173 Post requests 176 Put requests 178 Delete requests 180 Summary 180 Chapter 9: Creating Asynchronous Tasks with Celery 181 What is Celery? 182 Setting up Celery and RabbitMQ 183 Creating tasks in Celery 185 Running Celery tasks 189 Celery workflows 190 Partials 191 Callbacks 191 Group 192 Chain 192 Chord 193 Running tasks periodically 193 Monitoring Celery 195 Web-based monitoring with Flower 196 Creating a reminder app 198 Creating a weekly digest 199 Summary 202 Chapter 10: Useful Flask Extensions 203 Flask CLI 203 Flask Debug Toolbar 206 [ iv ] Table of Contents Flask Caching 208 Caching views and functions 209 Caching functions with parameters 210 Caching routes with query strings 211 Using Redis as a cache backend 212 Using memcached as a cache backend 213 Flask Assets 214 Flask Admin 216 Creating basic admin pages 218 Creating database admin pages 220 Enhancing administration for the post page 221 Creating file system admin pages 224 Securing Flask Admin 224 Flask-Babel 225 Flask Mail 229 Summary 230 Chapter 11: Building Your Own Extension 231 Creating a YouTube Flask extension 231 Creating a Python package 234 Creating