Full-Stack Flask and React - Olatunde Adedeji - E-Book

Full-Stack Flask and React E-Book

Olatunde Adedeji

0,0
28,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Developing an interactive, efficient, and fast enterprise web application requires both the right approach and tooling. If you are a web developer looking for a way to tap the power of React’s reusable UI components and the simplicity of Flask for backend development to develop production-ready, scalable web apps in Python, then this book is for you.
Starting with an introduction to React, a JavaScript library for building highly interactive and reusable user interfaces, you’ll progress to data modeling for the web using SQLAlchemy and PostgreSQL, and then get to grips with Restful API development. This book will aid you in identifying your app users and managing access to your web application. You’ll also explore modular architectural design for Flask-based web applications and master error-handling techniques. Before you deploy your web app on AWS, this book will show you how to integrate unit testing best practices to ensure code reliability and functionality, making your apps not only efficient and fast but also robust and dependable.
By the end of this book, you’ll have acquired deep knowledge of the Flask and React technology stacks, which will help you undertake web application development with confidence.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 516

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Full-Stack Flask and React

Learn, code, and deploy powerful web applications with Flask 2 and React 18

Olatunde Adedeji

BIRMINGHAM—MUMBAI

Full-Stack Flask and React

Copyright © 2023 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: Rohit Rajkumar

Publishing Product Manager: Bhavya Rao

Senior Content Development Editor: Abhishek Jadhav and Feza Shaikh

Technical Editor: Simran Ali

Copy Editor: Safis Editing

Project Coordinator: Aishwarya Mohan

Proofreader: Safis Editing

Indexer: Tejal Soni

Production Designer: Aparna Bhagat

Marketing Coordinator: Anamika Singh, Namita Velgekar, and Nivedita Pandey

First published: October 2023

Production reference: 2260923

Packt Publishing Ltd

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-80324-844-8

www.packtpub.com

This book is dedicated to my loving wife, Doyin, and my adorable daughters, Michelle and Mabel, with all my heart. Your unwavering support, love, and understanding have been the driving force behind my pursuit of knowledge and passion for technology.

– Olatunde Adedeji

Contributors

About the author

Olatunde Adedeji is a seasoned web developer with over 15 years of experience in developing dynamic and detail-oriented enterprise web applications. As the co-founder and principal software engineer at Mowebsite, a web and mobile applications development company, Olatunde has honed his skills in modern web development approaches to develop scalable web applications.

Along with his extensive experience in developing, maintaining, and supporting mobile, web, and enterprise applications in Python, Go, and JavaScript, Olatunde has consistently delivered excellent services as a team lead, team member, or in a consultancy capacity. He has worked across industries such as healthcare, banking and finance, information technology, education, legal, and insurance.

Olatunde is proficient in application design and solution blueprinting, including mastery of application development tools such as Flask, Django, Gin, React, and Node.js. Olatunde actively learns and researches blockchain technology and its potential to transform industries. When not weaving the web and playing chess, Olatunde spends time with his wife, Adedoyin, and his two daughters, Michelle and Mabel.

About the reviewers

Tyron Goldschmidt is a full stack software engineer. He loves working in TypeScript and Python. He has professional experience on large frontend and backed projects and currently focuses on performance optimization at Dotdash Meredith. Before turning to software engineering, he was a philosophy professor, and he has authored and edited many books for top academic publishers.

David McConkey is a full stack software engineer from Ottawa, Canada. With a background in organizational behavior, he has a detail-oriented mind and honed problem-solving skills. Equipped with excellent knowledge of JavaScript/TypeScript, React, and Flask, among many other languages and frameworks, he is able to develop tools and applications that will satisfy any user.

Acknowledgment

Before we dive into the world of Full-Stack Flask and React, I want to take a moment to express my heartfelt gratitude to all the amazing guys who have played a part in bringing this book to life. Without their support, expertise, and encouragement, this project wouldn’t have been possible.

First, I want to thank my incredible family. Your unwavering love, patience, and understanding have been my rock throughout this entire journey. I am forever grateful for your constant encouragement and belief in me.

