Mastering Flask Web and API Development: Build and deploy production-ready Flask apps seamlessly across web, APIs, and mobile platforms
()
Related to Mastering Flask Web and API Development
Related ebooks
Building the Future: Advanced Web Development Techniques with Flask and Python Rating: 0 out of 5 stars0 ratings50+ App Features with Python: Implement feature-focused, code-driven Python capabilities with UX at the core Rating: 0 out of 5 stars0 ratings50+ App Features with Python Rating: 0 out of 5 stars0 ratingsFlask Application Development Guide: Definitive Reference for Developers and Engineers Rating: 0 out of 5 stars0 ratingsFastAPI Cookbook: Develop high-performance APIs and web applications with Python Rating: 0 out of 5 stars0 ratingsPython Programming : Web Development, Flask, Django, FastAPI: Python, #4 Rating: 0 out of 5 stars0 ratingsNode.js Cookbook: Practical recipes for building server-side web applications with Node.js 22 Rating: 0 out of 5 stars0 ratingsMastering Python: A Journey Through Programming and Beyond Rating: 0 out of 5 stars0 ratingsDjango in Production: Expert tips, strategies, and essential frameworks for writing scalable and maintainable code in Django Rating: 0 out of 5 stars0 ratingsFull-Stack Web Development with TypeScript 5: Craft modern full-stack projects with Bun, PostgreSQL, Svelte, TypeScript, and OpenAI Rating: 0 out of 5 stars0 ratingsThe FastAPI Handbook: Simplifying Web Development with Python Rating: 0 out of 5 stars0 ratingsThe Complete Guide to Technology & Programming Rating: 0 out of 5 stars0 ratingsNGINX HTTP Server: Harness the power of NGINX with a series of detailed tutorials and real-life examples Rating: 0 out of 5 stars0 ratingsDjango on the Go: Harnessing the Power of Django in Termux on Android Rating: 0 out of 5 stars0 ratingsLearning Programming and Computer Science: 1, #1 Rating: 0 out of 5 stars0 ratingsHands-On Python for DevOps: Leverage Python's native libraries to streamline your workflow and save time with automation Rating: 0 out of 5 stars0 ratingsModern Full-Stack React Projects: Build, maintain, and deploy modern web apps using MongoDB, Express, React, and Node.js Rating: 0 out of 5 stars0 ratingsHTML language complete Rating: 0 out of 5 stars0 ratingsDeploying Python Applications with Gunicorn: Definitive Reference for Developers and Engineers Rating: 0 out of 5 stars0 ratingsPython APIs: From Concept to Implementation Rating: 5 out of 5 stars5/5Master Python: Unlock the Language of the Future Rating: 0 out of 5 stars0 ratingsFoundation Web Development Essentials: Definitive Reference for Developers and Engineers Rating: 0 out of 5 stars0 ratingsKickstart Python Programming Fundamentals Rating: 0 out of 5 stars0 ratingsFastAPI Essentials: Definitive Reference for Developers and Engineers Rating: 0 out of 5 stars0 ratings
Programming For You
SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsLearn NodeJS in 1 Day: Complete Node JS Guide with Examples Rating: 3 out of 5 stars3/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5The 1 Page Python Book Rating: 2 out of 5 stars2/5C All-in-One Desk Reference For Dummies Rating: 5 out of 5 stars5/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Hacking Electronics: Learning Electronics with Arduino and Raspberry Pi, Second Edition Rating: 0 out of 5 stars0 ratingsExcel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsPython Data Structures and Algorithms Rating: 5 out of 5 stars5/5
Reviews for Mastering Flask Web and API Development
0 ratings0 reviews
Book preview
Mastering Flask Web and API Development - Sherwin John C. Tragura
Mastering Flask Web and API Development
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Kaustubh Manglurkar
Publishing Product Manager: Bhavya Rao
Book Project Manager: Sonam Pandey
Senior Editor: Anuradha Joglekar
Technical Editor: Reenish Kulshrestha
Copy Editor: Safis Editing
Proofreader: Anuradha Joglekar
Indexer: Rekha Nair
Production Designer: Prashant Ghare
DevRel Marketing Coordinator: Anamika Singh
Publication date: August 2024
Production reference: 2220724
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-83763-322-7
www.packtpub.com
To my lola, Lila Calleja, my mama, Lorna Calleja, and the loving memory of my tatay, Cesar, for showing me what life should be to become successful. To Owen Estabillo, for being a partner from the start, through the thick and thin of life.
– Sherwin John C. Tragura
Contributors
About the author
Sherwin John C. Tragura is currently a subject matter expert and technical consultant in a company in the Philippines. He has been part of many development teams customizing Alfresco DMS/RMS and building Java and Python standalone and web projects. He is also a certified professional and bootcamp technical trainer who has delivered technical training on Java, Jakarta EE, C#, .NET, Python, Node frameworks, and other customized training courses since 2011. He was also associated as a lecturer with the Dela Salle University-Manila, Colegio de San Juan de Letran-Calamba, and the University of the Philippines-Los Banos. He is the author of other Packt books, including Spring MVC Blueprints, Spring 5 Cookbook, and Building Python Microservices with FastAPI.
First and foremost, I want to thank Packt and my team for the patience and understanding given to me for this project. A huge thanks to my cousin, Rhonalyn, for the road trips; Shon-Shon, my cute and puffy nephew, for making me laugh; and Owen, for being there during stressful days and coffee breaks. And to the Force for the blessings.
For my readers, to master something, you need to first learn how to share that something with others.
About the reviewers
Zubair Khan is a software engineer and the visionary behind Tech Marquee, a company dedicated to reimagining web services. His expertise in Python, Flask, FastAPI, Django, React, Vue, AWS, MySQL, Postgres, MongoDB, CI/CD, and BI analysis is globally recognized. An IGNITE Pakistan awardee for his driver drowsiness detection system using deep learning, Zubair is dedicated to quality and innovation, using SonarQube and Jenkins to ensure excellence. Inspired by the principles of decentralization, he strongly advocates for the open source community and regularly contributes with articles on AI, web development, and data science.
Vicente Marçal is a highly motivated self-taught Python developer with over 7 years of experience and is passionate about crafting clean, efficient, and scalable software solutions. Skilled in web development using popular frameworks such as Django, Flask, and FastAPI, he has a proven track record of delivering successful projects of varying sizes and complexities.
Table of Contents
Preface
Part 1: Learning the Flask 3.x Framework
1
A Deep Dive into the Flask Framework
Technical requirements
Setting up the project baseline
Installing the latest Python version
Installing the Visual Studio (VS) Code editor
Creating the virtual environment
Installing the Flask 3.x libraries
Creating the Flask project
Creating routes and navigations
Creating static URLs
Assigning multiple URLs
Applying path variables
Assigning URLs externally
Implementing class-based views
Managing request and response data
Retrieving the request object
Creating the response object
Implementing page redirection
Implementing view templates
Creating web forms
Building the data layer with PostgreSQL
Setting up database connectivity
Implementing the repository layer
Creating the service layer
Managing the project structure
Building the directory structure
Setting up a development environment
Implementing the main.py module
Creating environment variables
Summary
2
Adding Advanced Core Features
Technical requirements
Structuring huge and scalable projects
Using the application factory
Using the Blueprint
Utilizing both the application factory and the Blueprint
Applying object-relational mapping (ORM)
Setting up the database connectivity
Building the model layer
Implementing the repository layer
Configuring the logging mechanism
Creating user sessions
Managing session data
Clearing all session data
Applying flash messages
Utilizing some advanced Jinja2 features
Applying with-blocks and macros
Applying filters
Adding comments
Implementing error-handling solutions
Using the register_error_handler method
Applying the @errorhandler decorator
Creating custom exceptions
Managing built-in exceptions
Triggering the error handlers
Adding static resources
Accessing the assets in the templates
Summary
3
Creating REST Web Services
Technical requirements
Setting up a RESTful application
Implementing API endpoints
Managing requests and responses
Utilizing response encoders and decoders
Filtering API requests and responses
Handling exceptions
Consuming API endpoints
Summary
4
Utilizing Flask Extensions
Technical requirements
Applying database migration with Flask-Migrate
Installing Flask-Migrate and Flask-SQLAlchemy
Setting up the Alembic configuration
Creating the migrations
Applying the database changes
Designing the UI using Bootstrap-Flask
Setting up the UI module
Applying the Bootstrap files and assets
Utilizing built-in features
Building Flask forms with Flask-WTF
Creating the form models
Rendering the forms
Applying CSRF
Submitting the form
Validating form fields
Building RESTful services with Flask-RESTful
Implementing session handling with Flask-Session
Applying caching using Flask-Caching
Adding mail features using Flask-Mail
Summary
Part 2: Building Advanced Flask 3.x Applications
5
Building Asynchronous Transactions
Technical requirements
Creating asynchronous Flask components
Implementing asynchronous views and endpoints
Implementing the async before_request and after_request handlers
Creating asynchronous error handlers
Building an asynchronous SQLAlchemy repository layer
Setting up the DB connectivity
Building the asynchronous repository layer
Utilizing the asynchronous DB transactions
Implementing async transactions with asyncio
Utilizing asynchronous signal notifications
Constructing background tasks with Celery and Redis
Setting up the Celery task queue
Installing the Redis DB
Setting up the Celery client configuration
Creating the Client instance
Implementing the Celery tasks
Running the Celery worker server
Utilizing the Celery tasks
Building WebSockets with asynchronous transactions
Creating the client-side application
Creating server-side transactions
Creating a Flask API client application
Implementing asynchronous SSE
Implementing the message publisher
Building the server push
Applying reactive programming with RxPy
Choosing Quart over Flask 2.x
Summary
6
Developing Computational and Scientific Applications
Technical requirements
Uploading CSV and XLSX documents for computing
Using the pandas module for data and graphical analysis
Utilizing the DataFrame
Rendering graphs and charts using matplotlib
Rendering multiple line graphs
Rendering a pie chart from a CSV file
Rendering multiple Axes plots
Implementing symbolic computation with visualization
Solving linear equations
Solving non-linear formulas
Finding solutions for a linear system
Plotting mathematical expressions
Creating and rendering LaTeX documents
Rendering LaTeX documents
Creating LaTeX documents
Building graphical charts with frontend libraries
Plotting with Chart.js
Creating graphs with Plotly
Visualizing data using Bokeh
Building real-time data plots using WebSocket and SSE
Utilizing the WebSocket
Using SSE
Using asynchronous background tasks for resource-intensive computations
Incorporating Julia packages with Flask
Creating a custom Julia package
Configuring Julia accessibility in a Flask project
Implementing Julia functions in the package
Creating the Julia service module
Summary
7
Using Non-Relational Data Storage
Technical requirements
Managing non-relational data using Apache HBase
Designing HBase tables
Setting up the baseline requirements
Configuring Apache Hadoop
Configuring Zookeeper and Apache HBase
Setting up the HBase shell
Creating the HBase tables
Establishing an HBase connection
Building the repository layer
Applying a repository to API functions
Running the thrift server
Utilizing the column storage of Apache Cassandra
Designing Cassandra tables
Installing and configuring Apache Cassandra
Running the CQL shell client
Establishing a database connection
Building the model layer
Implementing the repository layer
Storing search data in Redis
Installing the Redis server
Understanding the Redis database
Establishing a database connection
Implementing the model layer
Building the repository layer
Handling BSON-based documents with MongoDB
Installing and configuring the MongoDB server
Establishing a database connection
Building the model layer
Implementing the repository
Managing key-based JSON documents with Couchbase
Installing and configuring the database instance
Setting up the server connection
Creating the repository layer
Establishing a data relationship with Neo4J
Installing Neo4J Desktop
Establishing a connection to the database
Implementing the repository
Summary
8
Building Workflows with Flask
Technical requirements
Building workflows with Celery tasks
Creating task signatures
Utilizing Celery primitives
Implementing a sequential workflow
Passing inputs to signatures
Running independent and parallel tasks
Using callbacks to manage task results
Creating BPMN and non-BPMN workflows with SpiffWorkflow
Setting up the development environment
Creating a BPMN diagram
Implementing the BPMN workflow
Distinguishing between workflow specifications and instances
Identifying between task specifications and instances
Passing form data to UserTask
Adding input variables to ScriptTask
Managing the result of the workflow
Implementing a non-BPMN workflow
Running a non-BPMN workflow
Building service tasks with the Zeebe/Camunda platforms
Setting up the Zeebe server
Installing the pyzeebe library
Creating a BPMN diagram for pyzeebe
Creating a pyzeebe worker
Implementing the pyzeebe client
Building API endpoints
Using Airflow 2.x in orchestrating API endpoints
Installing and configuring Airflow 2.x
Creating tasks
Utilizing Airflow built-in REST endpoints
Implementing workflows using Temporal.io
Setting up the environment
Implementing activities and a workflow
Building a worker
Running activities
Summary
9
Securing Flask Applications
Technical requirements
Adding protection from web vulnerabilities
Applying form validation to request data
Sanitizing form inputs
Securing response data
Rendering Jinja2 variables
Adding security response headers
Using HTTPS to run request/response transactions
Managing user credentials
Encrypting user passwords
Using sqlalchemy_utils for encrypted columns
Utilizing the server-side sessions
Implementing web form authentication
Preventing CSRF attacks
Implementing user authentication and authorization
Utilizing the Flask-HTTPAuth module
Utilizing the Authlib module
Controlling the view or API access
Summary
Part 3: Testing, Deploying, and Building Enterprise-Grade Applications
10
Creating Test Cases for Flask
Technical requirements
Creating test cases for web views, repository classes, and native services
Testing the model classes
Testing the repository classes
Testing the native services
Testing the view functions
Applying the monkey patching
Creating test cases for components in application factory and Blueprints
Testing ORM transactions
Testing API functions
Implementing exception testing
Creating test cases for asynchronous components
Testing asynchronous views and API endpoint function
Testing the asynchronous repository layer
Testing Celery tasks
Testing asynchronous file upload
Creating test cases for secured API and web components
Testing secured API functions
Testing HTTP Basic authentication
Testing web logins
Creating test cases for MongoDB transactions
Creating test cases for WebSockets
Summary
11
Deploying Flask Applications
Technical requirements
Getting ready for deployment
Classes and methods for the standard Peewee ORM
Classes and methods for the Async Peewee ORM
Running the application on Gunicorn and uWSGI
Using the Gunicorn server
Using uWSGI
Deploying the application to Uvicorn
Deploying the application on the Apache HTTP Server
Deploying the application on Docker
Using Docker Compose
Deploying the application on Kubernetes
Creating an API gateway using NGINX
Summary
12
Integrating Flask with Other Tools and Frameworks
Technical requirements
Implementing microservice applications involving FastAPI, Django, and Tornado
Adding the Flask sub-application
Adding the FastAPI sub-application
Adding the Django sub-application
Putting it all together with Tornado
Implementing Flask instrumentation
Applying OpenAPI 3.x specification with Swagger
Providing REST services to a Flutter mobile application
Consuming REST endpoints with a React application
Building a GraphQL application
Summary
Index
Other Books You May Enjoy
Preface
Since 2009, the time I started using the framework for software project development, Flask remains a powerful, lightweight, seamless, and easy-to-use Python framework for API and web application development. The non-boilerplate WSGI framework has grown its support, and now it has several utilities to support different features, even implementing asynchronous components.
The flexibility of Flask makes it the best tool for building various applications, from small-scale e-commerce to middle-scale enterprise applications, as per my experience. The framework is also an ideal choice for implementing scientific applications, such as laboratory calibration and monitoring systems, weather forecasting systems, and many other applications that require XLSX and CSV automation and report and graph generation.
This book showcases Flask 3 and how it translates and upgrades all my previous software development specifications with previous Flask versions using up-to-date features. I hope the book can help you understand Flask 3 and apply its components to create workarounds and provide solutions to challenging real-world problems.
Who this book is for
This book is for proficient Python developers seeking a deeper understanding of the Flask framework as a solution for tackling enterprise challenges. It is also a great resource for Flask-savvy readers eager to learn more about the framework’s advanced capabilities and new features.
What this book covers
Chapter 1
, A Deep Dive into the Flask Framework, introduces Flask as a simple and lightweight Python framework for web applications and showcases the installation of Flask 3 to jumpstart web application development using a non-standard project directory structure with basic Flask features, such as the view functions, class-based views, database connectivity, built-in Werkzeug server and libraries, and custom environment variables.
Chapter 2
, Adding Advanced Core Features, provides the Flask 3 core features of web applications, such as session management, data management using Object Relational Mapping (ORM), view rendition using Jinja2 templates, message flashing, error handling, software logging, adding static contents, and applying blueprint and application factory design to project structuring.
Chapter 3
, Creating REST Web Services, introduces API development using Flask 3 with request and response handling, implementation of JSON encoders and decoders for parsing the incoming request body and outgoing response, access of request and application context using @before_request and @after_request events, exception handling, and implementation of client applications to consume the REST services.
Chapter 4
, Utilizing Flask Extensions, discusses how to save development time and effort by using helpful and efficient Flask modules in replacement to their ground-up equivalents, such as Flask-Session for non-browser-based session handling, Bootstrap-Flask for providing the presentation layer, Flask-WTF for building model-based web forms, Flask-Caching for creating cache, Flask-Mail for sending emails, and Flask-Migrate for building the database schema from data models.
Chapter 5
, Building Asynchronous Transactions, explains the asynchronous features of Flask 3, which includes creating asynchronous view and API endpoint functions, implementing an asynchronous repository layer using SQLAlchemy, building asynchronous background tasks using Celery and Redis, implementing WebSocket and Server-Sent Events (SSE) with asyncio utilities, applying asynchronous signals for triggering transactions, and applying reactive programming, and introduces Quart as the ASGI-variant of Flask 3.
Chapter 6
, Developing Computational and Scientific Applications, discusses the use of Flask in building scientific applications with XLSX and CSV uploading and tabular and graphical reports using popular Python libraries such as numpy, pandas, matplotlib, seaborn, scipy, and sympy, JavaScript libraries such as Chart.js, Bokeh, and Plotly, LaTeX tools for PDF generation, Celery and Redis for time-expensive background computations, and other scientific tools, such as Julia.
Chapter 7
, Using Non-Relational Data Storage, explains how Flask can manage non-relational and big data using popular NoSQL databases, such as Apache HBase/Hadoop, Apache Cassandra, Redis, MongoDB, Couchbase, and Neo4J.
Chapter 8
, Building Workflows with Flask, discusses how to implement non-BPMN and BPMN workflows with Flask 3, using Celery and Redis, SpiffWorkflow, Zeebe server from Camunda, Airflow 2, and Temporal.io.
Chapter 9
, Securing Flask Applications, provides various ways to secure web-based and API-based Flask applications, such as implementing authentication and authorization mechanisms using HTTP Basic, Digest, and Bearer-token authentication schemes, OAuth2 authorization schemes, and Flask-Login; utilizing encoding/decoding and encryption/decryption libraries to protect user credentials; applying form validation and data sanitation to avoid different web attacks; replacing HTTP with the secured HTTPS to run applications; and controlling response headers to restrict or limit user access.
Chapter 10
, Creating Test Cases for Flask, provides techniques for testing with or without mocking the Flask 3 components, such as model classes, repository transactions, native services, view and API endpoint functions, database connectivity, asynchronous processes, and WebSockets, using the PyTest framework.
Chapter 11
, Deploying Flask Applications, discusses different options for deploying and running a web or API application, which includes using Gunicorn for standard and asynchronous Flask applications, uWSGI, the Docker platform through Docker Compose and Kubernetes deployments, and Apache HTTP Server.
Chapter 12
, Integrating Flask with Other Tools and Frameworks, provides solutions for integrating Flask applications into different popular tools, such as GraphQL, React client applications, and Flutter mobile applications, and for building sub-applications built from Django, FastAPI, Tornado, and Flask frameworks within a microservice application using Flask’s interoperability feature.
To get the most out of this book
To fully grasp the initial chapters of the book, you should have a background in Python web and API programming using any framework or a little background in Flask. But having a background in creating scripts using standard Python can also help you at least understand the first chapter, which is a jumpstart on how to use the Python language to build a web application using basic Flask concepts. Experienced developers can use the book to enrich their Flask experience further with the new utility classes and functions of the Flask 3.x framework.
Optionally, it would help if you use a licensed Microsoft Excel to open XLSX and CSV files for Chapter 6
and Foxit PDF Reader for the generated PDF files.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
We advise you to install the specified Python version to avoid unexpected errors related to version incompatibilities. Also, it will be advisable to download and read the code from GitHub while reading the chapters to understand the discussions. The code in GitHub is just a prototype and may serve as a guide to build your versions of the applications.
Download the example code files
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Mastering-Flask-Web-Development
. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/
. Check them out!
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: However, to fully use this feature, install the flask[async] module using the following pip command:
A block of code is set as follows:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
DB_URL = postgresql://
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
engine = create_engine(DB_URL) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
def init_db():
import modules.model.db
Any command-line input or output is written as follows:
pip install flask[async]
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: Clicking this option will lead you to the Enter interpreter path… menu command and, eventually, to the Find… option.
Tips or important notes
Appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected]
and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata
and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected]
with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com
.
Share Your Thoughts
Once you’ve read Mastering Flask Web and API Development, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page
for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Download a free PDF copy of this book
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your e-book purchase not compatible with the device of your choice?
Don’t worry!, Now with every Packt book, you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the following link:
https://packt.link/free-ebook/9781837633227
Submit your proof of purchase.
That’s it! We’ll send your free PDF and other benefits to your email directly.
Part 1:Learning the Flask 3.x Framework
In this part, you will learn and understand the basic and core components to implement Flask-accepted web and API applications, including using the Blueprints and application factory functions to build the proper Flask project structure. This part will also teach you how to integrate Flask into the PostgreSQL databases using the psycopg2 and asyncpg drivers and implement the repository layers of your application using the native database driver or the object-relational mapping (ORM) tool. Moreover, you will learn how to use external Flask modules to implement the features of your applications without spending much time and effort.
This part includes the following chapters:
Chapter 1
, A Deep Dive into the Flask Framework
Chapter 2
, Adding Advanced Core Features
Chapter 3
, Creating REST Web Services
Chapter 4
, Utilizing Flask Extensions
1
A Deep Dive into the Flask Framework
Flask is a Python web framework that was created by Armin Ronacher to solve both web-based and API-related requirements that need a rapid development approach. It is a lightweight framework with helper classes and methods, a built-in server, a debugger, and a reloader, all of which are required for building scalable web applications and web services.
Unlike the Django framework, Flask is minimalistic and slimmer in that it requires more experience in using Python to craft various coding techniques and workarounds to implement its components. It is more open-ended and extensible than the full-stack Django, which is more friendly to newbies because of its easy-to-build projects and reusable components.
This first chapter will showcase the essential task itineraries that cover the initial components and base features of Flask 3.x that are essential in initiating our web development.
In this chapter, we will cover the following development tasks:
Setting up the project baseline
Creating routes and navigations
Managing the requests and response data
Implementing view templates
Creating web forms
Building the data layer with PostgreSQL
Managing the project structure
Technical requirements
The first chapter will focus on building a prototype for an Online Personal Counseling System that simulates a face-to-face consultation between a patient and a counselor while highlighting the base components of Flask 3.x. The application will cover modules such as managing users, questionnaires, and some reports. The code for this chapter can be found at https://github.com/PacktPublishing/Mastering-Flask-Web-Development/tree/main/ch01
.
Setting up the project baseline
Gathering and studying the system requirements for the development environment for the proposed project is essential. Some of these requirements include the correct versions of the installers and libraries, the appropriate servers, and the inclusion of other essential dependencies. We have to perform various setups before kicking off our projects.
Installing the latest Python version
All our applications will run on the Python 11 environment for faster performance. The updated Python installer for all operating systems is available at https://www.python.org/downloads/
.
Installing the Visual Studio (VS) Code editor
The Django framework has a django-admin command that generates a project structure, but Flask does not have that. We can use a terminal console or a tool such as the Visual Studio (VS) Code editor that can help developers create a Flask project. The VS Code installer is available at https://code.visualstudio.com/download
.
After installing the VS Code editor, we can create a filesystem folder through it and start a Flask project. To create the folder, we should go to the Open Folder option under File or use the Ctrl + K + O shortcut to open the Open Folder mini-window. Figure 1.1 shows a sample process of creating a Flask project using the editor:
Figure 1.1 – Creating a Flask project folder using the VS Code editorFigure 1.1 – Creating a Flask project folder using the VS Code editor
Creating the virtual environment
Another aspect of developing a Flask project is having a repository called a virtual environment that can hold its libraries. It is a mechanism or a tool that can manage all dependencies of a project by isolating these dependencies from the global repository and other project dependencies. The following are the advantages of using this tool in developing Flask-based applications:
It can avoid broken module versions and collisions with other existing similar global repository libraries.
It can help build a dependency tree for the project.
It can help ease the deployment of applications with libraries to both physical and cloud-based servers.
A Python extension named virtualenv is required to set up these virtual environments. To install the extension, run the following command in the terminal:
pip install virtualenv
After this installation, we need to run python virtualenv -m ch01-01 to create our first virtual environment for our Flask project. Figure 1.2 shows a snapshot of creating our ch01-env repository:
Figure 1.2 – Creating a virtual environmentFigure 1.2 – Creating a virtual environment
The next step is to open the project and link it to the virtual environment created for it. Pressing Ctrl + Shift + P in VS Code will open the Command Palette area. Here, we can search for Python: Select Interpreter. Clicking this option will lead you to the Enter interpreter path… menu command and eventually to the Find… option. This Find… option will help you locate the virtual environment’s Python.exe file in the /Scripts folder. Figure 1.3 shows a snapshot of locating the Python interpreter in the repository’s /Scripts folder:
Figure 1.3 – Locating the Python interpreter of the virtual environmentFigure 1.3 – Locating the Python interpreter of the virtual environment
Afterward, the virtual environment must be activated for the project to utilize it. You must run /Scripts/activate.bat in Windows or /bin/activate in Linux through the editor’s internal console. Upon activation, the terminal should show the name of the virtual environment in its prompt (for example, (ch01-env) C:\).
Installing the Flask 3.x libraries
The integrated terminal of VS Code will appear after right-clicking the explorer portion of the editor, which leads to the Open in Integrated Terminal option. Once it appears on the lower right-hand side, activate the virtual environment first, then install all Flask dependencies into the repository by running pip install flask.
Once all the requirements are in place, we are ready to create our baseline application.
Creating the Flask project
The first component that must be implemented in the main project folder (that is, ch01) is the application file, which can be main.py or sometimes app.py. This component will become the top-level module the Flask will recognize when the server starts. Here is the baseline application file for our Online Personal Counseling System prototype:
from flask import Flask app = Flask(__name__)
@app.route('/', methods = ['GET'])
def index():
return This is an online … counseling system (OPCS)
if __name__ == '__main__':
app.run(debug=True)
Let’s dissect and scrutinize the essential parts of the given main.py file:
An imported Flask class from the flask package plays a considerable role in building the application. This class provides all the utilities that implement the Werkzeug specifications, which include features such as managing the requests and the responses of every route, redirecting pages, handling form data, accessing and creating cookies, parsing custom and built-in headers, and even providing debuggers for the development environment. In other words, the Flask instance is the main element in building a Web Server Gateway Interface (WSGI)-compliant application.
Werkzeug
Werkzeug is a WSGI-based library or module that provides Flask with the necessary utilities, including a built-in server, for running WSGI-based applications.
The imported Flask instance must be instantiated once per application. The __name__ argument must be passed to its constructor to provide Flask with a reference to the main module without explicitly setting its actual package. Its purpose is to provide Flask with the reach it needs in providing the utilities across the application and to register the components of the project to the framework.
The if statement tells the Python interpreter to run Werkzeug’s built-in development server if the module is main.py. This line validates the main.py module as the top-level module of the project.
app.run() calls and starts the built-in development server of Werkzeug. Setting its debug parameter to True sets development or debug mode and enables Werkzeug’s debugger tool and automatic reloading. Another way is to create a configuration file that will set FLASK_DEBUG to True. We can also set development mode by running main.py using the flask run command with the --debug option. Other configuration approaches before Flask 3.0, such as using FLASK_ENV, are already deprecated.
Running the python main.py command on the VS Code terminal will start the built-in development server and run our application. A server log will be displayed on the console with details that include the development mode, the debugger ID, and the URL address. The default port is 5000, while the host is localhost.
Now, it is time to explore the view functions of our Flask application. These are the components that manage the incoming requests and outgoing responses.
Creating routes and navigations
Routing is a mapping of URL pattern(s) and other related details to a view function that’s done using Flask’s route decorators. On the other hand, the view function is a transaction that processes an incoming request from the clients and, at the same time, returns the necessary response to them. It follows a life cycle and returns an HTTP status as part of its response.
There are different approaches to assigning URL patterns to view functions. These include creating static and dynamic URL patterns, mapping URLs externally, and mapping multiple URLs to a view function.
Creating static URLs
Flask has several built-in route decorators that implement some of its components, and @route decorator is one of these. @route directly maps the URL address to the view function seamlessly. For instance, @route maps the index() view function presented in the project’s main.py file to the root URL or /, which makes index() the view function of the root URL.
But @route can map any valid URL pattern to any view function. A URL pattern is accepted if it follows the following best practices:
All characters must be in lowercase.
Use only forward slashes to establish site hierarchy.
URL names must be concise, clear, and within the business context.
Avoid spaces and special symbols and characters as much as possible.
The following home() view function renders an introductory page of our ch01 application and uses the URL pattern of /home for its access:
@app.route('/home') def home():
return '''
Online … Counseling System (OPCS)
This is a template of a web-based counseling
application where counselors can … … …
'''
Now, Flask accepts simple URLs such as /home or complex ones with slashes and path-like hierarchy, including these multiple URLs.
Assigning multiple URLs
A view function can have a stack of @route decorators annotated on it. Flask allows us to map these valid multiple URLs if there is no conflict with other view functions and within that stack of @route mappings. The following version of the home() view function now has three URLs, which means any of these addresses can render the home page:
@app.route('/home') @app.route('/information') @app.route('/introduction') def home():
return '''
Online … Counseling System (OPCS)
… … … … …
'''
Aside from