Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Flask Framework Cookbook
Flask Framework Cookbook

Flask Framework Cookbook: Enhance your Flask skills with advanced techniques and build dynamic, responsive web applications , Third Edition

eBook
€23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m

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
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

Flask Framework Cookbook

Flask Configurations

This introductory chapter will help us understand the different ways Flask can be configured to suit the various needs of a project. Flask is “The Python micro framework for building web applications” (pallets/Flask, https://github.com/pallets/flask).

So, why is Flask called a microframework? Does this mean Flask lacks functionality, or that it’s mandatory for the complete code of your web application to be contained in a single file? Not really! The term 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, admin interface, and so on. In this chapter, you will learn several ways to set up and configure Flask.

Important information

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

Likewise, while writing this book, Flask 2.2.x was the latest version. Although a lot of code in this book can work on earlier versions of Flask, it is recommended that you use versions 2.2.x and above.

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 file, such as app.py, in any location on your computer that can access python or python3 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

Important

The code and Flask installation example here is just intended to demonstrate the ease with which Flask can be used. To set up a proper development environment, follow the recipes in this chapter.

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 to '__main__'. If we save this in a file called app.py, then the application can simply be run using the following command:

$ python3 app.py
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)

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 be run by using flask run or 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, namely 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/

Tip

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 the instance folder
  • Compositions of views and models
  • Creating a modular web app with blueprints
  • Making a Flask app installable using setuptools

Technical requirements

Working with Flask and Python in general is pretty easy and does not require a lot of dependencies and configurations. For most of the chapters in this book, all the required packages shall be mentioned in the relevant recipes. I will mention more specific requirements in relevant chapters. In general, you will need the following:

  • A decent computer, preferably with a UNIX-based OS such as Linux or macOS. You can also use Windows, which would require some additional setup, but that is out of the scope of this book.
  • A code editor of choice as the IDE. I use Vim and Visual Studio Code but anything will work, so long as it supports Python.
  • A good internet connection as you will be downloading the packages and their dependencies.

All the code is freely available on GitHub at https://github.com/PacktPublishing/Flask-Framework-Cookbook-Third-Edition. This repository on GitHub contains the code for all the chapters in this book, segregated into corresponding folders.

Setting up a virtual environment

Flask can be simply installed using pip/pip3 or easy_install globally, but it’s preferable to set up an application environment using venv. 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 for multiple applications; some packages might also have different versions of the same libraries as dependencies. venv manages this in separate environments and does not let the incorrect version of any library affect any application. In this recipe, we will learn how to create and manage these environments.

How to do it...

Python3 comes bundled with a venv module to create virtual environments. So, simply create a new environment called my_flask_env (or any other name of your choice) inside the folder of your choice where you want your development environment to live. This will create a new folder with the same name, as follows:

$ python3 -m venv my_flask_env

Run the following commands from inside the my_flask_env folder:

$ source my_flask_env/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 its 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 several packages are installed. The following is an outline of the package installation process of Flask:

$ pip3 install flask
Collecting Flask
...........
...........
Many more lines.........
...........
Installing collected packages: zipp, Werkzeug, MarkupSafe, itsdangerous, click, Jinja2, importlib-metadata, Flask
Successfully installed Flask-2.1.2 Jinja2-3.1.2 MarkupSafe-2.1.1 Werkzeug-2.1.2 click-8.1.3 importlib-metadata-4.11.4 itsdangerous-2.1.2 zipp-3.8.0

If we look carefully at the preceding snippet, we will see that multiple packages have been installed. Of these, five packages, namely, Werkzeug, Jinja2, click, itsdangerous, and markupsafe, are the packages on which Flask depends, and it will not work if any of them are missing. Others are sub-dependencies that are needed for the dependencies of Flask to work.

There’s more...

Before venv was introduced in Python 3.3, virtualenv was the standard library used to create and manage virtual environments. venv is a subset of virtualenv and misses out on the advanced features that virtualenv provides. For the sake of simplicity and to stay in the context of this book, I will use venv, but you are free to explore virtualenv and virtualenvwrapper.

See also

The references relating to this section are as follows:

Read more about virtualenv and virtualenvwrapper at https://virtualenv.pypa.io/en/latest/ and https://pypi.org/project/virtualenvwrapper/.

