Title: Mastering Python Web Development with Flask: A
Comprehensive Guide
Table of Contents
Introduction
About This eBook
Prerequisites
Chapter 1: Getting Started with Flask
What is Flask?
Installation and Setup
Creating Your First Flask Application
Understanding Routes
Running Your Flask App
Debugging and Development Server
Chapter 2: Building Web Pages with HTML and Templates
HTML Basics
Integrating HTML with Flask
Jinja2 Templating Engine
Building Dynamic Web Pages
Template Inheritance
Chapter 3: Handling Forms and User Input
HTML Forms
Processing Form Data
Form Validation
CSRF Protection
File Uploads
Flash Messages
Chapter 4: Structuring Your Flask Application
Organizing Your Project
Blueprints
Application Configuration
Managing Static Files
Database Integration
Models and Databases
Chapter 5: User Authentication and Authorization
User Registration
User Login and Logout
Session Management
Role-Based Access Control
Password Hashing
Remember Me Functionality
Chapter 6: RESTful APIs with Flask
RESTful API Concepts
Creating API Endpoints
Handling HTTP Methods (GET, POST, PUT, DELETE)
Serialization and Deserialization
Authentication and Security
Chapter 7: Testing Flask Applications
Unit Testing
Functional Testing
Mocking Dependencies
Test Coverage
Continuous Integration
Chapter 8: Frontend Integration and JavaScript
Integrating JavaScript
AJAX Requests
Frontend Libraries and Frameworks
Creating Interactive Web Applications
Chapter 9: Deployment and Scaling
Preparing for Production
Choosing a Hosting Platform
Setting Up a Production Server
Load Balancing and Scaling
Performance Optimization
Chapter 10: Advanced Topics
WebSockets with Flask-SocketIO
Real-Time Applications
Web Security Best Practices
Internationalization and Localization
Caching and Optimization
Chapter 11: Building a Complete Project
Building a Blog Application
Extending the Blog Application
Enhancing Security
Deployment to a Production Server
Appendix A: Additional Resources
Recommended Books
Online Courses and Tutorials
Community Forums
Appendix B: Glossary
Key Terminology
Appendix C: Index
Conclusion
Recap of Key Concepts
Next Steps
About This eBook
Welcome to "Mastering Python Web Development with Flask: A
Comprehensive Guide." This eBook is designed to take you on a journey
from a complete novice to a proficient web developer using the Flask
framework in Python. Whether you're a beginner just starting your
programming journey or an experienced developer looking to explore web
development, this book has something to offer you.
Who Is This eBook For?
This eBook is for anyone interested in web development with Python and
Flask. It caters to a wide range of audiences:
Beginners: If you're new to web development or Python, we'll start
from the very basics and gradually introduce you to Flask and web
programming concepts.
Intermediate Developers: If you already have some Python
experience and are looking to expand your skills into web
development, this book will provide you with the knowledge and
hands-on experience you need.
Advanced Developers: Even if you're already familiar with Flask,
you'll find advanced topics and best practices that will help you
build robust, production-ready applications.
What You Will Learn
This eBook covers a wide range of topics, from the fundamental concepts
of web development to advanced techniques. Here's a brief overview of
what you can expect to learn:
Getting Started: We'll begin with the basics of Flask, showing you
how to set up your development environment and create your first
web application.
HTML and Templates: You'll learn the essentials of creating web
pages with HTML and integrating them with Flask using the Jinja2
templating engine.
Handling Forms: Discover how to handle user input through HTML
forms, validate data, and protect your application from common
security issues.
Structuring Your Application: We'll teach you how to organize
your Flask project, work with databases, and maintain a clean and
scalable codebase.
User Authentication and Authorization: You'll implement user
registration, login, and access control to secure your applications.
RESTful APIs: Learn how to build APIs for your applications,
enabling interaction with external services and mobile applications.
Testing and Deployment: Explore the best practices for testing
your applications and deploying them to production servers.
Frontend Integration and JavaScript: Integrate JavaScript into
your Flask applications and create interactive web pages.
Advanced Topics: Dive into advanced subjects like real-time
applications with WebSockets, web security best practices, and
internationalization.
Building a Complete Project: Put your knowledge to the test by
building a fully functional blog application from scratch.
Why Choose This eBook?
We've designed this eBook with a hands-on, practical approach. You'll find
clear explanations, real-world examples, and step-by-step tutorials to help
you grasp each concept. You'll also have access to downloadable code
samples and resources to facilitate your learning process.
By the end of this eBook, you'll have the skills and knowledge to develop
web applications with Flask, from simple personal projects to complex,
production-ready systems. Whether your goal is to build your own web-
based projects or pursue a career in web development, this eBook is an
excellent resource to get you there.
Let's Get Started!
Enough with introductions, it's time to dive into the exciting world of
Python web development with Flask. Whether you're a complete beginner
or a seasoned programmer, we believe you'll find this eBook to be a
valuable resource in your journey to mastering Flask and web
development.
We hope you enjoy the journey and find this eBook a helpful companion
on your path to becoming a proficient web developer.
Happy coding!
Prerequisites
Before you embark on your journey to master Python web development
with Flask, it's important to ensure that you have the following
prerequisites in place:
1. Basic Knowledge of Python: You should have a fundamental
understanding of Python, including variables, data types, functions,
control structures (if statements, loops), and basic object-oriented
programming concepts. If you're new to Python, consider
completing a Python programming tutorial or course to build a solid
foundation.
2. Python Installed: Make sure you have Python installed on your
computer. You can download the latest version of Python from the
official website (https://www.python.org/downloads/). We
recommend using Python 3.x, as this eBook focuses on Python 3.
3. Text Editor or Integrated Development Environment (IDE):
You'll need a text editor or IDE to write Python code. Popular choices
include Visual Studio Code, PyCharm, Sublime Text, or any other
code editor you're comfortable with.
4. Command Line Knowledge: Understanding how to use the
command line or terminal is essential, as you'll need it to run Flask
applications, set up virtual environments, and manage your project.
5. Basic HTML Knowledge (Optional): While we will cover HTML
basics, having some prior knowledge of HTML will be beneficial. If
you're new to HTML, don't worry; we'll guide you through the
essentials.
6. SQL (Structured Query Language) Knowledge (Optional): If
you plan to work with databases, a basic understanding of SQL can
be helpful. We'll cover database concepts in this eBook, so having
some familiarity with SQL will be an advantage.
7. Desire to Learn: Most importantly, come with a curious and open
mind. Web development with Flask is an exciting and rewarding
field, but it can be challenging at times. Having a willingness to
learn and experiment is key to your success.
No matter your current level of expertise, this eBook is structured to
accommodate learners with varying levels of experience. We'll start with
the basics and gradually progress to more advanced topics. If you're a
beginner, don't be discouraged by the prerequisites; we're here to help
you along the way.
Now that you've checked off these prerequisites, you're ready to dive into
the world of Python web development with Flask. Let's get started!
Chapter 1: What is Flask?
In the world of web development, Flask is a name that stands out for its
simplicity, flexibility, and power. It's often the first choice for Python
developers looking to build web applications quickly and efficiently. In this
chapter, we'll introduce you to Flask, giving you a fundamental
understanding of what it is and why it's such a popular choice among web
developers.
What is Flask?
Flask is a micro web framework for Python. The term "micro" might raise
questions, so let's clarify that right away. Flask is micro in the sense that it
provides the essentials for building web applications, but it leaves many
decisions to the developers. This flexibility allows you to build web
applications with Flask tailored to your specific needs without imposing a
particular way of doing things. This is in contrast to some more
heavyweight frameworks that come with a lot of predefined conventions
and components.
Flask is often compared to other Python web frameworks, such as Django.
While Django offers a more comprehensive and opinionated solution for
web development, Flask gives you the freedom to make decisions about
components, libraries, and structure. This makes it an excellent choice for
both beginners looking to get started quickly and experienced developers
who want to have more control over their projects.
Key Features of Flask
Flask's simplicity and elegance come from its core philosophy of being
"micro," but that doesn't mean it lacks powerful features. Here are some
key features and benefits of Flask:
1. Lightweight: Flask has a minimalistic core and doesn't require
extensive setup or boilerplate code. This means you can start
building web applications right away.
2. Easy to Learn: Flask's straightforward and intuitive design makes it
an ideal choice for beginners. If you're new to web development or
Python, you'll find Flask to be an accessible entry point.
3. Flexibility: Flask doesn't force you into a specific structure or
pattern. You can choose the components, libraries, and tools you
prefer, allowing you to build the application your way.
4. Extensibility: While Flask provides a minimal set of tools, it's highly
extensible. You can add features and functionalities as needed
through Flask extensions and libraries.
5. Werkzeug and Jinja2: Flask is built on top of the Werkzeug WSGI
toolkit and uses the Jinja2 template engine. This combination
ensures high performance and robust capabilities.
6. Wide Community and Ecosystem: Flask has a vibrant community
and an extensive ecosystem of extensions, plugins, and resources
to help you with various tasks and challenges.
Why Learn Flask?
If you're wondering why you should invest your time in learning Flask,
here are a few compelling reasons:
Rapid Development: Flask allows you to get a web application up
and running quickly. This is great for prototyping, MVPs (Minimum
Viable Products), or personal projects.
Full Control: With Flask, you have control over every aspect of
your application. You can structure it the way you like, choose your
database, and select the tools that fit your needs.
Skill Transfer: Learning Flask can help you understand web
development concepts that are transferable to other frameworks
and technologies.
In-Demand Skill: Flask is a valuable skill in the job market,
especially for positions that require Python web development
expertise.
Scalability: Flask can be used for both small and large-scale
applications. You can start with a simple project and scale it as your
needs grow.
In this chapter, we'll start with the basics, including how to install Flask,
create a simple "Hello, World!" application, and understand the
fundamental concepts of Flask. By the end of this chapter, you'll have a
working knowledge of Flask and be ready to explore its capabilities
further.
Let's dive in and start building with Flask!
Installation and Setup
Before you can start building web applications with Flask, you need to set
up your development environment. In this section, we'll guide you through
the installation process and help you get everything in place to begin your
Flask journey.
Step 1: Installing Python
Flask is a Python web framework, so the first step is to ensure you have Python
installed on your computer. If you don't already have Python installed or if you need to
check your Python version, follow these steps:
1. Visit the official Python website at
https://www.python.org/downloads/.
2. Download the latest version of Python, preferably Python 3.x (e.g.,
Python 3.9).
3. Run the Python installer and follow the installation instructions.
Make sure to add Python to your system's PATH during installation.
This allows you to run Python from the command line.
4. To check if Python is installed correctly, open your command line (or
terminal) and type:
bashCopy code
python --version
You should see the Python version you installed (e.g., "Python
3.9.6").
Step 2: Setting Up a Virtual Environment
To manage your project's dependencies and isolate them from your
system-wide Python installation, it's a good practice to create a virtual
environment. Virtual environments allow you to work on multiple projects
with different package requirements without conflicts. Here's how to set
up a virtual environment:
1. Open your command line or terminal.
2. Navigate to the directory where you want to create your Flask
project. For example, create a new directory for your project and
navigate to it:
bashCopy code
mkdir my_flask_project cd my_flask_project
3. Create a virtual environment by running the following command.
Replace venv with the name you prefer for your virtual
environment:
bashCopy code
python -m venv venv
This will create a new virtual environment in the "venv" directory.
4. To activate the virtual environment, use the appropriate command
based on your operating system:
Windows:
bashCopy code
venv\Scripts\activate
macOS and Linux:
bashCopy code
source venv/bin/activate
5. Once activated, you'll see the virtual environment name in your
command line prompt, indicating that you're working within the
virtual environment.
Step 3: Installing Flask
With your virtual environment activated, you can now install Flask. Use
pip, the Python package manager, to install Flask:
bashCopy code
pip install Flask
This command will download and install Flask and its dependencies in
your virtual environment.
Step 4: Verify Flask Installation
To ensure Flask is installed correctly, you can run a simple check. Create a
Python script (e.g., app.py) and add the following code:
pythonCopy code
from flask import Flask
app = Flask(__name)
@app.route('/')
def hello_world ():
return 'Hello, Flask!'
if __name__ == '__main__' :
app.run()
Save the file and run it using the following command:
bashCopy code
python app.py
Open your web browser and go to http://localhost:5000. You should see
the message "Hello, Flask!" displayed in your browser.
Congratulations! You've successfully installed Flask and created a basic
Flask application. In the upcoming sections, we'll explore Flask's
fundamental concepts and start building more sophisticated web
applications.
In the next part of this chapter, we'll dive into the essential components of
a Flask application, including routes and views. Get ready to start building
your first Flask application!
Creating Your First Flask Application
Now that you have Flask installed and your virtual environment set up, it's
time to create your very first Flask application. In this section, we'll guide
you through the process of building a basic "Hello, Flask!" application.
Step 1: Project Structure
Before we start coding, let's set up a simple project structure. Create a
directory for your Flask project (if you haven't already) and organize it as
follows:
plaintext
Copy code
my_flask_project/
├── venv/ (Your virtual environment directory)
├── app.py (Your Flask application file)
Step 2: Writing Your Flask Application
Open your code editor or integrated development environment (IDE) and
create a new Python script named app.py in your project directory. This is
where we'll write our Flask application.
In app.py, add the following code to create a basic Flask web application:
python
Copy code
from flask import Flask
# Create a Flask web application
app = Flask(__name)
# Define a route and a view function
@app.route('/')
def hello_flask():
return 'Hello, Flask!'
# Entry point for your Flask application
if __name__ == '__main__':
app.run()
Here's what each part of the code does:
We import the Flask class from the flask module.
We create a Flask web application using app = Flask(__name). The
__name__ argument tells Flask to use the current module as the
starting point for finding templates and static files.
We define a route with @app.route('/'), which is the root route or
the default route for your application. It maps to the function
hello_flask.
The hello_flask function returns the message "Hello, Flask!" as a
response when the root route is accessed.
Finally, we start the Flask application with app.run() when the script
is executed.
Step 3: Running Your Flask Application
With your Flask application code in place, it's time to run the application.
Follow these steps:
Make sure your virtual environment is activated. If it's not already
active, use the appropriate command based on your operating
system:
Windows:
bash
venv\Scripts\activate
macOS and Linux:
bash
source venv/bin/activate
Now that you're inside your virtual environment, you can run the
Flask application using the following command:
bash
python app.py
You'll see output indicating that the Flask development server is
running.
Open your web browser and go to http://localhost:5000. You should
see the message "Hello, Flask!" displayed in your browser.
Congratulations! You've created and run your first Flask application.
You've now taken your first steps into the world of web development with
Flask.
In the next chapter, we'll explore Flask routes, views, and templates,
which are essential components of building dynamic web applications.
Understanding Routes
In the previous section, you created a simple Flask application that
displayed a "Hello, Flask!" message when you accessed the root URL.
What made this possible was the use of routes. In Flask, routes define how
your application responds to different URLs. They are a fundamental part
of web development with Flask. In this section, we'll dive deeper into the
concept of routes and learn how to create different routes for your
application.
What are Routes in Flask?
In the context of a Flask application, a route is a URL pattern that is
associated with a view function. When a user accesses a specific URL in
their web browser, Flask's routing system determines which view function
should be called to handle the request and generate a response.
A route in Flask is defined using the @app.route() decorator, and it
typically maps to a Python function, known as a view function. When a
user accesses a URL that matches a defined route, Flask calls the
associated view function and returns the response it generates.
Defining Routes
Let's explore how to define routes in your Flask application. In the
previous example, you created a route for the root URL ("/"). Here's a
closer look at the code:
@app.route('/')
def hello_flask():
return 'Hello, Flask!'
In this code:
@app.route('/') is the route decorator, and it specifies the URL
pattern that this route responds to. In this case, it's the root URL
("/").
def hello_flask(): is the view function associated with the route. It's a
Python function that gets executed when a user accesses the root
URL.
return 'Hello, Flask!' is the response generated by the view function.
In this case, it's a simple text response.
Dynamic Routes
Flask allows you to create dynamic routes by including variable parts
within the URL. For example, you might want to build a blog application
where the URLs follow the pattern "/post/1", "/post/2", and so on. In Flask,
you can achieve this with dynamic routes. Here's how you define a
dynamic route:
pythonCopy code
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Viewing Post {post_id}'
In this code:
@app.route('/post/<int:post_id>') defines a dynamic route that
captures an integer value from the URL. The <int:post_id> part
specifies that the captured value should be converted to an integer
and passed as the post_id argument to the view function.
def show_post(post_id): is the view function that takes the post_id as
an argument. It returns a response with the post ID.
With dynamic routes, you can create more flexible and data-driven
applications where the URL structure adapts to the content.
Multiple Routes
In a Flask application, you can define multiple routes that map to different
URLs, each with its view function. This allows you to create various pages
and functionalities in your application. Here's an example of defining
multiple routes:
pythonCopy code
@app.route('/')
def home():
return 'Welcome to the Home Page'
@app.route('/about')
def about():
return 'This is the About Page'
@app.route('/contact')
def contact():
In this example, three routes are defined, each with its view function. The
root URL ("/") maps to the home() function, "/about" maps to about(), and
"/contact" maps to contact().
Order of Routes
It's important to note that Flask evaluates routes in the order they are
defined. If you define a dynamic route with a variable part ( <variable>)
before a static route (e.g., "/about"), Flask will interpret the dynamic route
as a URL parameter. Therefore, the order of route definitions matters.
URL Structure and Design
Designing an effective URL structure is an essential part of building a web
application. A well-structured URL not only makes your application user-
friendly but also helps with search engine optimization (SEO). Consider
the information you want to convey and the logical organization of your
application when designing your URL routes.
In the next section, we'll explore view functions and how they handle
requests and generate responses based on the defined routes.
Understanding routes and view functions is fundamental to building
dynamic web applications with Flask.
Debugging and Development Server
When developing Flask applications, it's important to have tools that make
the development process easier and more efficient. Flask provides a built-
in development server and powerful debugging capabilities to help you
identify and fix issues as you work on your project. In this section, we'll
explore how to use the Flask development server and its debugging
features.
The Flask Development Server
Flask comes with a built-in development server that allows you to run your
web application locally during the development phase. This server is
lightweight and easy to use, making it a valuable tool for testing your
application as you build it.
To start the Flask development server, navigate to your project directory
(the one containing your Flask application, such as app.py), activate your
virtual environment (if not already active), and run the following
command:
bashCopy code
python app.py
Replace app.py with the name of your Flask application script.
The Flask development server will start, and you'll see output in the
terminal indicating that the server is running. By default, the server will
listen on http://localhost:5000/ , and you can access your Flask application
by opening a web browser and visiting that URL.
Debug Mode
One of the key features of the Flask development server is its built-in
debug mode. When you run your Flask application in debug mode, it
provides valuable information and features for debugging, including:
Automatic reloading of the application when code changes are
detected.
Detailed error messages with traceback information in the browser.
Interactive debugger through the web browser, which allows you to
inspect variables, set breakpoints, and explore the call stack.
To enable debug mode, modify your Flask application script (e.g., app.py)
by adding the following line before the app.run() call:
pythonCopy code
app.run(debug= True )
Here's an example:
pythonCopy code
if __name__ == '__main__' :
app.run(debug= True )
With debug mode enabled, the Flask development server will
automatically reload your application whenever you make code changes,
making the development process more efficient.
Interactive Debugger
The interactive debugger is an incredibly valuable tool when you
encounter errors in your Flask application. When an error occurs, Flask will
display a detailed error page in your web browser, and you can explore
the error's stack trace, inspect variables, and even execute Python code in
the context of the error.
When you see an error page in your browser, you can click on the
traceback frames to explore the details of each function call. The
interactive debugger also allows you to modify variables and re-run code
within the error context, which can be helpful for diagnosing and fixing
issues.
Caution: Debug Mode for Development Only
It's important to note that debug mode and the interactive debugger
should only be enabled during development. When deploying your Flask
application to a production server, ensure that debug mode is disabled to
avoid security risks and performance issues.
To summarize, the Flask development server, along with debug mode and
the interactive debugger, provides a productive environment for building
and debugging your Flask applications during the development phase.
These tools help you identify and resolve issues, making your
development process smoother and more efficient.
In the next section, we'll explore Flask's route decorators and how to
create routes for different URLs in your application.
Chapter 2: Building Web Pages with HTML and Templates
In the previous chapter, you were introduced to Flask's fundamental
concepts, including routes and view functions. You built a simple Flask
application that returned text-based responses. While text responses are
useful for basic demonstrations, they are limited in terms of creating
dynamic and visually appealing web pages. To build more interactive and
visually engaging web applications, we need to incorporate HTML and
templates. In this chapter, we will dive into the world of web page creation
with Flask, exploring how to build web pages with HTML and templates.
Why HTML and Templates?
HTML (Hypertext Markup Language) is the standard language for creating
web pages. It allows you to structure the content of a web page, define its
layout, and add various elements such as headings, paragraphs, images,
forms, and links. HTML provides the foundation for rendering web content
in browsers.
Flask, like many web frameworks, encourages the separation of content
(HTML templates) from the application logic (Python code). This
separation enables a cleaner and more maintainable codebase, as it
allows web designers and developers to work on the presentation layer
independently.
In this chapter, you will learn how to:
Create HTML templates to define the structure and appearance of
web pages.
Integrate HTML templates with Flask to dynamically generate web
content.
Pass data from your Python code to HTML templates for rendering.
By the end of this chapter, you'll have the skills to create visually
appealing and dynamic web pages for your Flask applications. You'll
understand the importance of using templates to maintain a clear
separation between your application's logic and presentation, making
your projects more manageable and collaborative.
Key Topics in This Chapter
This chapter covers several key topics related to building web pages with
HTML and templates in Flask:
1. Understanding HTML: We'll start with an introduction to HTML,
covering the basic elements and structure used to create web
pages.
2. Jinja2 Templating Engine: Flask uses the Jinja2 templating engine
to render dynamic content. You'll learn how to use Jinja2 templates
in your Flask applications.
3. Creating HTML Templates: We'll guide you through the process
of creating HTML templates that define the structure and layout of
your web pages.
4. Passing Data to Templates: You'll explore how to pass data from
your Python code to HTML templates, allowing you to display
dynamic content on your web pages.
5. Template Inheritance: We'll introduce template inheritance, a
powerful feature that enables you to create consistent layouts for
your web pages and reuse common elements.
Let's Get Started
The ability to create and manipulate web pages is a fundamental skill in
web development. By the end of this chapter, you'll have a solid
understanding of how to create visually appealing and dynamic web
pages with Flask.
HTML Basics and Integrating HTML with Flask
In this section, we'll introduce you to the fundamentals of HTML and how
to integrate HTML with Flask to build web pages. HTML (Hypertext Markup
Language) is the standard language for creating the structure and content
of web pages. It defines the elements and layout of a web page, allowing
you to display text, images, links, forms, and more.
HTML: The Building Blocks of Web Pages
HTML is a markup language composed of tags that define the structure
and content of a web page. Here are some essential HTML concepts:
HTML Document: An HTML document is the foundation of a web
page. It contains all the elements necessary to render content in a
web browser.
HTML Elements: Elements are the building blocks of HTML
documents. They consist of an opening tag, content, and a closing
tag. For example, the <p> element is used to define a paragraph.
Attributes: Attributes provide additional information about an
element. For instance, the src attribute in an <img> tag specifies
the image source.
Nesting: HTML elements can be nested inside other elements,
creating a hierarchical structure for content.
Here's a simple example of HTML code that displays a basic web page:
htmlCopy code
<!DOCTYPE html>
<html>
<head>
<title> My Web Page </title>
</head>
<body>
<h1> Welcome to My Web Page </h1>
<p> This is a sample web page created with HTML. </p>
<img src="image.jpg" alt="An example image"> <a
href="https://www.example.com"> Visit Example.com </a>
</body>
</html>
This HTML code defines a web page with a title, heading, paragraph,
image, and a link.
Integrating HTML with Flask
Flask makes it easy to integrate HTML into your web applications. You can
create HTML templates, which are HTML files that contain placeholders for
dynamic data, and then render these templates with Flask to generate
web content.
Let's start by creating an HTML template and rendering it using Flask.
Here's a step-by-step guide:
Step 1: Create an HTML Template
In your Flask project directory, create a new directory called "templates" if
it doesn't already exist. This directory will store your HTML templates.
Inside the "templates" directory, create a new HTML file. For this example,
name it index.html. Here's a basic template to get you started:
htmlCopy code
<!DOCTYPE html>
<html>
<head> <title> My Flask Web Page </title> </head> <body> <h1> Welcome to My
Flask Web Page </h1> <p> {{ message }} </p> </body> </html>
This HTML template contains a title, heading, and a paragraph. The
{{ message }} part is a placeholder for dynamic content that Flask will
insert when rendering the template.
Step 2: Rendering the HTML Template
Back in your Flask application script (e.g., app.py), you'll use the
render_template function from Flask to render the HTML template. Modify
your view function to include the rendering step:
pythonCopy code
from flask import Flask, render_template
app = Flask(__name)
@app.route('/')
def index ():
message = "Hello from Flask!"
return render_template( 'index.html' , message=message)
if __name__ == '__main__' :
app.run(debug= True )
In this updated code:
We import the render_template function from Flask.
Inside the index() view function, we define a message variable with
the value "Hello from Flask!"
We use render_template('index.html', message=message) to render
the index.html template, passing the message variable to it.
Step 3: Running Your Flask Application
Start your Flask application by running python app.py in your terminal.
The development server will start, and you can access your application by
visiting http://localhost:5000 in your web browser. You should see the web
page generated from the HTML template, with the message "Hello from
Flask!"
Congratulations! You've successfully integrated HTML templates with
Flask to create dynamic web content. This is just the beginning of your
journey into building web pages with Flask. You can create more complex
templates and pass different data to them, making your web applications
more interactive and informative.
In the next section, we'll explore the Jinja2 templating engine, which is the
powerful tool behind Flask's templating system.