Flask is a slim web framework, suitable for beginners and pro­fes­sion­als alike. Flask is limited to including only the es­sen­tials, but users can implement external libraries to expand its func­tion­al­i­ty.

Python and its web frame­works

Python is one of the most popular internet pro­gram­ming languages in the world. This is because it uses simple and short code. The neat pro­gram­ming style minimizes errors and users can quickly get their heads around a Python tutorial. Developed by Guido van Rossum in 1991, it’s now used and main­tained by a large community under the su­per­vi­sion of the non-profit Python Software Foun­da­tion. Python is open source and platform in­de­pen­dent. Python is a dynamic language. It supports object-oriented and func­tion­al pro­gram­ming such as logging and can be executed as CGI script.

Various web frame­works are available to use Python to create dynamic websites and develop web ap­pli­ca­tions. These provide the necessary code to ease the de­vel­op­ment process and simplify repeat tasks. Issues or common Python errors can be avoided and web services are up and running faster and in a more secure manner. Fre­quent­ly required functions can be adopted directly and don’t require in­de­pen­dent pro­gram­ming. One of the best-known web frame­works for Python is django CMS, which, as a full-stack solution, offers a large toolbox of various features in com­par­i­son to Flask vs. Django. However, it is also rel­a­tive­ly rigid and pre­de­fined. Perhaps the most well-known al­ter­na­tive to this approach is Flask.

What is Flask?

While full-stack frame­works such as Django provide de­vel­op­ers with their own libraries, Flask Python takes a different approach. The web framework launched by Austrian developer Armin Ronacher in 2010, takes a more min­i­mal­ist approach. Flask only includes the template engine Jinja and a library called “tool”. But it offers the pos­si­bil­i­ty to integrate third-party functions. The Flask framework is under a BSD license. It’s free and open source. As a counter-design to Django and other frame­works, Flask Python was quick to inspire a large fan community.

Website Builder
From idea to website in record time with AI
  • Intuitive website builder with AI as­sis­tance
  • Create cap­ti­vat­ing images and texts in seconds
  • Domain, SSL and email included

Python Flask tutorial to set up Flask and web ap­pli­ca­tions

Before setting up Flask for Python, make sure you meet the re­quire­ments. You’ll need Python 3 installed. You will also need a text editor or IDE and access to the internet. Having some basic knowledge of Python is useful. An un­der­stand­ing of pro­gram­ming, data types, and for-loops is also ad­van­ta­geous. Flask is a good starting point to learn how to build web ap­pli­ca­tions. You set up the framework as follows:

  1. Create a virtual en­vi­ron­ment to separate the new project from the rest of your Python libraries or projects and avoid problems with your system. The code looks like this:
$ python -m venv newproject
  1. Install Flask. The best way to do this is to use the package man­age­ment program pip. The ap­pro­pri­ate command is:
$ pip install flask
  1. Check if the in­stal­la­tion has been suc­cess­ful by using this command:
python -c "import flask; print(flask.__version__)"$ python -c "import flask; print ( flask._version_ )"
  1. Now you can test Flask and create a basic ap­pli­ca­tion. To do this, open a file in your directory. Here, we call it start.py and use nano to access it:
$ nano start.py
  1. Write the following code into the file:
from flask import Flask
app = Flask(__name__)Flask ( _name_ )
@app.route ( "/" )
def test ( ):
return "This is a test"
  1. Save and close the file.

  2. Use the en­vi­ron­ment variable FLASK_APP to point Flask to the location of the cor­re­spond­ing file:

$ export FLASK_APP=start
  1. Use FLASK_ENV to export the file in developer mode:
$ export FLASK_ENV=development
  1. Now run the ap­pli­ca­tion:
$ flask run

The output should look something like this:

Output
- Serving Flask app "start" (lazy loading)
- Environment: development
- Debug mode: on
- Running on [IP address]/ (Press CTRL+C to quit)
- Restarting with stat
- Debugger is active!
- Debugger PIN [PIN]

Pros and cons of Flask Python

There are good reasons for using Flask. However, a few things speak against it. For this reason, it’s worth taking a closer look at the pros and cons of the web framework.

Pros

Scope: You will hardly find a more stream­lined framework than Flask Python. Flask is quick to install and use.