Handling basic configurations

One of the beauties of Flask is that it is very easy to configure a Flask application according to the needs of the project. In this recipe, we will try to understand the different ways in which a Flask application can be configured, including how to load a configuration from environment variables, Python files, or even a config object.

Getting ready

In Flask, configuration variables are stored on a dictionary-like attribute named config of the Flask object. The config attribute is a subclass of the Python dictionary, and we can modify it just like any dictionary.

How to do it...

To run our application in debug mode, for instance, we can write the following:

app = Flask(__name__)
app.config['DEBUG'] = True

Tip

The debug Boolean can also be set at the Flask object level rather than at the config level, as follows:

app.debug = True

Alternatively, we can pass debug as a named argument to app.run, as follows:

app.run(debug=True)

In new versions of Flask, the debug mode can also be set on an environment variable, FLASK_DEBUG=1. Then, we can run the app using flask run or Python’s -m switch:

$ export FLASK_DEBUG=1

Enabling debug mode will make the server reload itself in the event of any code changes, and it also provides the very helpful Werkzeug debugger when something goes wrong.

There are a bunch of configuration values provided by Flask. We will come across them in relevant recipes throughout this chapter.

As an application becomes larger, there is a need to manage the application’s configuration in a separate file, as shown in the following example. In most operating systems and development environments that you use, it is unlikely that this file will be a part of the version control system. Thus, Flask provides us with multiple ways to fetch configurations. The most frequently used methods are as follows:

  • From a Python configuration file (*.cfg), where the configuration can be fetched using the following statement:
    app.config.from_pyfile('myconfig.cfg')
  • From an object, where the configuration can be fetched using the following statement:
    app.config.from_object('myapplication.default_settings')
  • Alternatively, to load from the same file from which this command is run, we can use the following statement:
    app.config.from_object(__name__)
  • From an environment variable, the configuration can be fetched using the following statement:
    app.config.from_envvar('PATH_TO_CONFIG_FILE')
  • New in Flask version 2.0 is a capability to load from generic configuration file formats such as JSON or TOML:
    app.config.from_file('config.json', load=json.load)
Alternatively, we can do the following:
app.config.from_file('config.toml', load=toml.load)

How it works...

Flask is designed to only pick up configuration variables that are written in uppercase. This allows us to define any local variables in our configuration files and objects and leave the rest to Flask.

The best practice when using configurations is to have a bunch of default settings in app.py, or via any object in the application itself, and then override the same by loading it from the configuration file. So, the code will look as follows:

app = Flask(__name__)
DEBUG = True
TESTING = True
app.config.from_object(__name__)
app.config.from_pyfile('/path/to/config/file')

Configuring using class-based settings

An effective way of laying out configurations for different deployment modes, such as production, testing, staging, and so on, can be cleanly done using the inheritance pattern of classes. As your project gets bigger, you can have different deployment modes, and each mode can have several different configuration settings or some settings that will remain the same. In this recipe, we will learn how to use class-based settings to achieve such a pattern.

How to do it...

We can have a base class with default settings; then, other classes can simply inherit from the base class and override or add deployment-specific configuration variables to it, as shown in the following example:

class BaseConfig(object):
    'Base config class'
    SECRET_KEY = 'A random secret key'
    DEBUG = True
    TESTING = False
    NEW_CONFIG_VARIABLE = 'my value'
class ProductionConfig(BaseConfig):
    'Production specific config'
    DEBUG = False
    SECRET_KEY = open('/path/to/secret/file').read()
class StagingConfig(BaseConfig):
    'Staging specific config'
    DEBUG = True
class DevelopmentConfig(BaseConfig):
    'Development environment specific config'
    DEBUG = True
    TESTING = True
    SECRET_KEY = 'Another random secret key'

Important information

In a production configuration, the secret key is generally stored in a separate file because, for security reasons, it should not be a part of your version control system. This should be kept in the local filesystem on the machine itself, whether it is your machine or a server.

How it works...

Now, we can use any of the preceding classes while loading the application’s configuration via from_object(). Let’s say that we save the preceding class-based configuration in a file named configuration.py, as follows:

app.config.from_object('configuration.DevelopmentConfig')

Overall, this makes managing configurations for different deployment environments more flexible and easier.