A big shout-out goes to the fantastic team at Packt Publishing. You folks have been phenomenal! I can’t thank my editors, Mark D’Souza and Abhishek Jadhav, enough for their sharp eyes, expert guidance, and unwavering support. Your attention to detail and dedication to excellence have truly elevated the quality of this book.

To my colleagues and mentors, thank you for sharing your wisdom and experience in the world of software development. Your expertise and criticism have shaped my understanding and approach in profound ways. I also want to thank Opeyemi Opanuga. Your incredible support and words of encouragement were instrumental to the success of this book.

I also want to extend my gratitude to the countless developers and open source contributors who have dedicated their time and effort to advancing these awesome technologies, Flask and React. Your commitment to the community and passion for innovation has not only inspired this book but has also propelled the growth of modern web applications.

Lastly, I want to express my deepest gratitude to you, the reader. Your curiosity, passion, and desire to learn are what fuel authors like me to share their knowledge and experiences. I truly hope that this book equips you with the tools, insights, and confidence to embark on your own exciting adventures in full stack web application development.

To each and every one of you who has contributed in some way, big or small, thank you from the bottom of my heart. Your support and involvement have been instrumental, and I am honored to have you by my side on this incredible journey.

With sincere appreciation,

-Olatunde Adedeji

Table of Contents

Preface

Part 1 – Frontend Development with React

1

Getting Full Stack Ready with React and Flask

Technical requirements

An introduction to full stack web development

Why should we choose React?

Setting up the development environment with React

Why should we choose Flask?

Setting up the development environment with Flask

Getting ready with Git

How does Git work?

Git versus GitHub

What will we build?

Summary

2

Getting Started with React

Technical requirements

Exploring a React project directory structure

Arrow functions in React

Understanding what destructuring is

Default and named exports

What is a React component?

Function components

Class components

Component life cycle

What are props?

Passing data as props

React state

Summary

3

Managing State with React Hooks

Technical requirements

What is a Hook in React?

Why use Hooks in React?

Using useState to develop stateful components

Passing state as props

Conditional rendering with state

Using useEffect to create side effects

Using useContext to manage global state in React applications

Understanding props drilling

Using useContext to solve the props drilling problem

Using useRef to directly access DOM elements and persist state values

Using useReducer for state management

Using useMemo to improve performance

Prevents unnecessary component re-rendering

Using useCallback to avoid re-rendering functions

Using custom Hooks for code reusability

Summary

4

Fetching Data with React APIs

Technical requirements

Fetching data using the Fetch API in React

Fetching data using async/await syntax

Fetching data using Axios

Fetching data using the React Query in React

Summary

5

JSX and Displaying Lists in React

Technical requirements

What is JSX?

JSX versus HTML

How JSX abstracts JavaScript

Event handling in React

Displaying lists in React

Using key and id in JSX

Nesting lists in JSX

Looping over objects in JSX

Using Object.keys()

Using Object.values()

Using Object.entries()

Example of looping with Object.keys

Summary

6

Working with React Router and Forms

Technical requirements

Routing with React Router

Routers

Components

Hooks

Adding React Router in React

Setting up the routing configuration

Adding links

Adding a nested route

Handling dynamic routes

Using useParams

Using useNavigate

Using forms in React

Controlled and uncontrolled form components

Controlled form

Uncontrolled form

Handling user input – Input, TextArea, and Select

Input

TextArea

Select

Validating and sanitizing users’ data in React

Implementing form validation

Summary

7

React Unit Testing

Technical requirements

What is software testing?

Introducing Jest

Setting up the Jest environment

Writing tests in Jest

Unit-testing React components

Writing a unit test for a stateless component

Writing a unit test for a stateful component

TDD

Writing a single test case

Writing minimal code that satisfies the test and making it pass

Code refactoring

Summary

Part 2 – Backend Development with Flask

8

SQL and Data Modeling

Technical requirements

What is the relational data model?

Exploring the different database relationships

One-to-one (1:1) relationship

One-to-many (1:M) relationship

Many-to-many (M:M) relationship

Setting up PostgreSQL, SQLAlchemy, and Alembic

