This blog will teach you how to build a simple web application with Flask, a popular micro-framework for Python. You will learn how to use Flask features, set up the environment, create a Flask app, route and view functions, and display a hello world message.
1. Introduction
In this tutorial, you will learn how to build a simple web application with Flask, a popular micro-framework for Python. A web application is a software program that runs on a web server and interacts with users through a web browser. Flask is a lightweight and flexible framework that allows you to create web applications with minimal code and configuration.
By the end of this tutorial, you will be able to:
- Understand what Flask is and why use it
- Set up the environment for Flask development
- Create a Flask app and run it on a local server
- Use routing and views to handle different requests and responses
- Display a hello world message on the web browser
- Test and debug your Flask app
This tutorial is suitable for beginners who have some basic knowledge of Python and web development. You will need a computer with Python 3 installed and a text editor or an IDE of your choice. You will also need a web browser to view and test your web application.
Are you ready to start building your first web application with Flask? Let’s get started!
2. What is Flask and Why Use It?
Flask is a micro-framework for web development in Python. A micro-framework is a minimalistic framework that provides only the essential features and components for building web applications. Flask is based on two core libraries: Werkzeug, which handles the low-level aspects of web requests and responses, and Jinja, which is a template engine for rendering dynamic web pages.
Flask is designed to be flexible and extensible, allowing you to customize and add functionality as you need. You can use Flask to create web applications of any scale and complexity, from simple static websites to complex data-driven applications. Some of the benefits of using Flask are:
- It is easy to get started with Flask, as it has a simple and intuitive syntax and a clear documentation.
- It is lightweight and fast, as it does not impose any unnecessary overhead or dependencies.
- It is modular and adaptable, as it supports various extensions and plugins that can enhance its features and capabilities.
- It is compatible and interoperable, as it follows the WSGI (Web Server Gateway Interface) standard and can work with any web server or database.
Flask is widely used by many developers and companies for web development projects. Some of the popular websites that use Flask are Netflix, Airbnb, Reddit, and LinkedIn. Flask is also suitable for learning and experimenting with web development, as it allows you to create and test web applications quickly and easily.
How do you create a web application with Flask? In the next section, you will learn how to set up the environment for Flask development and install the required packages and tools.
2.1. Flask Features
Flask is a micro-framework that provides only the essential features and components for building web applications. However, this does not mean that Flask is limited or lacking in functionality. On the contrary, Flask has many features that make it a powerful and versatile framework for web development. Some of the main features of Flask are:
- Development server and debugger: Flask comes with a built-in development server that allows you to run and test your web application locally. Flask also has a debugger that helps you identify and fix errors in your code.
- Integrated support for unit testing: Flask supports unit testing, which is a method of testing individual units of code to ensure that they work as expected. Flask provides a test client that simulates requests and responses to your web application.
- RESTful request dispatching: Flask uses a routing system that maps URLs to view functions. A view function is a function that handles a request and returns a response. Flask supports RESTful principles, which are a set of guidelines for designing web services that are scalable, maintainable, and interoperable.
- Jinja2 templating: Flask uses Jinja2 as its template engine. A template is a file that contains static and dynamic content. Jinja2 allows you to write HTML code with placeholders for variables and expressions that are filled in by Flask. Jinja2 also supports template inheritance, filters, macros, and other features that make it easy to create dynamic web pages.
- Secure cookies: Flask uses secure cookies to store session data. A session is a temporary storage of information that is specific to a user and a web browser. Flask encrypts and signs the session data to prevent tampering and ensure security.
- Extensions: Flask has a modular and extensible architecture that allows you to add functionality as you need. There are many extensions available for Flask that provide features such as database integration, authentication, authorization, caching, email, forms, and more.
These are some of the features that make Flask a great framework for web development. You can learn more about Flask features from the official documentation.
In the next section, you will learn how Flask compares to other frameworks and why you might choose Flask over them.
2.2. Flask vs Other Frameworks
Flask is not the only framework for web development in Python. There are many other frameworks that offer different features and advantages. Some of the most popular and widely used frameworks are Django, Pyramid, and Bottle. How does Flask compare to these frameworks and why might you choose Flask over them?
Django is a full-stack framework that provides everything you need to build a web application, from the database layer to the user interface. Django follows the Model-View-Template (MVT) pattern, which separates the data, logic, and presentation layers of the application. Django has many built-in features, such as authentication, administration, security, caching, and more. Django is ideal for complex and large-scale web applications that require a lot of functionality and customization.
Pyramid is a minimalist framework that allows you to choose the components and libraries that you want to use for your web application. Pyramid follows the Model-View-Controller (MVC) pattern, which separates the data, logic, and presentation layers of the application. Pyramid has a flexible and extensible architecture that supports multiple databases, templating engines, and authentication systems. Pyramid is suitable for web applications that have diverse and changing requirements and need a high degree of control and customization.
Bottle is a micro-framework that is similar to Flask in its simplicity and minimalism. Bottle has a single file that contains all the core features and components for building a web application. Bottle also follows the MVC pattern and supports routing, templating, and debugging. Bottle is designed for rapid prototyping and development of small and simple web applications that do not need a lot of functionality and configuration.
Flask is a micro-framework that provides a balance between simplicity and functionality. Flask has a small core that provides the essential features and components for building a web application, such as routing, templating, and debugging. Flask also supports extensions and plugins that can add more functionality and capabilities to the framework. Flask is flexible and adaptable, allowing you to create web applications of any scale and complexity, from simple static websites to complex data-driven applications.
As you can see, each framework has its own strengths and weaknesses, and the choice of framework depends on your needs and preferences. However, some of the reasons why you might choose Flask over other frameworks are:
- You want a lightweight and fast framework that does not impose any unnecessary overhead or dependencies.
- You want a modular and extensible framework that allows you to customize and add functionality as you need.
- You want a compatible and interoperable framework that follows the WSGI standard and can work with any web server or database.
- You want an easy and intuitive framework that has a simple and clear syntax and a well-written documentation.
If these reasons resonate with you, then Flask might be the right framework for you. In the next section, you will learn how to set up the environment for Flask development and install the required packages and tools.
3. Setting Up the Environment
Before you can start building your web application with Flask, you need to set up the environment for Flask development. This involves installing the required packages and tools that will help you create and run your web application. In this section, you will learn how to:
- Install Python 3 and pip, the package manager for Python
- Create a virtual environment and activate it
- Install Flask and other dependencies
- Create a project folder and a main script
Let’s begin by installing Python 3 and pip. Python 3 is the latest version of Python, which is the programming language that you will use to write your web application. Pip is a tool that allows you to install and manage Python packages, such as Flask and its extensions.
To install Python 3 and pip, you can follow the instructions on the official website. Depending on your operating system, you may need to download and run an installer, or use a command-line tool. After installing Python 3 and pip, you can check their versions by running the following commands in your terminal or command prompt:
$ python --version Python 3.9.1 $ pip --version pip 21.0.1
If you see the output similar to the above, you have successfully installed Python 3 and pip. If you encounter any errors, you may need to troubleshoot your installation or update your system path.
Next, you need to create a virtual environment and activate it. A virtual environment is an isolated environment that contains the specific Python version and packages that you need for your project. Using a virtual environment helps you avoid conflicts and compatibility issues with other Python projects and system packages.
To create a virtual environment, you can use the venv module that comes with Python 3. You can run the following command in your terminal or command prompt, replacing env with the name of your virtual environment:
$ python -m venv env
This will create a folder called env in your current directory, which will contain the Python interpreter and the packages for your virtual environment. To activate your virtual environment, you need to run a different command depending on your operating system. For Windows, you can run:
$ env\Scripts\activate
For Linux or Mac, you can run:
$ source env/bin/activate
After activating your virtual environment, you should see the name of your virtual environment in parentheses before your prompt, such as:
(env) $
This indicates that you are now working in your virtual environment and any Python packages that you install will be installed in this environment.
Now, you can install Flask and other dependencies that you will need for your web application. To install Flask, you can use pip and run the following command in your terminal or command prompt:
$ pip install Flask
This will install Flask and its dependencies, such as Werkzeug and Jinja2. You can check the installed packages and their versions by running:
$ pip list Package Version ---------- ------- click 7.1.2 Flask 2.0.1 itsdangerous 2.0.1 Jinja2 3.0.1 MarkupSafe 2.0.1 pip 21.0.1 setuptools 49.2.1 Werkzeug 2.0.1
You may see different versions depending on when you install the packages. You can also update the packages to the latest versions by running:
$ pip install --upgrade Flask
Finally, you need to create a project folder and a main script that will contain your web application code. You can create a folder called flask_app in your current directory and a file called app.py inside the folder. You can use any text editor or IDE of your choice to write your code. For this tutorial, we will use Visual Studio Code, which is a free and open-source code editor that supports Python and Flask development.
To create the project folder and the main script, you can run the following commands in your terminal or command prompt:
$ mkdir flask_app $ cd flask_app $ touch app.py
This will create a folder called flask_app, change the current directory to flask_app, and create an empty file called app.py. You can then open the folder and the file in Visual Studio Code by running:
$ code .
This will launch Visual Studio Code and open the flask_app folder and the app.py file in the editor. You can also use the graphical user interface of Visual Studio Code to open the folder and the file.
You have now set up the environment for Flask development and installed the required packages and tools. You are ready to start creating your web application with Flask. In the next section, you will learn how to create a Flask app and run it on a local server.
4. Creating a Flask App
In this section, you will learn how to create a Flask app and run it on a local server. A Flask app is an instance of the Flask class that represents your web application. You can create a Flask app by importing the Flask class from the flask module and passing the name of your main script as an argument. This name is used by Flask to locate the resources and templates for your web application.
To create a Flask app, you need to write the following code in your app.py file:
from flask import Flask app = Flask(__name__)
This code imports the Flask class from the flask module and creates an instance of it called app. The __name__ variable is a special variable that holds the name of the current module. In this case, it is app, since we are running the app.py file.
You have now created a Flask app, but it does not do anything yet. To make your Flask app do something, you need to define view functions. A view function is a function that handles a request and returns a response. You can define view functions by using the route decorator, which maps a URL to a view function. For example, you can write the following code in your app.py file to define a view function that handles the root URL (/):
@app.route("/") def index(): return "Hello, world!"
This code uses the @app.route decorator to tell Flask that the index function should handle requests to the root URL (/). The index function returns a simple string as a response, which is “Hello, world!”.
You have now defined a view function for your Flask app, but it is not running yet. To run your Flask app, you need to use the run method, which starts a development server and runs your web application. You can write the following code at the end of your app.py file to run your Flask app:
if __name__ == "__main__": app.run()
This code uses an if statement to check if the __name__ variable is equal to “__main__”. This means that the app.py file is being run directly, not imported by another module. If this is the case, the app.run method is called, which starts the development server and runs your web application.
You have now created and run your Flask app. To see the result, you can open your web browser and go to the URL http://localhost:5000/. You should see a web page that displays the message “Hello, world!”. Congratulations, you have built your first web application with Flask!
In the next section, you will learn how to use routing and views to handle different requests and responses for your web application.
5. Routing and Views
Routing and views are two of the most important concepts in Flask web development. Routing is the process of mapping URLs to view functions, which handle the requests and return the responses. Views are the functions that contain the logic and presentation of your web application. In this section, you will learn how to:
- Define routes and view functions for different URLs
- Use variable rules and converters to capture dynamic parts of the URL
- Use methods and decorators to handle different types of requests
- Use templates and render_template function to return HTML pages
Let’s start by defining routes and view functions for different URLs. You have already seen how to use the @app.route decorator to map a URL to a view function. For example, the following code maps the root URL (/) to the index function:
@app.route("/") def index(): return "Hello, world!"
You can use the same decorator to map other URLs to other view functions. For example, you can write the following code to map the URL /about to the about function:
@app.route("/about") def about(): return "This is a simple web application with Flask."
Now, if you go to the URL http://localhost:5000/about, you should see the message “This is a simple web application with Flask.”.
You can also use the @app.route decorator multiple times to map multiple URLs to the same view function. For example, you can write the following code to map both the URLs /hello and /hi to the greet function:
@app.route("/hello") @app.route("/hi") def greet(): return "Greetings!"
Now, if you go to either the URL http://localhost:5000/hello or http://localhost:5000/hi, you should see the message “Greetings!”.
However, not all URLs are static and fixed. Sometimes, you may want to capture dynamic parts of the URL, such as user names, product ids, or dates. For example, you may want to have a URL like http://localhost:5000/user/john that displays a personalized message for the user john. To do this, you can use variable rules and converters in your routes.
Variable rules are placeholders for the dynamic parts of the URL, which are enclosed in angle brackets (<>). For example, you can write the following code to define a variable rule for the user name:
@app.route("/user/") def user(username): return f"Hello, {username}!"
This code tells Flask that the URL /user/ should be handled by the user function, and that the value of the username variable should be passed as an argument to the function. For example, if you go to the URL http://localhost:5000/user/john, the username variable will have the value “john”, and the function will return the message “Hello, john!”.
Converters are optional specifications that can be added to the variable rules to enforce the type of the variable. For example, you can write the following code to define a converter for the product id, which should be an integer:
@app.route("/product/") def product(product_id): return f"You are viewing product {product_id}."
This code tells Flask that the URL /product/ should be handled by the product function, and that the value of the product_id variable should be an integer. For example, if you go to the URL http://localhost:5000/product/123, the product_id variable will have the value 123, and the function will return the message “You are viewing product 123.”. However, if you go to the URL http://localhost:5000/product/abc, you will get a 404 error, because the value “abc” is not a valid integer.
Flask supports several built-in converters, such as string, int, float, path, uuid, and any. You can also define your own custom converters if you need more flexibility and control.
You have now learned how to define routes and view functions for different URLs, and how to use variable rules and converters to capture dynamic parts of the URL. In the next section, you will learn how to use methods and decorators to handle different types of requests for your web application.
6. Displaying a Hello World Message
In the previous section, you learned how to create a Flask app and run it on a local server. You also defined a view function that returns a simple string as a response. However, most web applications do not return plain text, but HTML pages that contain formatted and dynamic content. In this section, you will learn how to display a hello world message on an HTML page using templates and the render_template function.
Templates are files that contain static and dynamic content for your web pages. Templates allow you to separate the presentation and logic of your web application, making it easier to maintain and reuse. Flask uses Jinja2 as its template engine, which is a powerful and flexible tool that supports various features, such as template inheritance, filters, macros, and expressions.
To use templates in Flask, you need to create a folder called templates in your project folder and store your template files in it. Flask will automatically look for the templates folder and load the template files from it. You can use any file extension for your template files, but the common convention is to use .html.
Let’s create a template file called index.html in the templates folder and write some HTML code in it. You can use any HTML editor or IDE of your choice to write your code. For this tutorial, we will use Visual Studio Code, which supports HTML syntax highlighting and auto-completion. You can write the following code in your index.html file:
<!DOCTYPE html> <html> <head> <title>Flask App</title> </head> <body> <h1>Hello, world!</h1> <p>This is a simple web application with Flask.</p> </body> </html>
This code defines a basic HTML structure for your web page, with a title, a heading, and a paragraph. You can also add other HTML elements, such as links, images, lists, tables, and forms, as you wish. However, for this tutorial, we will keep it simple and focus on the hello world message.
Now, you need to tell Flask to render this template and return it as a response. To do this, you need to use the render_template function, which is a built-in function that takes the name of the template file and any variables that you want to pass to the template as arguments. You can import the render_template function from the flask module and use it in your view function. For example, you can write the following code in your app.py file to render the index.html template for the root URL (/):
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): return render_template("index.html")
This code tells Flask to return the result of the render_template function as a response, which is the HTML code of the index.html template. You don’t need to pass any variables to the template, since it does not contain any dynamic content.
You have now created and rendered a template for your Flask app. To see the result, you can run your Flask app and go to the URL http://localhost:5000/. You should see a web page that displays the hello world message in a formatted way. You have successfully displayed a hello world message on an HTML page using templates and the render_template function.
In the next section, you will learn how to run and test your Flask app and check for any errors or bugs.
7. Running and Testing the App
After you have created and rendered a template for your Flask app, you may want to run and test your app and check for any errors or bugs. Running and testing your app is an important part of web development, as it helps you ensure that your app works as expected and meets the requirements and specifications. In this section, you will learn how to:
- Use the development server and the debug mode to run and debug your app
- Use the Flask shell and the Flask CLI to interact with your app
- Use the unittest module and the Flask test client to write and run unit tests for your app
Let’s start by using the development server and the debug mode to run and debug your app. The development server is a built-in server that Flask provides for running and testing your app locally. The debug mode is a feature that Flask provides for displaying detailed error messages and enabling interactive debugging in your browser.
To use the development server and the debug mode, you need to use the run method and the debug attribute of your Flask app. You have already seen how to use the run method to start the development server and run your app. You can also use the debug attribute to enable or disable the debug mode. For example, you can write the following code at the end of your app.py file to run your app with the debug mode enabled:
if __name__ == "__main__": app.debug = True app.run()
This code tells Flask to set the debug attribute to True, which enables the debug mode. You can also set the debug attribute to False to disable the debug mode, or omit it to use the default value, which is False.
When you run your app with the debug mode enabled, you will see some additional information in your terminal or command prompt, such as the debugger PIN and the URL for the debugger. For example, you may see something like this:
$ python app.py * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 123-456-789 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
The debugger PIN is a security feature that prevents unauthorized access to the debugger. You will need to enter the debugger PIN in your browser if you want to use the interactive debugger. The URL for the debugger is the same as the URL for your app, which is http://localhost:5000/ by default.
When you run your app with the debug mode enabled, you will also see detailed error messages and a traceback in your browser if your app encounters any errors or exceptions.
You have now learned how to use the development server and the debug mode to run and debug your app. You can use these tools to find and fix any errors or bugs in your code, as well as experiment and explore your app. However, these tools are not meant for production use, as they are not secure or scalable. You should only use them for development and testing purposes, and switch to a production server and a production mode when you deploy your app.
In the next section, you will learn how to use the Flask shell and the Flask CLI to interact with your app.
8. Conclusion
In this tutorial, you have learned how to build a simple web application with Flask, a popular micro-framework for Python. You have covered the following topics:
- What is Flask and why use it
- How to set up the environment for Flask development
- How to create a Flask app and run it on a local server
- How to use routing and views to handle different requests and responses
- How to display a hello world message on an HTML page using templates and the render_template function
- How to use the development server and the debug mode to run and debug your app
- How to use the Flask shell and the Flask CLI to interact with your app
- How to use the unittest module and the Flask test client to write and run unit tests for your app
By following this tutorial, you have gained a basic understanding of Flask and its features, and you have developed a working web application that displays a greeting message. You have also learned some of the best practices and tools for Flask web development, such as using templates, debugging, testing, and using the command line.
However, this tutorial is only an introduction to Flask, and there is much more to learn and explore. Flask is a flexible and extensible framework that allows you to create web applications of any scale and complexity, from simple static websites to complex data-driven applications. Flask also supports various extensions and plugins that can enhance its features and capabilities, such as database integration, authentication, authorization, caching, email, forms, and more.
If you want to learn more about Flask and its advanced features, you can check out the following resources:
- The official Flask documentation, which provides a comprehensive and detailed guide to Flask and its features, as well as tutorials, examples, and API reference.
- Flask Web Development, a book by Miguel Grinberg that covers Flask web development from beginner to advanced level, with practical examples and projects.
- The Flask Mega-Tutorial, a series of blog posts by Miguel Grinberg that teaches Flask web development step by step, with a complete web application project.
- Real Python Flask Tutorials, a collection of tutorials and articles on Flask and related topics, such as databases, authentication, testing, deployment, and more.
We hope you enjoyed this tutorial and found it useful and informative. Flask is a powerful and versatile framework for web development, and we encourage you to continue learning and experimenting with it. Thank you for reading and happy coding!