Organizing static files

Organizing static files such as JavaScript, stylesheets, images, and so on efficiently is always a matter of concern for all web frameworks. In this recipe, we’ll learn how to achieve this in Flask.

How to do it...

Flask recommends a specific way of organizing static files in an application, as follows:

my_app/
    app.py
    config.py
    __init__.py
    static/
        css/
        js/
        images/
            logo.png

While rendering this in templates (say, the logo.png file), we can refer to the static files using the following code:

<img src='/static/images/logo.png'>

How it works...

If a folder named static exists at the application’s root level – that is, at the same level as app.py – then Flask will automatically read the contents of the folder without any extra configuration.

There’s more...

Alternatively, we can provide a parameter named static_folder to the application object while defining the application in app.py, as follows:

app = Flask(__name__,
    static_folder='/path/to/static/folder')

In the preceding line of code, static refers to the value of static_folder on the application object. This can be modified as follows by providing a URL prefix by supplying static_url_path:

app = Flask(
    _name_, static_url_path='/differentstatic',
    static_folder='/path/to/static/folder'
)

Now, to render the static file, we can use the following code:

<img src='/differentstatic/logo.png'>

It is always a good practice to use url_for to create URLs for static files rather than explicitly defining them, as follows:

<img src="{{ url_for('static', filename='logo.png') }}">

Being deployment-specific with the instance folder

Flask provides yet another method for configuration, where we can efficiently manage deployment-specific parts. Instance folders allow us to segregate deployment-specific files from our version-controlled application. We know that configuration files can be separate for different deployment environments, such as development and production, but there are also many more files, such as database files, session files, cache files, and other runtime files. In this recipe, we will create an instance folder that will act like a holder container for such kinds of files. By design, the instance folder will not be a part of the version control system.

How to do it...

By default, the instance folder is picked up from the application automatically if we have a folder named instance in our application at the application level, as follows:

my_app/
    app.py
    instance/
        config.cfg

We can also explicitly define the absolute path of the instance folder by using the instance_path parameter on our application object, as follows:

app = Flask(
    __name__,
    instance_path='/absolute/path/to/instance/folder')

To load the configuration file from the instance folder, we can use the instance_relative_config parameter on the application object, as follows:

app = Flask(__name__, instance_relative_config=True)

This tells the application to load the configuration file from the instance folder. The following example shows how to configure this:

app = Flask(
    __name__, instance_path='path/to/instance/folder',
    instance_relative_config=True
)
app.config.from_pyfile('config.cfg', silent=True)

How it works...

In the preceding code, first, the instance folder is loaded from the given path; then, the configuration file is loaded from the config.cfg file in the given instance folder. Here, silent=True is optional and is used to suppress the error if config.cfg is not found in the instance folder. If silent=True is not given and the file is not found, then the application will fail, giving the following error:

IOError: [Errno 2] Unable to load configuration file (No such file or directory): '/absolute/path/to/config/file'

Information

It might seem that loading the configuration from the instance folder using instance_relative_config is redundant work and could be moved to one of the configuration methods itself. However, the beauty of this process lies in the fact that the instance folder concept is completely independent of configuration, and instance_relative_config just complements the configuration object.

Composition of views and models

As our application becomes bigger, we might want to structure it in a modular manner. In this recipe, we will do this by restructuring our Hello World application.

How to do it...

First, create a new folder in the application and move all the files inside this new folder. Then, create __init__.py in the folders, which are to be used as modules.

After that, create a new file called run.py in the topmost folder. As its name implies, this file will be used to run the application.

Finally, create separate folders to act as modules.

Refer to the following file structure to get a better understanding:

flask_app/
    run.py
    my_app/
        __init__.py
        hello/
            __init__.py
            models.py
            views.py

Let’s see how each of the preceding files will look.

The flask_app/run.py file will look something like the following lines of code:

from my_app import app
app.run(debug=True)

The flask_app/my_app/__init__.py file will look something like the following lines of code:

from flask import Flask
app = Flask(__name__)
import my_app.hello.views

Next, we have an empty file just to make the enclosing folder a Python package, flask_app/my_app/hello/__init__.py:

# No content.
# We need this file just to make this folder a python module.