Setting up PostgreSQL

Setting up SQLAlchemy

Setting up Alembic

Understanding database concepts for Flask applications

RDBMS

DB-APIs

Client–server model interaction

Understanding SQLAlchemy ORM basics

The SQLAlchemy engine

SQLAlchemy connection pools

SQLAlchemy dialect

SQLAlchemy data types – mapping between tables and classes

Modeling data for a speakers’ conference web application

Sending data to the PostgreSQL database from a Flask app

Migration with Alembic

Running migrations

Summary

9

API Development and Documentation

Technical requirements

What is an API?

Why use an API in web development

Endpoint and payload anatomy

Understanding the endpoint structure

Understanding the payload structure

Understanding HTTP requests/responses

Request line

HTTP responses

Understanding HTTP status codes

REST API design principles

Client-server

Statelessness

Caching

Uniform interface

Layered system

Code on demand (optional)

Implementing a REST API in a Flask application

Defining the application resources

Defining the API endpoints

Implementing the API endpoints

JSONifying response data

Adding query parameters to endpoints

Passing variables to an endpoint

API interaction with a database via CRUD operations

Creating a venue resource

Returning lists of venues

Returning a single venue resource

Updating a single venue resource

Deleting a single venue resource

API documentation

Testing and documenting with Postman

Summary

10

Integrating the React Frontend with the Flask Backend

Technical requirements

The Bizza application structure

Application overview

Breaking down the code structure into frontend and backend

Configuring the React frontend for API consumption

Making Flask backend-ready

Handling forms in React and Flask

Troubleshooting tips for the React frontend and the Flask backend

Summary

11

Fetching and Displaying Data in a React-Flask Application

Technical requirements

Fetching and displaying data – the React-Flask approach

Retrieving the speakers’ list from Flask

Displaying data in React

Adding data to a database – the React–Flask approach

Adding data to Flask

Adding the speaker data to the backend using the CreateSpeaker component

Editing data – the React–Flask approach

Editing data in Flask

Displaying the edited data in React

Deleting data from a database – the React–Flask approach

Handling delete requests in Flask

Handling delete requests in React

Managing pagination in a React–Flask application

Summary

12

Authentication and Authorization

Technical requirements

Understanding the fundamentals of information security

Defining authentication and the authentication role in web application

Implementing password security and hashing passwords

Understanding access and authorization in web application development

Adding authentication to your Flask application

Flask backend

React frontend

Identifying system users and managing their information

Session management

Flask backend

React Frontend

Creating a password-protected dashboard

Flask backend

React frontend

Implementing flash messages in Flask

Flask backend

React frontend

Summary

13

Error Handling

Technical requirements

Using the Flask debugger

Creating error handlers

Flask backend

React frontend

Creating custom error pages

Tracking events in your application

Sending error emails to administrators

Summary

14

Modular Architecture – Harnessing the Power of Blueprints

Technical requirements

Understanding the benefits of modular architecture in web development

Understanding Flask Blueprints

Setting up a Flask application with Blueprints

Structuring Blueprint Flask applications

Defining models and Blueprint modules

Registering the Blueprints

Handling the React frontend with Flask Blueprints

Summary

15

Flask Unit Testing

Technical requirements

Unit testing in Flask applications

FIRST

RITE

3A

Introducing Pytest

Setting up Pytest

Basic syntax, structures, and features of Pytest

Using fixtures

Parameterizing in pytest

Mocking external dependencies in pytest

Writing unit tests

Unit-testing user registration

Unit-testing user login

Testing JSON APIs

Testing speaker data creation

Updating the speaker data object

Testing the deletion of the speaker data object

Test-driven development with Flask

Defining the feature

Writing a failed test case

Implementing the minimal amount of code to pass the test

Running the test and ensuring it passes

Refactoring the code

Writing additional tests

Handling exceptions

Summary

16

Containerization and Flask Application Deployment

Technical requirements

What is containerization?

Introducing Docker

Creating a Flask application

Creating a Dockerfile

Building the Docker image

Running the Docker container

Dockerizing React and Flask applications

