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
Flask Framework Cookbook
Flask Framework Cookbook

Flask Framework Cookbook: Over 80 proven recipes and techniques for Python web development with Flask , Second Edition

Arrow left icon
Profile Icon Shalabh Aggarwal
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (11 Ratings)
Paperback Jul 2019 302 pages 2nd Edition
eBook
Can$62.99 Can$70.99
Paperback
Can$88.99
Subscription
Free Trial
Arrow left icon
Profile Icon Shalabh Aggarwal
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (11 Ratings)
Paperback Jul 2019 302 pages 2nd Edition
eBook
Can$62.99 Can$70.99
Paperback
Can$88.99
Subscription
Free Trial
eBook
Can$62.99 Can$70.99
Paperback
Can$88.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Flask Framework Cookbook

Flask Configurations

This introductory chapter will help us to understand the different ways Flask can be configured to suit various needs as per the demands of the project.

"Flask is a microframework for Python based on Werkzeug, Jinja 2, and good intentions."
- Flask official documentation

So, why a microframework? Does this mean Flask lacks functionality, or that it's mandatory your complete web application goes inside one file? Not really! The microframework simply refers to the fact that Flask aims to keep the core of its framework small but highly extensible. This makes writing applications or extensions both easy and flexible, and gives developers the power to choose the configurations they want for their application without imposing any restrictions on the choice of database, templating engine, and so on. In this chapter, you will learn a number of ways to set up and configure Flask.

This whole book uses Python 3 as the default version of Python. Python 2 loses its support on December 31st, 2019, and is therefore not supported in this book. It is recommended that readers use Python 3 while learning from this book, as many of the recipes might not work on Python 2.

Getting started with Flask takes just a couple of minutes. Setting up a simple Hello World application is as easy as pie. Simply create a filename, such as app.py—in any location on your computer that can access python—that contains the following script:

from flask import Flask 
app = Flask(__name__) 
 
@app.route('/') 
def hello_world(): 
    return 'Hello to the World of Flask!' 
 
if __name__ == '__main__': 
    app.run() 

Now, Flask needs to be installed; this can be done via pip or pip3. You may have to use sudo on a Unix-based machine if you run into access issues:

    $ pip3 install Flask