The models file, flask_app/my_app/hello/models.py, has a non-persistent key-value store, as follows:

MESSAGES = {
    'default': 'Hello to the World of Flask!',
}

Finally, the following is the views file, flask_app/my_app/hello/views.py. Here, we fetch the message corresponding to the requested key and can also create or update a message:

from my_app import app
from my_app.hello.models import MESSAGES
@app.route('/')
@app.route('/hello')
def hello_world():
    return MESSAGES['default']
@app.route('/show/<key>')
def get_message(key):
    return MESSAGES.get(key) or "%s not found!" % key
@app.route('/add/<key>/<message>')
def add_or_update_message(key, message):
    MESSAGES[key] = message
    return "%s Added/Updated" % key

How it works...

In this recipe, we have a circular import between my_app/__init__.py and my_app/hello/views.py, where, in the former, we import views from the latter, and in the latter, we import app from the former. Although this makes the two modules dependent on each other, there is no issue, as we won’t be using views in my_app/__init__.py. Note that it is best to import the views at the bottom of the file so that they are not used in this file. This ensures that when you refer to the app object inside the view, it does not lead to null-pointer exceptions.

In this recipe, we used a very simple non-persistent in-memory key-value store to demonstrate the model’s layout structure. We could have written the dictionary for the MESSAGES hash map in views.py itself, but it is best practice to keep the model and view layers separate.

So, we can run this app using just run.py, as follows:

$ python run.py
Serving Flask app "my_app" (lazy loading)
Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
Debug mode: on
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Restarting with stat
Debugger is active!
* Debugger PIN: 111-111-111

Tip

Note the preceding WARNING in the block. This warning occurs because we did not specify the application environment, and by default, production is assumed. To run the application in the development environment, modify the run.py file with the following:

from my_app import app

app.env="development"

app.run(debug=True)

Information

The reloader indicates that the application is being run in debug mode and that the application will reload whenever a change is made in the code.

As we can see, we have already defined a default message in MESSAGES. We can view that by opening http://127.0.0.1:5000/show/default. To add a new message, we can type http://127.0.0.1:5000/add/great/Flask%20is%20greatgreat!!. This will update the MESSAGES key-value store so that it looks like this:

MESSAGES = {
    'default': 'Hello to the World of Flask!',
    'great': 'Flask is great!!',
}

Now, if we open http://127.0.0.1:5000/show/great in a browser, we will see our message, which would have otherwise appeared as a not found message.

See also

The next recipe, Creating a modular web app with blueprints, provides a much better way of organizing your Flask applications and is a ready-made solution for circular imports.

Creating a modular web app with blueprints

A blueprint is a feature in Flask that helps make large applications modular. This keeps application dispatching simple by providing a central place to register all components in an application. A blueprint looks like an application object but is not an application. It also looks like a pluggable app or a smaller part of a bigger app, but it is not. A blueprint is a set of operations that can be registered on an application and represents how to construct or build an application. Another benefit is that it allows us to create reusable components between multiple applications.

Getting ready

In this recipe, we’ll take the application from the previous recipe, Composition of views and models, as a reference and modify it so that it works using blueprints.

How to do it...

The following is an example of a simple Hello World application using Blueprint. It will work like it did in the previous recipe but will be much more modular and extensible.

First, we will start with the following flask_app/my_app/__init__.py file:

from flask import Flask
from my_app.hello.views import hello
app = Flask(__name__)
app.register_blueprint(hello)

Next, we will add some code to the views file, my_app/hello/views.py, which should look as follows:

from flask import Blueprint
from my_app.hello.models import MESSAGES
hello = Blueprint('hello', __name__)
@hello.route('/')
@hello.route('/hello')
def hello_world():
    return MESSAGES['default']
@hello.route('/show/<key>')
def get_message(key):
    return MESSAGES.get(key) or "%s not found!" % key
@hello.route('/add/<key>/<message>')
def add_or_update_message(key, message):
    MESSAGES[key] = message
    return "%s Added/Updated" % key

We have now defined a blueprint in the flask_app/my_app/hello/views.py file. We no longer need the application object in this file, and our complete routing is defined on a blueprint named hello. Instead of @app.route, we use @hello.route. The same blueprint is imported into flask_app/my_app/__init__.py and registered on the application object.

