What is Flask Python? A short Flask framework tutorial
Flask is a slim web framework, suitable for beginners and professionals alike. Flask is limited to including only the essentials, but users can implement external libraries to expand its functionality.
Python and its web frameworks
Python is one of the most popular internet programming languages in the world. This is because it uses simple and short code. The neat programming 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 maintained by a large community under the supervision of the non-profit Python Software Foundation. Python is open source and platform independent. Python is a dynamic language. It supports object-oriented and functional programming such as logging and can be executed as CGI script.
Various web frameworks are available to use Python to create dynamic websites and develop web applications. These provide the necessary code to ease the development 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. Frequently required functions can be adopted directly and don’t require independent programming. One of the best-known web frameworks for Python is django CMS, which, as a full-stack solution, offers a large toolbox of various features in comparison to Flask vs. Django. However, it is also relatively rigid and predefined. Perhaps the most well-known alternative to this approach is Flask.
What is Flask?
While full-stack frameworks such as Django provide developers with their own libraries, Flask Python takes a different approach. The web framework launched by Austrian developer Armin Ronacher in 2010, takes a more minimalist approach. Flask only includes the template engine Jinja and a library called “tool”. But it offers the possibility 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 frameworks, Flask Python was quick to inspire a large fan community.
- Intuitive website builder with AI assistance
- Create captivating images and texts in seconds
- Domain, SSL and email included
Python Flask tutorial to set up Flask and web applications
Before setting up Flask for Python, make sure you meet the requirements. 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 understanding of programming, data types, and for-loops is also advantageous. Flask is a good starting point to learn how to build web applications. You set up the framework as follows:
- Create a virtual environment 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- Install Flask. The best way to do this is to use the package management program pip. The appropriate command is:
$ pip install flask- Check if the installation has been successful by using this command:
python -c "import flask; print(flask.__version__)"$ python -c "import flask; print ( flask._version_ )"- Now you can test Flask and create a basic application. To do this, open a file in your directory. Here, we call it start.py and use nano to access it:
$ nano start.py- 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"-
Save and close the file.
-
Use the environment variable FLASK_APP to point Flask to the location of the corresponding file:
$ export FLASK_APP=start- Use FLASK_ENV to export the file in developer mode:
$ export FLASK_ENV=development- Now run the application:
$ flask runThe 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 streamlined framework than Flask Python. Flask is quick to install and use.
✓ Flexibility: The flexibility that Flask offers is also outstanding. You have the freedom to solve each problem individually and can implement exactly the libraries you actually need. This allows you to approach every project in a fully customized way.
✓ Learning curve: You’ll see quick results when following a Flask tutorial. The framework is intentionally designed to be simple, yet it also allows you to work on advanced projects. Flask is therefore a great choice for both beginners and professionals 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 experienced developers. Questions and errors are rapidly answered and solved.
Cons
✗- Scope: Depending on intended use, its minimalist scope can be disadvantageous. All tools require individual installation. Alternative frameworks offer significantly more pre-installed functions.
✗- Dependency on third-party providers: The use of external libraries is always a possible source of errors, but Flask depends on them.
✗- Maintenance: While other frameworks handle maintenance automatically and fix potential issues on their own, Flask leaves this responsibility 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 understanding of how Flask works, let’s look at a simple example that illustrates the core concepts of the web framework. We’ll create a small web application 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 dynamically 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)pythonHere’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>htmlWith @app.route, we define different endpoints — URLs 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 personalized 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 demonstrate 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 traditional websites and API endpoints. Thanks to templates, dynamic content can be easily integrated into HTML without having to manually update the page.
This code is only a minimal example for a Flask tutorial and is meant to illustrate the core concepts. In a real application, you would also need to consider aspects such as error handling, security, data validation, and a clean project structure to ensure the app remains stable, reliable, and easy to maintain.
Flask Extensions
Since Flask is designed to be very minimalistic, many useful features like database integration, authentication, or form validation are not built in. To add these functions, developers rely on Flask extensions, which are created and maintained by the community. These extensions can be easily integrated into a Flask application and significantly expand its functionality — without modifying the framework itself. This approach allows developers to choose exactly the components they need and build their apps in a modular way. Extensions typically follow the same design principles as Flask itself and are well-documented.
Examples of important Flask extensions include:
- Flask-SQLAlchemy: An extension for database integration. It integrates the popular SQLAlchemy ORM into Flask and enables easy interaction with databases using Python classes.
- Flask-WTF: This extension supports the creation and validation of web forms. It offers security features such as CSRF protection and simplifies handling user input.
- Flask-Login: As the name suggests, Flask-Login handles user management and authentication. It manages login states, sessions, and access control for specific routes.
- Flask-Migrate: With Flask-Migrate, you get database migration functionality that automatically manages changes to your database schema. It’s ideal for use alongside Flask-SQLAlchemy for structured updates.
- Flask-RESTful: This extension simplifies the creation of REST APIs. It provides standardized handling of resources, routes, and HTTP methods such as GET, POST, PUT, and DELETE.
Project structure and best practices
For Flask projects, it’s recommended to start with a clear and well-structured project organization right from the beginning. While small apps can technically run from a single file, a clean structure makes maintenance and further development much easier.
For larger projects, it’s common to create directories 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 subdirectories for blueprints, models, forms, and utilities to keep functions logically separated. Blueprints make it possible to design different components of the app modularly — for example, a user management system or a blog section.
Best practices also recommend keeping configuration values such as database URLs or secret keys in a separate config.py file or storing them as environment variables. Continuous logging helps detect errors early and track the app’s behavior. It’s also a good idea to use virtual environments to manage dependencies cleanly. Additionally, version control with Git is considered standard practice to keep changes transparent and maintainable.
- Professional templates
- Intuitive customizable design
- Free domain, SSL, and email address
Flask security and testing
Security and testing are not optional extras but essential components of a professional Flask application — and should never be overlooked in any Flask tutorial. By focusing on encryption, input validation, secure configurations, and automated testing from the very beginning, you can develop stable and secure web applications that can be easily expanded later on.
Security in Flask
Because of Flask’s minimalist design, developers are responsible for ensuring the security of their applications. A fundamental layer of protection is the use of CSRF protection for forms, especially when handling user input. The Flask-WTF extension provides proven mechanisms 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 validation is equally important to prevent SQL injection, XSS attacks, and other types of manipulation.
For sessions and cookies, it’s important to enable the HttpOnly and Secure flags to protect sensitive data. Configuration details such as database URLs or API keys should be managed through environment variables or separate configuration 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 application. Unit tests are used to check individual functions in isolation, while integration tests verify the interaction between multiple components.
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 automatically test routes, templates, and API endpoints. It’s especially important to write and update test cases regularly — particularly when adding new features — to prevent regressions. Combined with Continuous Integration, this approach helps ensure that your app remains stable and reliable even as it evolves.


