Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Mastering Flask Web Development
Mastering Flask Web Development

Mastering Flask Web Development: Build enterprise-grade, scalable Python web applications , Second Edition

Arrow left icon
Profile Icon Gaspar Profile Icon Jack Stouffer
Arrow right icon
S$42.99 S$47.99
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2 (2 Ratings)
eBook Oct 2018 332 pages 2nd Edition
eBook
S$42.99 S$47.99
Paperback
S$59.99
Subscription
Free Trial
Arrow left icon
Profile Icon Gaspar Profile Icon Jack Stouffer
Arrow right icon
S$42.99 S$47.99
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2 (2 Ratings)
eBook Oct 2018 332 pages 2nd Edition
eBook
S$42.99 S$47.99
Paperback
S$59.99
Subscription
Free Trial
eBook
S$42.99 S$47.99
Paperback
S$59.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Mastering Flask Web Development

Getting Started

Over the course of this book, you will be introduced to multiple concepts that will enable you to build a complete modern web application. You will progress from a "Hello world" web page to a complete web application that uses databases, caches, asynchronous task processing, authentication, role-based access, a REST API, and internationalization. You will learn a comprehensive way of structuring your application so that it can grow effortlessly. To choose between SQL and NoSQL technologies, you will learn how to use the most common Flask extensions to help you leverage multiple technologies, from sending emails to authentication using social media accounts. Toward the end, you will learn how to write tests, build a modern continuous integration/delivery pipeline with Docker and Jenkins, deploy your application to multiple cloud services, and know how to deal with high availability and scaling. We will tackle all of these topics with a simple and practical approach.

Flask is the Python web framework that we are going to use. It has a very well-designed API, is very easy to learn, and makes no assumptions whatsoever as to what technology stack you are going to use, so it won't get in your way. Flask has a micro footprint, but leverages an extension system that contains hundreds of packages from a very active and vibrant community.

In this first chapter, you will learn how to set up your development environment and build your first Flask application. We will be covering the following topics:

  • Setting up and learning how to use Git, a powerful version control system
  • Learning pip, the Python management system, and how to create virtual environments with different setups
  • Setting up and learning the basic facts about Docker
  • Building a first simple Flask application

Version control with Git

Using Python or any other language requires you to use a version control system. A version control system is a tool that records changes in files over time. This allows a programmer to revert to an earlier version of the file and identify bugs more easily. You can test new ideas without fear of breaking your current code, and your team can work using a predefined workflow without stepping on each others' toes. Git was developed by Linus Torvalds, the father of Linux. It's decentralized, light, and has great features that get the job done the right way.

Installing Git

Installing Git is very simple. Simply go to http://www.git-scm.com/downloads and click on the operating system (OS) that is being run. A program will begin to download will walk you through the basic installation process.

Git on Windows

Git was originally solely developed for Unix OSes (for example, Linux and macOS X). Consequently, using Git on Windows is not seamless. During the installation, the installer will ask whether you want to install Git alongside the normal Windows Command Prompt. Do not pick this option. Choose the default option that will install a new type of command processor on your system named Bash (Bourne-again shell), which is the same command processor that the Unix systems use. Bash is much more powerful than the default Windows command line, and this is what we will be using for all the examples in this book.

A good introduction to Bash for beginners can be found at http://linuxcommand.org.

Git basics

Git is a very complex tool; only the basics that are needed for this book will be covered in this section.

To learn more, refer to the Git documentation at http://www.git-scm.com/doc.

Git does not track your changes automatically. In order for Git to run properly, we have to give it the following information:

  • Which folders to track
  • When to save the state of the code
  • What to track and what not to track

Before we can do anything, we have to tell Git to initialize a new git repository in our directory. Run the following code on your Terminal:

$ git init

Git will now start to track changes in our project. As git tracks our files, we can see the status of our tracked files and any files that are not tracked by typing the following command:

$ git status

Now we can save our first commit, which is a snapshot of our code at the time that we run the commit command:

# In Bash, comments are marked with a #, just like Python
# Add any files that have changes and you wish to save in this      
# commit $ git add main.py # Commit the changes, add in your commit message with -m $ git commit -m "Our first commit"

Now, at any point in the future, we can return to this point in our project. Adding files that are to be committed is called staging files in Git. Remember that you should only add stage files if you are ready to commit them. Once the files are staged, any further changes will not be staged. For an example of more advanced Git usage, add any text to your main.py file with your text editor and then run the following:

    # To see the changes from the last commit
    $ git diff
    # To see the history of your changes
    $ git log
    # As an example, we will stage main.py
    # and then remove any added files from the stage
    $ git add main.py
    $ git status
    $ git reset HEAD main.py
    # After any complicated changes, be sure to run status
    # to make sure everything went well
    $ git status
    # lets delete the changes to main.py, reverting to its state at the   
# last commit # This can only be run on files that aren't staged $ git checkout -- main.py

Your terminal should look something like the following:

Note that in the preceding example I have modified the main.py file by adding the comment # Changed to show the git diff command.