The preceding snippet is a complete Flask-based web application. Here, an instance of the imported Flask class is a Web Server Gateway Interface (WSGI) (http://legacy.python.org/dev/peps/pep-0333/) application. So, app in this code becomes our WSGI application, and as this is a standalone module; we set the __name__ string as '__main__'. If we save this in a file with the name app.py, then the application can simply be run using the following command:

    $ python3 app.py
    * Running on http://127.0.0.1:5000/

Now, if we head over to our browser and type http://127.0.0.1:5000/, we can see our application running.

Alternatively, the application can also be run by using flask run or by using Python's -m switch with Flask. While following this approach, the last two lines of app.py can be skipped. Note that the following commands work only if there is a file named app.py or wsgi.py in the current directory. If not, then the file containing the app object should be exported as an environment variable, such as FLASK_APP. As a best practice, this should be done in either case:

    $ export FLASK_APP=app.py
$ flask run

* Running on http://127.0.0.1:5000/

Alternatively, if you decide to use the -m switch, it will look as follows:

    $ export FLASK_APP=app.py
$ python3 -m flask run

* Running on http://127.0.0.1:5000/
Never save your application file as flask.py; if you do, it will conflict with Flask itself while importing.

In this chapter, we will cover the following recipes:

  • Setting up our environment with virtualenv
  • Handling basic configurations
  • Configuring class-based settings
  • Organizing static files
  • Being deployment-specific with instance folders
  • Compositions of views and models
  • Creating a modular web app with Blueprints
  • Making a Flask app installable using setuptools

Setting up our environment with virtualenv

Flask can be simply installed using pip/pip3 or easy_install globally, but it's preferable to set up an application environment using virtualenv. This prevents the global Python installation from being affected by a custom installation, as it creates a separate environment for the application. This separate environment is helpful as it allows you to have multiple versions of the same library used for multiple applications; some packages might also have different versions of the same libraries as dependencies. virtualenv manages this in separate environments and does not let the incorrect version of any library affect any application. In this recipe, we will learn about how to create and manage these environments.

How to do it...

First, install virtualenv using pip3 and then create a new environment with the name my_flask_env inside the folder in which we ran the first command. This will create a new folder with the same name, as follows:

    $ pip3 install virtualenv
    $ virtualenv my_flask_env
  

Run the following commands from inside the my_flask_env folder:

    $ cd my_flask_env
    $ source bin/activate
    $ pip3 install flask

This will activate our environment and install Flask inside it. Now, we can do anything with our application within this environment, without affecting any other Python environment.

How it works...

So far, we have used pip3 install flask multiple times. As the name suggests, the command refers to the installation of Flask, just like any Python package. If we look a bit deeper into the process of installing Flask via pip3, we will see that a number of packages are installed. The following is an outline of the package installation process of Flask:

    $ pip3 install -U flask
    Downloading/unpacking flask
    ...........
    ...........
    Many more lines.........
    ...........
    Successfully installed flask Werkzeug Jinja2 itsdangerous
markupsafe click
Cleaning up...
In the preceding command, -U refers to an installation with upgrades. This will overwrite any existing installation with the latest released versions.

If we look carefully at the preceding snippet, we will see that there are six packages installed in total; namely, flask, Werkzeug, Jinja2, click, itsdangerous, and markupsafe. These are the packages on which Flask depends, and it will not work if any of them are missing.

There's more...

To make our lives easier, we can use virtualenvwrapper, which, as the name suggests, is a wrapper written over virtualenv and makes the handling of multiple instances of virtualenv easier.

Remember that the installation of virtualenvwrapper should be done on a global level. So, deactivate any virtualenv that might still be active. To deactivate, use the following command:

$ deactivate
It is also possible that you might not be able to install the package on a global level because of permission issues. Switch to superuser or use sudo if this occurs.

Install virtualenvwrapper using the following commands:

$ pip3 install virtualenvwrapper
$ export WORKON_HOME=~/workspace
$ source /usr/local/bin/virtualenvwrapper.sh

In the preceding code, we installed virtualenvwrapper, created a new environment variable with the name WORKON_HOME, and provided it with a path, which will act as the home for all virtual environments created using virtualenvwrapper.

To create a virtualenv and install Flask, use the following commands:

$ mkvirtualenv my_flask_env
$ pip3 install flask

To deactivate a virtualenv, simply run the following command:

$ deactivate

To activate an existing virtualenv using virtualenvwrapper, run the following command:

 $ workon my_flask_env
Remember that all the commands used with virtualenv are also available with virtualenvwrapper. Commands such as mkvirtualenv and workon are quick alternatives that make life a bit easier.

See also

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore Flask 1.0.3 and Python 3.7, along with useful insights into microservices
  • Get the most out of the powerful Flask framework and maintain the flexibility of your design choices
  • Write cleaner and maintainable code with the help of sample apps

Description

Flask, the lightweight Python web framework, is popular thanks to its powerful modular design that lets you build scalable web apps. With this recipe-based guide, you’ll explore modern solutions and best practices for Flask web development. Updated to the latest version of Flask and Python 3, this second edition of Flask Framework Cookbook moves away from some of the old and obsolete libraries and introduces new recipes on cutting-edge technologies. You’ll discover different ways of using Flask to create, deploy, and manage microservices. This Flask Python book starts by covering the different configurations that a Flask application can make use of, and then helps you work with templates and learn about the ORM and view layers. You’ll also be able to write an admin interface and get to grips with debugging and logging errors. Finally, you’ll learn a variety of deployment and post-deployment techniques for platforms such as Apache, Tornado, and Heroku. By the end of this book, you’ll have gained all the knowledge you need to confidently write Flask applications and scale them using standard industry practices.

Who is this book for?

If you are a web developer who wants to learn more about developing scalable and production-ready applications in Flask, this is the book for you. You’ll also find this book useful if you are already aware of Flask's major extensions and want to use them for better application development. Basic Python programming experience along with basic understanding of Flask is assumed.

What you will learn

  • Explore web application development in Flask, right from installation to post-deployment stages
  • Make use of advanced templating and data modeling techniques
  • Discover effective debugging, logging, and error handling techniques in Flask
  • Integrate Flask with different technologies such as Redis, Sentry, and MongoDB
  • Deploy and package Flask applications with Docker and Kubernetes
  • Design scalable microservice architecture using AWS Lambda continuous integration and continuous deployment

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 17, 2019
Length: 302 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789951295
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jul 17, 2019
Length: 302 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789951295
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 Can$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 Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 194.97
Python API Development Fundamentals
Can$49.99
Mastering Flask Web Development
Can$55.99
Flask Framework Cookbook
Can$88.99
Total Can$ 194.97 Stars icon

Table of Contents

14 Chapters
Flask Configurations Chevron down icon Chevron up icon
Templating with Jinja2 Chevron down icon Chevron up icon
Data Modeling in Flask Chevron down icon Chevron up icon
Working with Views Chevron down icon Chevron up icon
Webforms with WTForms Chevron down icon Chevron up icon
Authenticating in Flask Chevron down icon Chevron up icon
RESTful API Building Chevron down icon Chevron up icon
Admin Interface for Flask Apps Chevron down icon Chevron up icon
Internationalization and Localization Chevron down icon Chevron up icon
Debugging, Error Handling, and Testing Chevron down icon Chevron up icon
Deployment and Post-Deployment Chevron down icon Chevron up icon
Microservices and Containers Chevron down icon Chevron up icon
Other Tips and Tricks Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(11 Ratings)
5 star 54.5%
4 star 9.1%
3 star 0%
2 star 9.1%
1 star 27.3%
Filter icon Filter
Top Reviews

Filter reviews by




Rajendra Sharma Sep 05, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
He had the most sagacious way to structure the book and very well laid out with wonderful examples.He teaches all the new concepts via an actual app that you can make along with him. What makes this especially amazing/helpful is the subject matter itself.
Amazon Verified review Amazon
Richard Jun 04, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
i've been using python flask and django [with bulma and bootstrap] for a good while now and until now i much preferred django as a web framework as it is very powerful and flask comes as a bare bones framework with very little out of the box.i've read the usual flask reference books and although they are comprehensive they can be verbose and it's not so easy to find the snippets that you need.this book is well organised, presented and cross referenced so that you can go to relevant sections in a flash.my motivation for choosing this book was to understand flask blueprints better as i was getting annoying circular imports. not only can i now organise my code but i have an excellent reference collection of extensions that i can use out of the box to make my apps much more functional.highly recommended
Amazon Verified review Amazon
debashish Feb 21, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Concise introductions to a broad range of Flask topics.
Amazon Verified review Amazon
Ashish Desai Apr 12, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Perfect book for folks who are used to pgrogramming and need a quick reference to solve a specific scenario. Covers most use cases any developer will encounter during 90% of their dev time
Amazon Verified review Amazon
Alex Sep 11, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It's a great book and I used it to create several services, but I just wish I had not started with Flask but used Django instead. Yes, you can get a webserver running with five lines of code and you can build everything using Flask and SqlAlchemy and you can also build a house only using a screwdriver and enough determination.But if you want to build a serious web application and need a lot of features, just do yourself a favour, stop here and start learning Django.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.