We can create any number of blueprints in our application and complete most of the activities that we would usually do, such as providing different template paths or different static paths. We can even have different URL prefixes or subdomains for our blueprints.

How it works...

This application will work in just the same way as the last application. The only difference is in the way the code is organized.

Making a Flask app installable using setuptools

We now have a Flask app, but how do we install it like any Python package? It is possible that another application might depend on our application, or that our application is an extension of Flask and would need to be installed in a Python environment so it can be used by other applications. In this recipe, we will see how setuptools can be used to create an installable Python package.

What is a Python package?

A Python package can simply be thought of as a program that can be imported using Python’s import statement in a virtual environment or globally based on its installation scope.

How to do it...

Installing a Flask app can be easily achieved using the setuptools Python library. To achieve this, create a file called setup.py in your application’s folder and configure it to run a setup script for the application. This will take care of any dependencies, descriptions, loading test packages, and so on.

The following is an example of a simple setup.py script for the Hello World application from the previous recipe:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os
from setuptools import setup
setup(
    name = 'my_app',
    version='1.0',
    license='GNU General Public License v3',
    author='Shalabh Aggarwal',
    author_email='contact@shalabhaggarwal.com',
    description='Hello world application for Flask',
    packages=['my_app'],
    platforms='any',
    install_requires=[
        'Flask',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: GNU General Public
          License v3',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development :: Libraries ::
          Python Modules'
],
)

How it works...

In the preceding script, most of the configuration is self-explanatory. The classifiers are used when the application is made available on PyPI. These will help other users search the application using the relevant classifiers.

Now, we can run this file with the install keyword, as follows:

$ python setup.py install

The preceding command will install the application along with all the dependencies mentioned in install_requires – that is, Flask and all of Flask’s dependencies. Now, the app can be used just like any Python package in a Python environment.

To verify the successful installation of your package, import it inside a Python environment:

$ python
Python 3.8.13 (default, May  8 2022, 17:52:27)
>>> import my_app
>>>

See also

The list of valid trove classifiers can be found at https://pypi.python.org/pypi?%3Aaction=list_classifiers.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • A practical and rich companion guide for web developers, offering real-world situations and use cases to learn Flask
  • Get the most out of the powerful Flask framework while preserving the flexibility of your design choices
  • Write cleaner, testable, and maintainable code with the help of sample apps

Description

Discover what makes Flask, the lightweight Python web framework, popular, as you delve into its modular design that enables the development of scalable web apps. With this practical guide, you'll explore modern solutions, recommended design patterns, and best practices for Flask web development. Updated to the latest version of Flask and Python, this third edition of the Flask Framework Cookbook moves away from the outdated libraries, updates content to incorporate new coding patterns, and introduces recipes for the latest tools. You'll explore different ways to integrate with GPT to build AI-ready Flask applications. The book starts with an exploration of Flask application configurations and then guides you through working with templates and understanding the ORM and view layers. You’ll also be able to write an admin interface and get to grips with testing using the factory pattern, debugging, and logging errors. Then you’ll discover different ways of using Flask to create, deploy, and manage microservices using AWS, GCP, and Kubernetes. Finally, you’ll gain insights into various deployment and post-deployment techniques for platforms such as Apache, Tornado, and Datadog. By the end of this book, you'll have acquired the knowledge necessary to write Flask applications that cater to a wide range of use cases in the best possible way and scale them using standard industry practices.

Who is this book for?

If you are a web developer seeking to expand your knowledge of developing scalable and production-ready applications in Flask, this is the book for you. It is also highly valuable if you are already aware of Flask's major extensions and want to leverage them for better application development. This book will come handy as a quick reference for specific topic on Flask, its popular extensions, or specific use cases. It assumes basic Python programming experience, as well as familiarity with web development and related terminology.