One important step to include in every Git repository is a .gitignore file. This file tells Git what files to ignore. This way you can safely commit and add all your files. The following are some common files that you can ignore:

  • Python's byte code files (*.pyc)
  • Databases (specially for our examples using SQLLite database files) (*.db)
  • Secrets (never push secrets (password, keys, and so on) to your repositories)
  • IDE metadata files (.idea)
  • The Virtualenv directory (env or venv)

Here's a simple example of a gitignore file:

*.pyc
*.pem
*.pub
*.tar.gz
*.zip
*.sql
*.db
secrets.txt
./tmp
./build/*
.idea/*
.idea
env
venv

Now we can safely add all the files to git and commit them:

  $ git add --all
$ git status
$ git commit -a -m "Added gitignore and all the projects missing
files"

The Git system's checkout command is rather advanced for this simple introduction, but it is used to change the current status of the Git system's HEAD pointer, which refers to the current location of our code in the history of our project. This will be shown in the next example.

Now, if we wish to see the code in a previous commit, we should first run the following command:

$ git log
commit cd88be37f12fb596be743ccba7e8283dd567ac05 (HEAD -> master)
Author: Daniel Gaspar
Date: Sun May 6 16:59:46 2018 +0100

Added gitignore and all the projects missing files
commit beb471198369e64a8ee8f6e602acc97250dce3cd
Author: Daniel Gaspar
Date: Fri May 4 19:06:57 2018 +0100

Our first commit

The string of characters next to our commit message, beb4711, is called the hash of our commit. It is the unique identifier of the commit that we can use to return to the saved state. Now, to take the project back to the previous state, run the following command:

$ git checkout beb4711

Your Git project is now in a special state where any changes or commits will neither be saved nor affect any commits that were made after the one you checked out. This state is just for viewing old code. To return to the normal mode of Git, run the following command:

$ git checkout master

Git branches and flow

Source control branches are an important feature that works great in team projects. A developer can create a new line of code from a specific point in time, revision, or tag. In this way, developing new features, creating releases, and making bugfixes or hotfixes can be done safely and subjected to team revision, and/or automatic integration tools (such as tests, code coverage, lint tools). A branch can be merged with other branches until it finally reaches the main line of code, called the master branch.

But let's get our hands on a practical exercise. Let's say that we want to develop a new feature. Our first chapter example displays the traditional "Hello World" message, but we want it to say "good morning" to the users. First, we create a branch from a special branch called the feature/good-morning that for now is a copy of the master branch, as shown in the following code:

# Display our branches
$ git branch
* master
# Create a branch called feature/good-morning from master
$ git branch feature/good-morning
# Display our branches again
$ git branch
feature/good-morning
* master
# Check out the new feature/good-morning branch
$ git checkout feature/good-morning

This could be resumed to the following:

$ git checkout -b feature/good-morning master

Now let's change our code to display good morning to the visitors of a certain URL, along with their names. To do this, we change main.py, which looks like the following code:

@app.route('/')
def home():
return '<h1>Hello world</h1>'

We change main.py to the following:

@app.route('/username')
def home():
return '<h1>Good Morning %s</h1>' % username

Let's look at what we have done:

$ git diff
diff --git a/main.py b/main.py
index 3e0aacc..1a930d9 100755
--- a/main.py
+++ b/main.py
@@ -5,9 +5,9 @@ app = Flask(__name__)
app.config.from_object(DevConfig)

# Changed to show the git diff command
-@app.route('/')
-def home():
- return '<h1>Hello World!</h1>'
+@app.route('/<username>')
+def home(username):
+ return '<h1>Good Morning %s</h1>' % username

if __name__ == '__main__':
app.run()

Looks good. Let's commit, as shown in the following code:

$ git commit -m "Display good morning because its nice"
[feature/good-morning d4f7fb8] Display good morning because its nice
1 file changed, 3 insertions(+), 3 deletions(-)

Now, if we were working as part of a team, or if our work was open source (or if we just wanted to back up our work), we should upload (push) our code to a centralized remote origin. One way of doing this is to push our code to a version control system, such as Bitbucket or GitHub, and then open a pull request to the master branch. This pull request will show our changes. As such, it may need approval from other team members, and many other features that these systems can provide.

One example of a pull request on the Flask project can be found at https://github.com/pallets/flask/pull/1767.

For our example, let's just merge to the master, as shown in the following code:

# Get back to the master branch
$ git checkout master

Switched to branch 'master'
bash-3.2$ git log
commit 139d121d6ecc7508e1017f364e6eb2e4c5f57d83 (HEAD -> master)
Author: Daniel Gaspar
Date: Fri May 4 23:32:42 2018 +0100

Our first commit
# Merge our feature into the master branch
$ git merge feature/good-morning
Updating 139d121..5d44a43
Fast-forward
main.py | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
bash-3.2$ git log
commit 5d44a4380200f374c879ec1f7bda055f31243263 (HEAD -> master, feature/good-morning)
Author: Daniel Gaspar
Date: Fri May 4 23:34:06 2018 +0100

Display good morning because its nice

commit 139d121d6ecc7508e1017f364e6eb2e4c5f57d83
Author: Daniel Gaspar <daniel.gaspar@miniclip.com>
Date: Fri May 4 23:32:42 2018 +0100

Our first commit

As you can see from the output, Git uses the fast-forward strategy by default. If we wanted to keep an extra commit log message that mentions the merge itself, then we could have used the --no-ff flag on the git merge command. This flag will disable the fast-forward merging strategy.

Now imagine that we regret our change and want to revert the feature that we have just created back to an earlier version. To do this, we can use the following code:

$ git revert

With Git, you can actually delete your commits, but this is considered a really bad practice. Note that the revert command did not delete our merge, but created a new commit with the reverted changes. It's considered a good practice not to rewrite the past.

What was shown is a feature branch simple workflow. With big teams or projects, the use of more complex workflows is normally adopted to better isolate features, fixes, and releases, and to keep a stable line of code. This is what is proposed when using the git-flow process.

Now that we have a version control system, we are ready to cover Python's package management system.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create production-ready MVC and REST API with the dynamic features of Flask
  • Utilize the various extensions like Flask-JWT and Flask-SQLAlchemy to develop powerful applications
  • Deploy your flask application on real-world platforms like AWS and Heroku on VM’s or Docker containers

Description

Flask is a popular Python framework known for its lightweight and modular design. Mastering Flask Web Development will take you on a complete tour of the Flask environment and teach you how to build a production-ready application. You'll begin by learning about the installation of Flask and basic concepts such as MVC and accessing a database using an ORM. You will learn how to structure your application so that it can scale to any size with the help of Flask Blueprints. You'll then learn how to use Jinja2 templates with a high level of expertise. You will also learn how to develop with SQL or NoSQL databases, and how to develop REST APIs and JWT authentication. Next, you'll move on to build role-based access security and authentication using LDAP, OAuth, OpenID, and database. Also learn how to create asynchronous tasks that can scale to any load using Celery and RabbitMQ or Redis. You will also be introduced to a wide range of Flask extensions to leverage technologies such as cache, localization, and debugging. You will learn how to build your own Flask extensions, how to write tests, and how to get test coverage reports. Finally, you will learn how to deploy your application on Heroku and AWS using various technologies, such as Docker, CloudFormation, and Elastic Beanstalk, and will also learn how to develop Jenkins pipelines to build, test, and deploy applications.

Who is this book for?

The ideal target audience for this book would be Python developers who want to use Flask and its advanced features to create Enterprise grade and lightweight applications. The book is for those who have some exposure of Flask and want to take it from introductory to master level.

What you will learn

  • Develop a Flask extension using best practices
  • Implement various authentication methods: LDAP, JWT, Database, OAuth, and OpenID
  • Learn how to develop role-based access security and become an expert on Jinja2 templates
  • Build tests for your applications and APIs
  • Install and configure a distributed task queue using Celery and RabbitMQ
  • Develop RESTful APIs and secure REST API s
  • Deploy highly available applications that scale on Heroku and AWS using Docker or VMs

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 31, 2018
Length: 332 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788999557
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Oct 31, 2018
Length: 332 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788999557
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 221.97
Mastering Flask Web Development
S$59.99
Django 2 Web Development Cookbook
S$66.99
Flask Framework Cookbook
S$94.99
Total S$ 221.97 Stars icon

Table of Contents

14 Chapters
Getting Started Chevron down icon Chevron up icon
Creating Models with SQLAlchemy Chevron down icon Chevron up icon
Creating Views with Templates Chevron down icon Chevron up icon
Creating Controllers with Blueprints Chevron down icon Chevron up icon
Advanced Application Structure Chevron down icon Chevron up icon
Securing Your App Chevron down icon Chevron up icon
Using NoSQL with Flask Chevron down icon Chevron up icon
Building RESTful APIs Chevron down icon Chevron up icon
Creating Asynchronous Tasks with Celery Chevron down icon Chevron up icon
Useful Flask Extensions Chevron down icon Chevron up icon
Building Your Own Extension Chevron down icon Chevron up icon
Testing Flask Apps Chevron down icon Chevron up icon
Deploying Flask Apps Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
(2 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 100%
1 star 0%
Veil_Lord May 01, 2019
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
So the book isn't awful, it's got a lot of good info. However, it's also got unforgivable issues. For example, when setting up virtualenv it guides you through the steps. The problem being, the steps are largely wrong if you're on a Windows machine. You have to activate env/scripts/activate it is NOT actually env/bin/activate as you're told. Windows is literally the most used OS in the world, so not putting a footnote or anything is just insane. I wasted good hour trying to get it to work then hunting down on Google because of it. Makes me wonder what other surprises the book will have as I go on. Wishing I'd picked up one of the O'Reilly books. Those have always been good for me.
Amazon Verified review Amazon
Courtney Schuett Mar 22, 2020
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
There is a lot of good info in here, but the instructions and steps to follow have numerous gaps. Assumptions are made and steps are skipped entirely leading to extensive time spent troubleshooting instead of learning.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.