Learning Flask Framework - Matt Copperwaite - E-Book

Learning Flask Framework E-Book

Matt Copperwaite

0,0
35,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Flask is a small and powerful web development framework for Python. It does not presume or force a developer to use a particular tool or library. Flask supports extensions that can add application features as if they were implemented in Flask itself. Flask’s main task is to build web applications quickly and with less code. With its lightweight and efficient web development framework, Flask combines rapid development and clean, simple design.
This book will take you through the basics of learning how to apply your knowledge of Python to the web.
Starting with the creation of a “Hello world” Flask app, you will be introduced to the most common Flask APIs and Flask’s interactive debugger. You will learn how to store and retrieve blog posts from a relational database using an ORM and also to map URLs to views. Furthermore, you will walk through template blocks, inheritance, file uploads, and static assets.
You will learn to authenticate users, build log in/log out functionality, and add an administrative dashboard for the blog. Moving on, you will discover how to make Ajax requests from the template and see how the Mock library can simplify testing complex interactions.
Finally, you will learn to deploy Flask applications securely and in an automated, repeatable manner, and explore some of the most popular Flask resources on the web.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 275

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Flask Framework
Credits
About the Authors
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. Creating Your First Flask Application
What is Flask?
With great freedom comes great responsibility
Setting up a development environment
Supporting Python 3
Installing Python packages
Installing pip
Installing virtualenv
Why use virtualenv?
Installing virtualenv with pip
Creating your first Flask app
Installing Flask in your virtualenv
Hello, Flask!
Understanding the code
Routes and requests
Reading values from the request
Debugging Flask applications
Introducing the blog project
The spec
Creating the blog project
A barebones Flask app
Zooming out
The import flow
Summary
2. Relational Databases with SQLAlchemy
Why use a relational database?
Introducing SQLAlchemy
Installing SQLAlchemy
Using SQLAlchemy in our Flask app
Choosing a database engine
Connecting to the database
Creating the Entry model
Creating the Entry table
Working with the Entry model
Making changes to an existing entry
Deleting an entry
Retrieving blog entries
Filtering the list of entries
Special lookups
Combining expressions
Negation
Operator precedence
Building a tagging system
Adding and removing tags from entries
Using backrefs
Making changes to the schema
Adding Flask-Migrate to our project
Creating the initial migration
Adding a status column
Summary
3. Templates and Views
Introducing Jinja2
Basic template operations
Loops, control structures, and template programming
Jinja2 built-in filters
Creating a base template for the blog
Creating a URL scheme
Defining the URL routes
Building the index view
Building the detail view
Listing entries matching a given tag
Listing all the tags
Full-text search
Adding pagination links
Enhancing the blog app
Summary
4. Forms and Validation
Getting started with WTForms
Defining a form for the Entry model
A form with a view
The create.html template
Handling form submissions
Validating input and displaying error messages
Editing existing entries
The edit.html template
Deleting entries
Cleaning up
Using flash messages
Displaying flash messages in the template
Saving and modifying tags on posts
Image uploads
Processing file uploads
The image upload template
Serving static files
Summary
5. Authenticating Users
Creating a user model
Installing Flask-Login
Implementing the Flask-Login interface
Creating user objects
Login and logout views
The login template
Logging out
Accessing the current user
Restricting access to views
Storing an entry's author
Setting the author on blog entries
Protecting the edit and delete views
Displaying a user's drafts
Sessions
Summary
6. Building an Administrative Dashboard
Installing Flask-Admin
Adding Flask-Admin to our app
Exposing models through the Admin
Customizing the list views
Adding search and filtering to the list view
Customizing Admin model forms
Enhancing the User form
Generating slugs
Managing static assets via the Admin
Securing the admin website
Creating an authentication and authorization mixin
Setting up a custom index page
Flask-Admin templates
Reading more
Summary
7. AJAX and RESTful APIs
Creating a comment model
Creating a schema migration
Installing Flask-Restless
Setting up Flask-Restless
Making API requests
Creating comments using AJAX
AJAX form submissions
Validating data in the API
Preprocessors and postprocessors
Loading comments using AJAX
Retrieving the list of comments
Reading more
Summary
8. Testing Flask Apps
Unit testing
Python's unit test module
A simple math test
Flask and unit testing
Testing a page
Testing an API
Test-friendly configuration
Mocking objects
Logging and error reporting
Logging
Logging to file
Custom log messages
Levels
Error reporting
Read more
Summary
9. Excellent Extensions
SeaSurf and CSRF protection of forms
Creating Atom feeds
Syntax highlighting using Pygments
Simple editing with Markdown
Caching with Flask-Cache and Redis
Creating secure, stable versions of your site by creating static content
Commenting on a static site
Synchronizing multiple editors
Asynchronous tasks with Celery
Creating command line instructions with Flask-script
References
Summary
10. Deploying Your Application
Running Flask with a WSGI server
Apache's httpd
Serving static files
Nginx
Serving static files
Gunicorn
Securing your site with SSL
Getting your certificate
Apache httpd
Nginx
Gunicorn
Automating deployment using Ansible
Read more
Summary
Index

