Home Web Development Flask Framework Cookbook - Third Edition

Flask Framework Cookbook - Third Edition

By Shalabh Aggarwal
ai-assist-svg-icon Book + AI Assistant
eBook + AI Assistant $31.99 $21.99
Print $39.99
Subscription $15.99 $10 p/m for three months
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
eBook + AI Assistant $31.99 $21.99
Print $39.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Flask Configurations
About this book
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.
Publication date:
July 2023
Publisher
Packt
Pages
318
ISBN
9781804611104

 

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.

About the Author
  • Shalabh Aggarwal

    Shalabh Aggarwal is a seasoned engineering leader who develops and manages enterprise systems and web and mobile applications for small- and large-scale organizations. He started his career working with Python, and although he now works on multiple technologies, he remains a Python developer at heart. He is passionate about open source technologies and writes highly readable and high-quality code. Throughout his career, he has built software products and engineering teams for companies moving from 0 to 1, 1 to 10, and 10 to 100 levels. He is also active in voluntary training for engineering students and young engineers on non-conventional and open source topics. When not working with full-time assignments, he consults for start-ups on starting or scaling up while leveraging different technologies. When not writing code, he dedicates his time to his young kid and occasional travels.

    Browse publications by this author
Latest Reviews (3 reviews total)
Good content but the code snippets do not always match the code in the github repo.
Flask Framework Cookbook - Third Edition
Unlock this book and the full library FREE for 7 days
Start now