Flex­i­bil­i­ty: The flex­i­bil­i­ty that Flask offers is also out­stand­ing. You have the freedom to solve each problem in­di­vid­u­al­ly and can implement exactly the libraries you actually need. This allows you to approach every project in a fully cus­tomized way.

Learning curve: You’ll see quick results when following a Flask tutorial. The framework is in­ten­tion­al­ly designed to be simple, yet it also allows you to work on advanced projects. Flask is therefore a great choice for both beginners and pro­fes­sion­als working on more complex projects.

Open source: The Flask framework is open source and available for free. Simply give it a try and find out if it’s the right tool for your needs.

Community: Flask is supported by a huge community providing advice and support to newcomers and more ex­pe­ri­enced de­vel­op­ers. Questions and errors are rapidly answered and solved.

Cons

- Scope: Depending on intended use, its min­i­mal­ist scope can be dis­ad­van­ta­geous. All tools require in­di­vid­ual in­stal­la­tion. Al­ter­na­tive frame­works offer sig­nif­i­cant­ly more pre-installed functions.

- De­pen­den­cy on third-party providers: The use of external libraries is always a possible source of errors, but Flask depends on them.

- Main­te­nance: While other frame­works handle main­te­nance au­to­mat­i­cal­ly and fix potential issues on their own, Flask leaves this re­spon­si­bil­i­ty to the users. On the one hand, this means more control, but on the other, it also requires more effort.

Hello World example on routing, templates and APIs

To get a better un­der­stand­ing of how Flask works, let’s look at a simple example that il­lus­trates the core concepts of the web framework. We’ll create a small web ap­pli­ca­tion to show how routing, templates, and a REST API work together. The example consists of two files:

  • app.py: This file contains our Python code.
  • templates/hello.html: This file is a Jinja2 template that dy­nam­i­cal­ly displays the website.

The app.py file looks like this:

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route("/")
def home():
    return "Hello World!"
@app.route("/greet/<name>")
def greet(name):
    return render_template("hello.html", name=name)
@app.route("/api/square", methods=["GET"])
def square():
    number = request.args.get("number", default=0, type=int)
    result = number ** 2
    return jsonify({"number": number, "square": result})
if __name__ == "__main__":
    app.run(debug=True)
python

Here’s the hello.html file that serves as the template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Greeting</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
    <p>Welcome to Flask with a Jinja2 template.</p>
</body>
</html>
html

With @app.route, we define different endpointsURLs that the server can respond to. The home page ("/") simply displays the text “Hello World!”. Using a dynamic path ("/greet/<name>"), we can display a per­son­al­ized greeting. The name is taken from the URL and passed to our Jinja2 template, which inserts it into the HTML (see the code in templates/hello.html).

We also demon­strate how to create a small REST API: under the endpoint "/api/square", the user can pass a number as a URL parameter, and the app returns the square of that number as a JSON response. This shows that Flask can handle both tra­di­tion­al websites and API endpoints. Thanks to templates, dynamic content can be easily in­te­grat­ed into HTML without having to manually update the page.

Note

This code is only a minimal example for a Flask tutorial and is meant to il­lus­trate the core concepts. In a real ap­pli­ca­tion, you would also need to consider aspects such as error handling, security, data val­i­da­tion, and a clean project structure to ensure the app remains stable, reliable, and easy to maintain.

Flask Ex­ten­sions

Since Flask is designed to be very min­i­mal­is­tic, many useful features like database in­te­gra­tion, au­then­ti­ca­tion, or form val­i­da­tion are not built in. To add these functions, de­vel­op­ers rely on Flask ex­ten­sions, which are created and main­tained by the community. These ex­ten­sions can be easily in­te­grat­ed into a Flask ap­pli­ca­tion and sig­nif­i­cant­ly expand its func­tion­al­i­ty — without modifying the framework itself. This approach allows de­vel­op­ers to choose exactly the com­po­nents they need and build their apps in a modular way. Ex­ten­sions typically follow the same design prin­ci­ples as Flask itself and are well-doc­u­ment­ed.

