Flask Framework Cookbook
5/5
()
About this ebook
Flask Framework Cookbook takes you through a number of recipes that will help you understand the power of Flask and its extensions. You will start by seeing the different ways of configurations that a Flask application can make use of. You will learn how to work with templates and learn about the ORM and view layers. You will see how to write an admin interface followed by the debugging and logging of errors. Finally, you will learn about different deployment and post-deployment techniques on platforms such as Apache, Tornado, and Heroku.
By the end of this book, you will have gained all the knowledge required to write Flask applications in the best possible way, and scale them with best practices.
Related to Flask Framework Cookbook
Related ebooks
Modern Python Cookbook Rating: 5 out of 5 stars5/5Web Development with Django Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsPython GUI Programming Cookbook Rating: 5 out of 5 stars5/5MongoDB Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsNode Cookbook: Second Edition Rating: 3 out of 5 stars3/5Python Parallel Programming Cookbook Rating: 5 out of 5 stars5/5JavaScript JSON Cookbook Rating: 0 out of 5 stars0 ratingsLaravel 5.x Cookbook Rating: 0 out of 5 stars0 ratingsNumPy Cookbook Rating: 5 out of 5 stars5/5Elixir Cookbook Rating: 0 out of 5 stars0 ratingsLearning Flask Framework Rating: 4 out of 5 stars4/5Flask By Example Rating: 0 out of 5 stars0 ratingsBuilding Web Applications with Flask Rating: 0 out of 5 stars0 ratingsFlask Blueprints Rating: 0 out of 5 stars0 ratingsDjango Design Patterns and Best Practices Rating: 5 out of 5 stars5/5Mastering Python Design Patterns Rating: 0 out of 5 stars0 ratingsFunctional Python Programming Rating: 0 out of 5 stars0 ratingsBuilding RESTful Python Web Services Rating: 4 out of 5 stars4/5Git Best Practices Guide Rating: 0 out of 5 stars0 ratingsDesigning Microservices using Django: Structuring, Deploying and Managing the Microservices Architecture with Django Rating: 0 out of 5 stars0 ratingsDjango Project Blueprints Rating: 0 out of 5 stars0 ratingsDeveloping with Docker Rating: 5 out of 5 stars5/5ReactJS by Example - Building Modern Web Applications with React Rating: 4 out of 5 stars4/5Modular Programming with Python Rating: 0 out of 5 stars0 ratingsMastering Objectoriented Python Rating: 5 out of 5 stars5/5RESTful Web API Design with Node.js - Second Edition Rating: 1 out of 5 stars1/5Mastering Python Regular Expressions Rating: 5 out of 5 stars5/5Learning JavaScript Data Structures and Algorithms - Second Edition Rating: 0 out of 5 stars0 ratings
Programming For You
SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Spies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsC Programming For Beginners: The Simple Guide to Learning C Programming Language Fast! Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Automate the Boring Stuff with Python, 2nd Edition: Practical Programming for Total Beginners Rating: 4 out of 5 stars4/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5C All-in-One Desk Reference For Dummies Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsJavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5
Reviews for Flask Framework Cookbook
1 rating0 reviews
Book preview
Flask Framework Cookbook - Shalabh Aggarwal
Table of Contents
Flask Framework Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Flask Configurations
Introduction
Environment setup with virtualenv
How to do it…
How it works…
There's more…
See also
Handling basic configurations
Getting ready
How to do it…
How it works…
Class-based settings
How to do it…
How it works…
Organization of static files
How to do it…
How it works…
There's more…
Being deployment specific with instance folders
How to do it…
How it works…
Composition of views and models
How to do it…
How it works…
See also
Creating a modular web app with blueprints
Getting ready
How to do it…
How it works…
See also
Making a Flask app installable using setuptools
How to do it…
How it works…
See also
2. Templating with Jinja2
Introduction
Bootstrap layout
Getting ready
How to do it…
How it works…
See also
Block composition and layout inheritance
Getting ready
How to do it…
How it works…
See also
Creating a custom context processor
How to do it…
See also
Creating a custom Jinja2 filter
How to do it…
How it works…
See also
Creating a custom macro for forms
Getting ready
How to do it…
Advanced date and time formatting
Getting ready
How to do it…
See more
3. Data Modeling in Flask
Introduction
Creating a SQLAlchemy DB instance
Getting ready
How to do it…
There's more…
See also
Creating a basic product model
How to do it…
How it works…
See also
Creating a relational category model
How to do it…
See also
Database migration using Alembic and Flask-Migrate
Getting ready
How to do it…
How it works…
See also
Model data indexing with Redis
Getting ready
How to do it…
How it works…
Opting the NoSQL way with MongoDB
Getting ready
How to do it…
See also
4. Working with Views
Introduction
Writing function-based views and URL routes
Getting ready
How to do it…
A simple GET request
A simple POST request
A simple GET/POST request
How it works…
There's more…
Class-based views
Getting ready
How to do it…
How it works…
There's more…
See also
URL routing and product-based pagination
Getting ready
How to do it…
Adding pagination to applications
See also
Rendering to templates
Getting ready
How to do it…
How it works…
See also
Dealing with XHR requests
Getting ready
How to do it…
How it works…
Decorator to handle requests beautifully
Getting ready
How to do it…
See also
Creating custom 404 and 500 handlers
Getting ready
How to do it…
How it works…
There's more…
Flashing messages for better user feedback
Getting ready
How to do it…
How it works…
SQL-based searching
Getting ready
How to do it…
How it works…
5. Webforms with WTForms
Introduction
SQLAlchemy model data as form representation
Getting ready
How to do it…
How it works…
See also
Validating fields on the server side
How to do it…
How it works…
There's more…
See also
Creating a common forms set
How to do it…
How it works…
Creating custom fields and validation
How to do it…
How it works…
There's more…
Creating a custom widget
How to do it…
How it works…
See also
Uploading files via forms
How to do it…
How it works…
Cross-site Request Forgery protection
How to do it…
How it works…
6. Authenticating in Flask
Introduction
Simple session-based authentication
Getting ready
How to do it…
How it works…
See also
Authenticating using the Flask-Login extension
Getting ready
How to do it…
How it works…
There's more…
See also
Using OpenID for authentication
Getting ready
How to do it…
How it works…
Using Facebook for authentication
Getting started
How to do it…
How it works...
Using Google for authentication
Getting ready
How to do it…
How it works…
Using Twitter for authentication
Getting ready
How to do it…
How it works…
7. RESTful API Building
Introduction
Creating a class-based REST interface
Getting ready
How to do it…
How it works…
There's more…
Creating an extension-based REST interface
Getting ready
How to do it…
How it works…
There's more…
Creating a SQLAlchemy-independent REST API
Getting ready
How to do it…
How it works…
See also
A complete REST API example
Getting ready
How to do it…
See also
8. Admin Interface for Flask Apps
Introduction
Creating a simple CRUD interface
Getting ready
How to do it…
How it works…
Using the Flask-Admin extension
Getting ready
How to do it…
There's more…
Registering models with Flask-Admin
Getting ready
How to do it…
Creating custom forms and actions
Getting ready
How to do it…
How it works…
WYSIWYG for textarea integration
Getting ready
How to do it…
How it works…
See also
Creating user roles
Getting ready
How to do it…
How it works…
9. Internationalization and Localization
Introduction
Adding a new language
Getting ready
How to do it…
How it works…
There's more…
See also
Lazy evaluation and the gettext/ngettext functions
Getting ready
How to do it…
Global language-switching action
Getting ready
How to do it…
How it works…
See also
10. Debugging, Error Handling, and Testing
Introduction
Setting up basic file logging
Getting ready
How to do it…
How it works…
There's more…
See also
Sending e-mails on the occurrence of errors
Getting ready
How to do it…
How it works…
There's more…
Using Sentry to monitor exceptions
Getting ready
How to do it…
How it works…
Debugging with pdb
Getting ready
How to do it…
See also
Creating our first simple test
Getting ready
How to do it…
How it works…
See also
Writing more tests for views and logic
Getting ready
How to do it…
How it works…
Nose library integration
Getting ready
How to do it…
See also
Using mocking to avoid real API access
Getting ready
How to do it…
How it works…
See also
Determining test coverage
Getting ready
How to do it…
How it works…
See also
Using profiling to find bottlenecks
Getting ready
How to do it…
How it works…
11. Deployment and Post Deployment
Introduction
Deploying with Apache
Getting ready
How to do it…
How it works…
There's more…
See also
Deploying with uWSGI and Nginx
Getting ready
How to do it…
See also
Deploying with Gunicorn and Supervisor
Getting ready
How to do it…
How it works…
See also
Deploying with Tornado
Getting ready
How to do it…
How it works…
Using Fabric for deployment
Getting ready
How to do it…
How it works…
There's more…
S3 storage for file uploads
Getting ready
How to do it…
How it works…
See also
Deploying with Heroku
Getting ready
How to do it…
How it works…
There's more…
Deploying with AWS Elastic Beanstalk
Getting ready
How to do it…
How it works…
Application monitoring with Pingdom
Getting ready
How to do it…
How it works…
Application performance management and monitoring with New Relic
Getting ready
How to do it…
How it works…
See also
12. Other Tips and Tricks
Introduction
Full-text search with Whoosh
Getting ready
How to do it…
How it works…
See also
Full-text search with Elasticsearch
Getting ready
How to do it…
How to do it…
Working with signals
Getting ready
How to do it…
How it works…
See also
Using caching with your application
Getting ready
How to do it…
How it works…
There's more…
See also
E-mail support for Flask applications
Getting ready
How to do it…
How it works…
There's more…
See also
Understanding asynchronous operations
Getting ready
How to do it…
How it works…
Working with Celery
Getting ready
How to do it…
How it works…
See also
Index
Flask Framework Cookbook
Flask Framework Cookbook
Copyright © 2014 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: November 2014
Production reference: 1151114
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-340-7
www.packtpub.com
Cover image by Pratyush Mohanta (<[email protected]>)
Credits
Author
Shalabh Aggarwal
Reviewers
Matt Copperwaite
Christoph Heer
Jack Stouffer
Commissioning Editor
Ashwin Nair
Acquisition Editor
Subho Gupta
Content Development Editor
Amey Varangaonkar
Technical Editor
Taabish Khan
Copy Editor
Karuna Narayanan
Project Coordinator
Leena Purkait
Proofreaders
Simran Bhogal
Paul Hindle
Maria Gould
Ameesha Green
Indexer
Mariammal Chettiyar
Production Coordinator
Arvindkumar Gupta
Cover Work
Arvindkumar Gupta
About the Author
Shalabh Aggarwal has several years of experience in developing business systems and web applications for small-to-medium scale industries. He started his career working on Python, and although he works on multiple technologies, he remains a Python developer at heart. He is passionate about open source technologies and writes highly readable and quality code. He is a major contributor to some very popular open source applications. He has worked with Openlabs Technologies and Consulting (P) Limited as the CTO for a large part of his career. He is also active in voluntary training for engineering students on nonconventional and open source topics.
When not working with full-time assignments, he consults for start-ups on leveraging different technologies. When not writing code, he writes non-technical literature and makes music with his guitar.
I would like to dedicate this book to my late father who will always be there in my thoughts for the love and encouragement he gave me to explore new things in life. I would like to thank my family, my mother and my sister, for putting up with me during my long writing and research sessions. I would also like to thank my friends and colleagues who encouraged me and kept the momentum going. I would like to convey deep gratitude to my mentor, Sharoon Thomas, who introduced me to these technologies and helped me learn a lot. Without the support of all of them, I would have never been able to learn these technologies and complete this book.
About the Reviewers
Matt Copperwaite graduated in Computer Systems and Networks with a BSc Hons degree from University of Plymouth in 2008 and has since worked in the private and public sectors in the UK. He is currently a Python software developer and DevOps engineer for the UK government, mostly working in Django. However, his first love is Flask, using which he has built several products, all under the GPL license.
Matt is also a trustee of South London Makerspace, a hackerspace-like community in south London. He is a co-host of The Dick Turpin Road Show, a podcast about free and open source software, and the LUG Master
of the Greater London Linux User Group.
I would like to thank my fiancée, Marie, who has put up with my crazy ideas and always makes me laugh, and my parents, who afforded me all the opportunities to get into computing and for their unconditional love.
Christoph Heer is a passionate Python developer based in Germany. He likes to develop web applications and also tools and systems for infrastructure optimization, management, and monitoring. He is proud to be part of the great Python community and wishes to have more time for open source contribution.
Currently, Christoph is studying Computer Science in Karlsruhe in cooperation with his current employer, SAP, and is going to finish his degree in the fall of 2015.
I would like to thank Armin Ronacher for his work for the Python community, especially for Flask and his inspiring API designs and well-written documentation.
Jack Stouffer is a web programmer from the Metro Detroit area. He works for Apollo America. At Apollo, he creates various web applications using Python, Flask, and Backbone.js, which manage everything from KPI tracking and display to controlling manufacturing. He is currently attending college at Oakland University in Rochester, Michigan.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.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.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.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.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Preface
Flask is a lightweight web application microframework written in Python. It makes use of the flexibility of Python to provide a relatively simple template for web application development. Flask makes it possible to write simple one-page applications, but it also has the power to scale them and build larger applications without any issues.
Flask has excellent documentation and an active community. It has a number of extensions, each of which have documentation that can be rated from good to excellent. There are a few books also available on Flask; they are great and provide a lot of insight into the framework and its applications. This book tries to take a different approach to explain the Flask framework and multiple aspects of its practical uses and applications as a whole.
This book takes you through a number of recipes that will help you understand the power of Flask and its extensions. You will start by seeing the different configurations that a Flask application can make use of. From here, you will learn how to work with templates, before learning about the ORM and view layers, which act as the foundation of web applications. Then, you will learn how to write RESTful APIs with Flask, after learning various authentication techniques. As you move ahead, you will learn how to write an admin interface followed by the debugging and logging of errors in Flask. You will also learn how to make your applications multilingual and gain an insight into the various testing techniques. Finally, you will learn about the different deployment and post-deployment techniques on platforms such as Apache, Tornado, Heroku, and AWS Elastic Beanstalk.
By the end of this book, you will have all the necessary information required to make the best use of this incredible microframework to write small and big applications and scale them with industry-standard practices.
A good amount of research coupled with years of experience has been used to develop this book, and I really wish that this book will benefit fellow developers.
What this book covers
Chapter 1, Flask Configurations, helps in understanding the different ways in which Flask can be configured to suit various needs as per the demands of the project. It starts by telling us how to set up our development environment and moves on to the various configuration techniques.
Chapter 2, Templating with Jinja2, covers the basics of Jinja2 templating from the perspective of Flask and explains how to make applications with modular and extensible templates.
Chapter 3, Data Modeling in Flask, deals with one of the most important part of any application, that is, its interaction with the database systems. We will see how Flask can connect to database systems, define models, and query the databases for the retrieval and feeding of data.
Chapter 4, Working with Views, talks about how to interact with web requests and the proper responses to be catered for these requests. It covers various methods of handling the requests properly and designing them in the best way.
Chapter 5, Webforms with WTForms, covers form handling, which is an important part of any web application. As much as the forms are important, their validation holds equal importance, if not more. Presenting this information to the users in an interactive fashion adds a lot of value to the application.
Chapter 6, Authenticating in Flask, deals with authentication, which sometimes acts as a thin red line between the application being secure and insecure. This chapter deals with social logins in detail.
Chapter 7, RESTful API Building, helps in understanding REST as a protocol and then talks about writing RESTful APIs for Flask applications.
Chapter 8, Admin Interface for Flask Apps, focuses on writing admin views for Flask applications. First, we will write completely custom-made views and then write them with the help of an extension.
Chapter 9, Internationalization and Localization, expands the scope of Flask applications and covers the basics of how to enable support for multiple languages.
Chapter 10, Debugging, Error Handling, and