Learning Flask Framework

Learning Flask Framework

Copyright © 2015 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 authors, 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 2015

Production reference: 1241115

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78398-336-0

www.packtpub.com

Credits

Authors

Matt Copperwaite

Charles Leifer

Reviewers

Abhishek Gahlot

Burhan Khalid

Commissioning Editor

Ashwin Nair

Acquisition Editor

Subho Gupta

Content Development Editor

Mamata Walkar

Technical Editors

Siddhesh Ghadi

Siddhesh Patil

Copy Editor

Sonia Mathur

Project Coordinator

Shipra Chawhan

Proofreaders

Stephen Copestake

Safis Editing

Indexer

Mariammal Chettiyar

Production Coordinator

Conidon Miranda

Cover Work

Conidon Miranda

About the Authors

Matt Copperwaite graduated from the University of Plymouth in 2008 with a bachelor of science (Hons) degree in computer systems and networks. Since then, he has worked in various private and public sectors in the UK. Matt is currently working as a Python software developer and DevOps engineer for the UK Government, focusing mainly on Django. However, his first love is Flask, with which he has built several products under the General Public License (GPL).

Matt is also a trustee of South London Makerspace, a hackerspace community in South London; a cohost of The Dick Turpin Road Show, a podcast for free and open source software; and LUG Master of Greater London Linux User Group.

He has also been the technical reviewer of the Flask Framework Cookbook.

I would like to thank my new wife Marie who has been so patient throughout the production of this book.

Charles Leifer is a professional software engineer with 6 years of experience using Python. He is the author of several popular open source libraries, including Peewee ORM and Huey, a multithreaded task queue. He is also the cocreator of https://readthedocs.org, a free documentation hosting platform.

Charles developed a passion for Python while working at the Journal World. His colleagues there patiently answered his endless questions and taught him everything about the Web, Linux, open source, and how to write clean Python.

Charles maintains an active programming blog at http://charlesleifer.com.

I would like to thank my wife, Leslie, and my parents, Anne and John, for their encouragement and support.

About the Reviewers

Abhishek Gahlot is a Computer Engineer and holds a Bachelors degree in Computer Science. He loves programming in Python and Go.

He created two Web Applications Cloudtub (cloudtub.com) and Dynofy (dynofy.com). Dynofy uses the Flask framework for Web and REST API. Abhishek is very passionate about Algorithms, Artificial Intelligence and Parallel Programming.

He occasionally writes articles related to Web Engineering at blog.abhishek.it. Abhishek can be reached at <[email protected]>.

Burhan Khalid has always been tinkering with technology from his early days of XT to writing JCL on the ISPF editor, C and C++, Java, Pascal, and COBOL, to his latest favorite, Python. As a lover of technology, he is most comfortable experimenting with the next big technology stack.