Examples of important Flask ex­ten­sions include:

  • Flask-SQLAlche­my: An extension for database in­te­gra­tion. It in­te­grates the popular SQLAlche­my ORM into Flask and enables easy in­ter­ac­tion with databases using Python classes.
  • Flask-WTF: This extension supports the creation and val­i­da­tion of web forms. It offers security features such as CSRF pro­tec­tion and sim­pli­fies handling user input.
  • Flask-Login: As the name suggests, Flask-Login handles user man­age­ment and au­then­ti­ca­tion. It manages login states, sessions, and access control for specific routes.
  • Flask-Migrate: With Flask-Migrate, you get database migration func­tion­al­i­ty that au­to­mat­i­cal­ly manages changes to your database schema. It’s ideal for use alongside Flask-SQLAlche­my for struc­tured updates.
  • Flask-RESTful: This extension sim­pli­fies the creation of REST APIs. It provides stan­dard­ized handling of resources, routes, and HTTP methods such as GET, POST, PUT, and DELETE.

Project structure and best practices

For Flask projects, it’s rec­om­mend­ed to start with a clear and well-struc­tured project or­ga­ni­za­tion right from the beginning. While small apps can tech­ni­cal­ly run from a single file, a clean structure makes main­te­nance and further de­vel­op­ment much easier.

For larger projects, it’s common to create di­rec­to­ries such as templates for HTML files, static for CSS, JavaScript, and images, as well as app or src for Python modules. Within the app folder, you can create sub­di­rec­to­ries for blue­prints, models, forms, and utilities to keep functions logically separated. Blue­prints make it possible to design different com­po­nents of the app modularly — for example, a user man­age­ment system or a blog section.

Best practices also recommend keeping con­fig­u­ra­tion values such as database URLs or secret keys in a separate config.py file or storing them as en­vi­ron­ment variables. Con­tin­u­ous logging helps detect errors early and track the app’s behavior. It’s also a good idea to use virtual en­vi­ron­ments to manage de­pen­den­cies cleanly. Ad­di­tion­al­ly, version control with Git is con­sid­ered standard practice to keep changes trans­par­ent and main­tain­able.

Create a website with your domain
Build your own website or online store, fast
  • Pro­fes­sion­al templates
  • Intuitive cus­tomiz­able design
  • Free domain, SSL, and email address

Flask security and testing

Security and testing are not optional extras but essential com­po­nents of a pro­fes­sion­al Flask ap­pli­ca­tion — and should never be over­looked in any Flask tutorial. By focusing on en­cryp­tion, input val­i­da­tion, secure con­fig­u­ra­tions, and automated testing from the very beginning, you can develop stable and secure web ap­pli­ca­tions that can be easily expanded later on.

Security in Flask

Because of Flask’s min­i­mal­ist design, de­vel­op­ers are re­spon­si­ble for ensuring the security of their ap­pli­ca­tions. A fun­da­men­tal layer of pro­tec­tion is the use of CSRF pro­tec­tion for forms, es­pe­cial­ly when handling user input. The Flask-WTF extension provides proven mech­a­nisms for this purpose.

Passwords should never be stored in plain text — they should always be encrypted or hashed. Libraries such as werkzeug.security or bcrypt are well suited for this. Input val­i­da­tion is equally important to prevent SQL injection, XSS attacks, and other types of ma­nip­u­la­tion.

For sessions and cookies, it’s important to enable the HttpOnly and Secure flags to protect sensitive data. Con­fig­u­ra­tion details such as database URLs or API keys should be managed through en­vi­ron­ment variables or separate con­fig­u­ra­tion files rather than being hardcoded directly into the source code.

Testing in Flask

As with any software project, testing is essential in Flask to ensure the stability of the ap­pli­ca­tion. Unit tests are used to check in­di­vid­ual functions in isolation, while in­te­gra­tion tests verify the in­ter­ac­tion between multiple com­po­nents.

Flask provides a built-in test client system that allows you to simulate HTTP requests without actually starting the server. This makes it easy to au­to­mat­i­cal­ly test routes, templates, and API endpoints. It’s es­pe­cial­ly important to write and update test cases regularly — par­tic­u­lar­ly when adding new features — to prevent re­gres­sions. Combined with Con­tin­u­ous In­te­gra­tion, this approach helps ensure that your app remains stable and reliable even as it evolves.

Reviewer

Go to Main Menu