Bizza frontend application with React

Bizza backend application with Flask

Understanding AWS ECR

Using Docker Compose

Deploying React and Flask applications to AWS Elastic Beanstalk

Summary

Index

Other Books You May Enjoy

Preface

Full-Stack Flask and React is designed to be your definitive guide to mastering the art of full stack web development using the dynamic duo – React and Flask.

Whether you’re a curious learner looking to learn both frontend and backend development or an experienced developer looking to expand your skill set, this book is structured to take you on a journey of building modern web applications.

In today’s digital age, building web applications that are interactive, dynamic, and responsive seamlessly to user interactions is crucial. Flask, an open source, micro-web framework written in Python, promotes fast development and embraces a clean and practical design approach. On the other hand, React, a JavaScript library to build user interfaces, offers an efficient and flexible way to create interactive UIs. By combining the power of React and the lightweight Flask framework, you’ll gain the ability to create modern full stack web applications with ease.

In this book, we’ll head first to components-driven development with React and explore the fundamentals of React. We will explore concepts such as components, props and state, JSX, managing state with React Hooks, data fetching in React, displaying lists, events handling, routing with React Router, and unit testing with Jest. Then, we’ll continue with full stack application development with Flask.

We’ll cover everything from SQL and data modeling to creating RESTful APIs, integrating a React client with the Flask backend, authentication and authorization, building modular and reusable Flask applications with Blueprint, error handling, unit testing in Flask, and understanding how your web applications can be deployed to the cloud. We’ll break down complex concepts into bite-sized pieces, provide clear explanations, and offer practical examples to ensure that you grasp each topic along the way. Whether you prefer learning by doing or enjoy deep dives into the inner workings of these technologies, we’ve got you covered.

Who this book is for

This book is ideal for developers who are interested in expanding their skills and knowledge in full stack web development. Whether you are a backend developer looking to learn frontend development with React or a frontend developer looking to learn server-side development with Flask, this book will provide you with the necessary guidance and practical examples to become proficient in full stack development.

Prior knowledge of basic HTML, CSS, JavaScript, and Python is required to benefit from this book.

Prior knowledge of basic HTML, CSS, JavaScript, and Python is required to benefit from this book.

What this book covers

This book is divided into 16 chapters, each focusing on essential concepts and practical techniques that you need to know to become proficient in full stack Flask web development with React.

Let’s take a closer look at the chapters:

Chapter 1, Getting Full Stack Ready with React and Flask, lays the groundwork for your full stack development journey. We will discuss the reasons for developing web applications with React and Flask. You’ll learn how to set up your development environment and install React and Flask. You will also learn the fundamentals of Git for source versioning and the project we will build in this book.

Chapter 2, Getting Started with React, introduces you to the basics of React, including exploring the React project structure, components, props, and state. We will discuss JavaScript concepts frequently used in React, such as destructuring, arrow functions, and default and named exports. You’ll build a solid foundation to create React applications.

Chapter 3, Managing State with React Hooks, delves into the power of React Hooks, such as useState, useEffect, useContext, useRef, useMemo, useCallback, and useReducer. You’ll discover how Hooks simplify state management and enable you to create more reusable and scalable code.

Chapter 4, Fetching Data with React APIs, focuses on fetching data in React applications. You’ll explore different techniques using React Query, async/await syntax, the Fetch API, and Axios; handle loading and error states; and implement caching for efficient data retrieval.

Chapter 5, JSX and Displaying Lists in React, covers the display of dynamic lists in React. You’ll learn how to use JSX as a bridge that connects JavaScript and HTML, implement nesting lists in JSX, loop over objects in JSX, and efficiently handle events in React.

Chapter 6, Working with React Router and Forms, guides you through the process of handling form input and validation, form submission, and implementing client-side routing using React Router.

Chapter 7, React Unit Testing, teaches you how to write comprehensive unit tests for React components using Jest and React Testing Library. You’ll gain confidence in the quality and reliability of your code.

Chapter 8, SQL and Data Modeling, introduces you to SQL and database modeling. You’ll learn how to set up databases, perform CRUD operations, and design efficient data models for your applications.