By day, he works at a multinational bank in the alternative channels unit, where he gets to hack, develop, and test applications that help execute transactions across all sectors of electronic devices and channels. In addition to his work, he also contributes to open source projects. Burhan has also released a few toolkits for transaction processing.

He is an avid volunteer and has mentored Sirdab Lab (a start-up accelerator). Burhan is a frequent speaker at the local Google Developer Groups, a presenter and volunteer at StartupQ8, a start-up community. He is also actively involved with StackOverflow.

In his free time, you can find him splitting time nurturing his other passions—flight, by scheduling time in flight simulators, and photography, by uploading images to his Flickr feed.

I would like to thank my mother and father for always encouraging me; my wife for putting up with my long days at the keyboard and my ever - growing gadget collection; and my friends and colleagues for providing me with new challenges to sharpen my skills.

Special thanks to Lalith Polepeddi for contributing to the book at a stage where we needed it the most.

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 <[email protected]> for more details.

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.

https://www2.packtpub.com/books/subscription/packtlib

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 PacktCopy and paste, print, and bookmark contentOn 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

Welcome to Learning Flask, the book that will teach you the necessary skills to build web applications with Flask, a lightweight Python web framework. This book takes an example-driven approach that is designed to get you started quickly. The practical examples are balanced with just the right amount of background information to ensure that you understand not only the how, but also the why of Flask development.

Flask was originally released by Armin Ronacher as part of an elaborate April Fool's Day prank in 2010. The project touted itself as, "The next generation python micro web-framework," and lampooned features made popular by similar microframeworks. Although Flask was intended as a prank, the authors were caught by surprise when many people expressed serious interest in the project.

Flask is a microframework that is built on top of two excellent libraries: the Jinja2 templating engine, and the Werkzeug WSGI toolkit. Despite being a relative new-comer compared to other frameworks, such as Django, and Pylons, Flask has garnered a large and loyal following. Flask provides powerful tools for common web development tasks and encourages a bring-your-own-library approach for everything else, allowing programmers the flexibility to pick and choose the best components for their application. Every Flask app is different, and as the project's documentation states, "Flask is Fun".

The Flask microframework represents a departure in terms of design and API from most other popular Python web frameworks, which has led many developers that are new to Flask to ask, "What is the right way to build an app?" Flask does not offer any strong opinions on how we, the developers, should build our app. Instead, it provides opinions on what you need to build an app. Flask can be thought of as a collection of objects and functions to deal with common web tasks, such as routing URLs to code, processing request data, and rendering templates. While the level of flexibility that Flask provides is liberating, it can also lead to confusion and poor designs.

The purpose of this book is to help you see this flexibility as opportunity. Over the course of this book, we will be building and progressively enhancing a Flask-powered blogging site. New concepts will be introduced through the addition of new features to the site. By the end of the book, we will have created a fully-featured website, and you will have a strong working knowledge of Flask and the ecosystem of its commonly-used extensions and libraries.

What this book covers

Chapter 1, Creating Your First Flask Application, begins with the bold declaration, "Flask is fun", which is one of the first things that you see when you view the official Flask documentation, and in this chapter, you will get to grips with why so many Python developers agree.

Chapter 2, Relational Databases with SQLAlchemy, says that relational databases are the bedrock upon which almost all modern web applications are built. We will use SQLAlchemy, a powerful object-relational mapper that allows us to abstract away the complexities of multiple database engines. In this chapter, you will learn about how the data model that you choose early on will affect almost every facet of the code that follows.

Chapter 3, Templates and Views, covers two of the most recognizable components of the framework: the Jinja2 template language, and the URL routing framework. We will fully immerse ourselves in Flask and see our app finally start to take shape. As we progress through the chapter, our app will start looking like a proper website.

Chapter 4, Forms and Validation, shows you how to use forms to modify content on your blog directly through the site handled by the popular WTForms library. This is a fun chapter because we will add all sorts of new ways to interact with our site. We will create forms to work with our data models and learn how to receive and validate user data.