What you will learn

  • Explore advanced templating and data modeling techniques
  • Discover effective debugging, logging, and error-handling techniques in Flask
  • Work with different types of databases, including RDBMS and NoSQL
  • Integrate Flask with different technologies such as Redis, Sentry, and Datadog
  • Deploy and package Flask applications with Docker and Kubernetes
  • Integrate GPT with your Flask application to build future-ready platforms
  • Implement continuous integration and continuous deployment (CI/CD) to ensure efficient and consistent updates to your Flask web applications

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 28, 2023
Length: 318 pages
Edition : 3rd
Language : English
ISBN-13 : 9781804610008
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
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : Jul 28, 2023
Length: 318 pages
Edition : 3rd
Language : English
ISBN-13 : 9781804610008
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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 €5 each
Feature tick icon Exclusive print discounts
€264.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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 97.97
Full-Stack Flask and React
€29.99
Flask Framework Cookbook
€29.99
50 Algorithms Every Programmer Should Know
€37.99
Total 97.97 Stars icon

Table of Contents

19 Chapters
Part 1: Flask Fundamentals Chevron down icon Chevron up icon
Chapter 1: Flask Configurations Chevron down icon Chevron up icon
Chapter 2: Templating with Jinja Chevron down icon Chevron up icon
Chapter 3: Data Modeling in Flask Chevron down icon Chevron up icon
Chapter 4: Working with Views Chevron down icon Chevron up icon
Part 2: Flask Deep Dive Chevron down icon Chevron up icon
Chapter 5: Web Forms with WTForms Chevron down icon Chevron up icon
Chapter 6: Authenticating in Flask Chevron down icon Chevron up icon
Chapter 7: RESTful API Building Chevron down icon Chevron up icon
Chapter 8: Admin Interface for Flask Apps Chevron down icon Chevron up icon
Chapter 9: Internationalization and Localization Chevron down icon Chevron up icon
Part 3: Advanced Flask Chevron down icon Chevron up icon
Chapter 10: Debugging, Error Handling, and Testing Chevron down icon Chevron up icon
Chapter 11: Deployment and Post-Deployment Chevron down icon Chevron up icon
Chapter 12: Microservices and Containers Chevron down icon Chevron up icon
Chapter 13: GPT with Flask Chevron down icon Chevron up icon
Chapter 14: Additional Tips and Tricks Chevron down icon Chevron up icon
Index 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 Full star icon Half star icon 4.8
(12 Ratings)
5 star 83.3%
4 star 8.3%
3 star 8.3%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Bohuslav Hošek Feb 08, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Hemant Aug 17, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Flask Framework Cookbook is a robust resource for advancing Flask skills. While it assumes some familiarity with Flask, its comprehensive coverage and hands-on approach makes it an essential tool for developers seeking to elevate their Flask proficiency. It offers a comprehensive range of recipes, catering to both novice developers and seasoned pros. The step-by-step instructions will guide you through real-world scenarios, making complex concepts digestible.
Amazon Verified review Amazon
Not Your Average Consumer Aug 04, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book takes a practical, hands-on approach, providing numerous real-world examples that are easy to follow.One thing that stood out to me was how the book keeps up with the latest trends and technologies. The fact that it's updated to the most recent version of Flask and Python instantly won my confidence. The inclusion of AI integration with GPT opened up a whole new realm of possibilities for my projects.Another one of my favorite parts of the book was discovering how to create microservices using Flask on platforms like AWS, GCP, and Kubernetes. It gave me the confidence to experiment with distributed applications and explore new frontiers.What sets this book apart is how it caters to developers of all levels. Whether you're a Flask beginner or someone with prior experience, the book ensures you'll learn something new and find inspiration for your projects. The well-organized content and clear explanations make it an excellent reference for both learning and problem-solving.
Amazon Verified review Amazon
Ian Propst-Campbell Aug 06, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a comprehensive overview of the Flask framework, complete with lots of real life code samples and helpful tips about Flask implementation. An important and valuable resource for any developer learning or using the Flask framework.
Amazon Verified review Amazon
Amazon Customer Jul 30, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"Flask Framework Cookbook" is a comprehensive and well-crafted book that caters to web developers of all levels. From foundational concepts like Flask configurations and setting up virtual environments to advanced topics such as authentication, RESTful API building, and GPT applications, the book covers a wide range of essential subjects.The author's lucid explanations, practical examples, and humane tone make learning Flask a delightful experience. Moreover, the book's inclusion of cutting-edge technologies like GPT-based applications adds a forward-looking perspective, making it stand out among other Flask resources. Whether you're a beginner or an experienced developer, this book equips you with the knowledge and confidence to build robust and sophisticated web applications.Highly recommended! Happy coding!
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.