Chapter 9, API Development and Documentation, dives into the world of API development with Flask. You’ll understand RESTful API concepts, implement CRUD operations, and document your APIs effectively.

Chapter 10, Integrating the React Frontend with the Flask Backend, focuses on establishing communication between the React client and Flask backend. You’ll learn how to handle API calls and requests seamlessly.

Chapter 11, Fetching and Displaying Data in a React-Flask Application, explores the process of fetching and displaying data in a full stack React-Flask application. You’ll learn how to handle CRUD operations in a Flask-React application. You will also learn how to handle pagination in a Flask application.

Chapter 12, Authentication and Authorization, covers essential topics of user authentication and authorization. You’ll implement secure login and registration functionalities, identify system users and manage their information, learn about session management, create a password-protected resource, implement flash messages in Flask, and ensure the security of your application.

Chapter 13, Error Handling, delves into effective error-handling techniques in Flask applications. You’ll learn about different types of errors and how to use Flask debugger, create error handlers, create custom error pages, track events in your application, and send error emails to administrators.

Chapter 14, Modular Architecture – The Power of Blueprints, introduces the concept of modular architecture and blueprints in Flask. You’ll learn how to organize your code base into reusable modules and create a scalable application structure.

Chapter 15, Flask Unit Testing, explores the importance of unit testing in Flask applications. You’ll discover techniques to write comprehensive tests for your Flask components, ensuring the robustness of your backend.

Chapter 16, Containerization and Flask Application Deployment, concludes the book by covering the deployment and containerization of Flask applications. You’ll learn how to deploy your applications on servers and leverage containerization technologies for efficient deployment.

Each chapter is crafted to provide clear explanations to develop an interactive and efficient fast enterprise web application. You’ll gain a deep understanding of both React and Flask and become proficient in developing full stack web applications.

We hope this book serves as your essential definitive guide on your journey to becoming a skilled full stack web developer. Don’t hesitate to experiment, ask questions, and explore beyond the boundaries of the topics we cover. This book serves as a starting point, but the possibilities are endless. Let’s dive in and unlock the limitless potential of Full Stack Flask Web Development with React!

To get the most out of this book

We recommend using the latest version of Python. Flask supports Python 3.8+, React, and Node.js 16+, and Docker 23+ installation is required for this book. All code and examples in this book are tested using Flask 2.3.2 and React 18.2.

Software/hardware covered in the book

Operating system requirements

Python

Windows, macOS, or Linux

React

Windows, macOS, or Linux

Flask

Windows, macOS, or Linux

PostgreSQL

Windows, macOS, or Linux

Docker

Windows, macOS, or Linux

JavaScript

Windows, macOS, or Linux

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.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Full-Stack-Flask-and-React. 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: “Navigate to the Bizza folder after the setup has finished.”

A block of code is set as follows:

bizza/--node_modules/ --public/ ----index.html ----manifest.json

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

function App() {  return (     <div className="App">       <header className="App-header">         <img src={logo} className="App-logo" alt="logo" />         <p>           Edit <code>src/App.js</code> and save to reload.

Any command-line input or output is written as follows:

$ node -v$ npm -v

Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Log in and click on Repositories.”

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 Full- Stack Flask and React, 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 eBook 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 link below

https://packt.link/free-ebook/9781803248448

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1 – Frontend Development with React

Welcome to Part 1 of our book. In this part of the book, we will embark on an exciting journey into the world of frontend development with React. In this section, we will delve into the fundamental concepts and techniques that form the backbone of modern web development using the React library.

You will learn the key principles and best practices that will empower you to build dynamic and interactive user interfaces. We will cover the core concepts, from setting up your development environment to creating reusable components and managing state in React.

This part has the following chapters:

Chapter 1, Getting Full Stack-Ready with React and FlaskChapter 2, Getting Started with ReactChapter 3, Managing State with React HooksChapter 4, Fetching Data with React APIsChapter 5, JSX and Displaying Lists in ReactChapter 6, Working with React Router and FormsChapter 7, React Unit Testing