Chapter 5, Authenticating Users, explains how you can add user authentication to your site. Being able to distinguish one user from another allows us to develop an entirely new class of features. For instance, we will see how to restrict access to the create, edit, and delete views, preventing anonymous users from tampering with site content. We can also display a user's draft posts to them but hide them from everyone else.

Chapter 6, Building an Administrative Dashboard, shows you how you can build an administrative dashboard for your site, using the excellent Flask-Admin. Our admin dashboard will give certain selected users the ability to manage all the content across the entire site. In essence, the admin site will be a graphical frontend for the database, supporting operations to create, edit, and delete rows in our application's tables.

Chapter 7, AJAX and RESTful APIs, uses Flask-Restless to create a RESTful API for the blogging app. A RESTful API is a powerful way of accessing your app programmatically by providing highly-structured data to represent it. Flask-Restless works very well with our SQLAlchemy models, and it also handles complex tasks, such as serialization, and result filtering.

Chapter 8, Testing Flask Apps, covers how you can write unit tests covering all parts of the blogging app. We will utilize Flask's test client to simulate "live" requests. We will also see how the Mock library can simplify testing complex interactions, such as calling third-party services, such as databases.

Chapter 9, Excellent Extensions, teaches you how to enhance your Flask installation with popular third-party extensions. We used extensions throughout the book, but we can now explore the added extra security or functionality with very little effort and can polish off your app nicely.

Chapter 10, Deploying Your Application, teaches you how to deploy your Flask applications securely and in an automated, repeatable manner. We will look at how to configure the commonly-used WSGI capable servers, such as Apache and Nginx, as well as the Python web server Gunicorn, to give you plenty of options. Then, we will see how to secure part or the entire site using SSL before finally wrapping up our application in a configuration management tool to automate our deployment.

What you need for this book

While Python is at home on most operating systems, and we have tried to keep an operating system-agnostic approach within the book, it is advisable to use a computer running a Linux distribution or OS X when working with this book, as Python is already installed and running. The Linux distribution can be either installed on the machine or within a virtual machine. Almost any Linux distribution will do, and any recent version of Ubuntu will be fine.

Who this book is for

This book is for anyone who wants to develop their knowledge of Python into something that can be used on the Web. Flask follows Python design principles, and it can be easily understood by anyone who knows Python and even by those who do not.

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:

from app import api from models import Comment api.create_api(Comment, methods=['GET', 'POST'])

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

{% block content %} {{ entry.body }} <h4 id="comment-form">Submit a comment</h4> {% include "entries/includes/comment_form.html" %} {% endblock %}

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

(blog) $ python manage.py db upgradeINFO [alembic.migration] Context impl SQLiteImpl.INFO [alembic.migration] Will assume non-transactional DDL.INFO [alembic.migration] Running upgrade 594ebac9ef0c -> 490b6bc5f73c, empty message

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: "You should see the message Hello, Flask displayed on a blank white page."

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 <[email protected]>, 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 from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.

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 <[email protected]> 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 <[email protected]>, and we will do our best to address the problem.

Chapter 1. Creating Your First Flask Application

Flask is fun. This bold declaration is one of the first things you see when you view the official Flask documentation and, over the course of this book, you will come to understand why so many Python developers agree.

In this chapter we shall:

Briefly discuss the features of the Flask frameworkSet up a development environment and install FlaskImplement a minimal Flask app and analyze how it worksExperiment with commonly used APIs and the interactive debuggerStart working on the blog project that will be progressively enhanced over the course of the book

What is Flask?

Flask is a lightweight Web framework written in Python. Flask started out as an April fool's joke that became a highly popular underdog in the Python web framework world. It is now one of the most widely used Python web frameworks for start-ups, and is becoming commonly accepted as the perfect tool for quick and simple solutions in most businesses. At its core, it provides a set of powerful libraries for handling the most common web development tasks, such as:

URL routing that makes it easy to map URLs to your codeTemplate rendering with Jinja2, one of the most powerful Python template enginesSession management and securing cookiesHTTP request parsing and flexible response handlingInteractive web-based debuggerEasy-to-use, flexible application configuration management

This book will teach you how to use these tools through practical, real-world examples. We will also discuss commonly used third-party libraries for things that are not included in Flask, such as database access and form validation. By the end of this book you will be ready to tackle your next big project with Flask.

With great freedom comes great responsibility

As the documentation states, Flask is fun, but it can also be challenging, especially when you are building a large application. Unlike other popular Python web frameworks, such as Django, Flask does not enforce ways of structuring your modules or your code. If you have experience with other web frameworks, you may be surprised how writing applications in Flask feels like writing Python as opposed to the framework boilerplate.

This book will teach you to use Flask to write clean, expressive applications. As you progress through this book, you will not only become a proficient Flask developer but you will also become a stronger Python developer.

Setting up a development environment

Flask is written in Python, so before we can start writing Flask apps we must ensure that Python is installed. Most Linux distributions and recent versions of OSX come with Python pre-installed. The examples in this book will require Python 2.6 or 2.7. Instructions for installing Python can be found at http://www.python.org.

If this is your first time using Python, there are a number of excellent resources available for free on the web. I would recommend Learn Python The Hard Way, by Zed Shaw, available for free online at http://learnpythonthehardway.org. Looking for more? You can find a large list of free Python resources at http://resrc.io/list/10/list-of-free-programming-books/#python.

You can verify that Python is installed and that you have the correct version by running the Python interactive interpreter from a command prompt:

$ pythonPython 2.7.6 (default, Nov 26 2013, 12:52:49)[GCC 4.8.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>>

At the prompt (>>>) type exit() and hit Enter to leave the interpreter.

Supporting Python 3

This book will include code that is compatible with both Python 2 and Python 3 where possible. Unfortunately, since Python 3 is still relatively new as compared to Python 2, not all third-party packages used in this book are guaranteed to work seamlessly with Python 3. There is a lot of effort being put into making popular open-source libraries compatible with both versions but, at the time of writing, some libraries have still not been ported. For best results, ensure that the version of Python that you have installed on your system is 2.6 or above.

Installing Python packages

Now that you have ensured that Python is installed correctly, we will install some popular Python packages that will be used over the course of this book.

We will be installing these packages system-wide but, once they are installed, we will be working exclusively in virtual environments.

Installing pip

The de-facto Python package installer is pip . We will use it throughout the book to install Flask and other third-party libraries.

If you already have setuptools installed, you can install pip by simply running the following command:

$ sudo easy_install pip

After completing the installation, verify that pip is installed correctly:

$ pip --versionpip 1.2.1 from /usr/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg (python 2.7)

The version numbers are likely to change, so for a definitive guide please consult the official instructions, which can be found at http://www.pip-installer.org/en/latest/installing.html.

Installing virtualenv

Once pip is installed, we can proceed to install the most important tool in any Python developer's toolkit: virtualenv. Virtualenv makes it easy to produce isolated Python environments, complete with their own copies of system and third-party packages.

Why use virtualenv?

Virtualenv solves a number of problems related to package management. Imagine you have an old application that was built using a very early version of Flask, and you would like to build a new project using the most-recent version of Flask. If Flask was installed system-wide, you was be forced to either upgrade your old project or write your new project against the old Flask. If both projects were using virtualenv, then each could run its own version of Flask, with no conflicts or issues.

Virtualenv makes it easy to control which versions of the third-party package is used by your project.

Another consideration is that installing packages system-wide generally requires elevated privileges (sudo pip install foo). By using virtualenvs, you can create Python environments and install packages as a regular user. This is especially useful if you are deploying to a shared hosting environment or are in a situation where you do not have administrator privileges.

Installing virtualenv with pip

We will use pip to install virtualenv; since it is a standard Python package, it can be installed just like any other Python package. To ensure that virtualenv is installed system-wide, run the following command (it requires elevated privileges):

$ sudo pip install virtualenv$ virtualenv --version1.10.1

The version numbers are likely to change, so for a definitive guide please consult the official instructions at http://virtualenv.org.