Flask – (Creating first simple application)
Last Updated :
18 Aug, 2024
Building a webpage using python.
There are many modules or frameworks which allow building your webpage using python like a bottle, Django, Flask, etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you with the versatility to program with.
To understand what Flask is you have to understand a few general terms.Â
- WSGI Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications.Â
- Werkzeug It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases.
- jinja2 jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages.Â
Flask is a web application framework written in Python. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects.
Installation:
We will require two packages to set up your environment. virtualenv for a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries and the next will be Flask itself.Â
virtualenvÂ
pip install virtualenv
Create Python virtual environment
virtualenv venv
Activate virtual environment
windows > venv\Scripts\activate
linux > source ./venv/bin/activate
For windows, if this is your first time running the script, you might get an error like below:
venv\Scripts\activate : File C:\flask_project\venv\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For Â
more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ venv\Scripts\activate
  + FullyQualifiedErrorId : UnauthorizedAccess
This means that you don’t have access to execute the scripts.
To solve this error, run the powershell as admin, when you right click on powershell icon, choose the option ‘Run as adminstrator’. Now, the powershell will open in the admin mode.
Type the following command in Shell
set-executionpolicy remotesigned
Now, you will be prompted to change the execution policy. Please type A. This means Yes to all.
FlaskÂ
pip install Flask
After completing the installation of the package, let’s get our hands on the code.
Python
# Importing flask module in the project is mandatory
# An object of Flask class is our WSGI application.
from flask import Flask
# Flask constructor takes the name of
# current module (__name__) as argument.
app = Flask(__name__)
# The route() function of the Flask class is a decorator,
# which tells the application which URL should call
# the associated function.
@app.route('/')
# â/â URL is bound with hello_world() function.
def hello_world():
return 'Hello World'
# main driver function
if __name__ == '__main__':
# run() method of Flask class runs the application
# on the local development server.
app.run()
Save it in a file and then run the script we will be getting an output like this.

Then go to the URL given there you will see your first webpage displaying hello world there on your local server.
Digging further into the context, the route() decorator in Flask is used to bind a URL to a function. Now to extend this functionality our small web app is also equipped with another method add_url_rule() which is a function of an application object that is also available to bind a URL with a function as in the above example, route() is used.Â
Example:Â
def gfg():
return âgeeksforgeeksâ
app.add_url_rule(â/â, âg2gâ, gfg)
Output:Â
geeksforgeeks
You can also add variables in your web app, well you might be thinking about how it’ll help you, it’ll help you to build a URL dynamically. So let’s figure it out with an example.
Python
from flask import Flask
app = Flask(__name__)
@app.route('/hello/<name>')
def hello_name(name):
return 'Hello %s!' % name
if __name__ == '__main__':
app.run()
And go to the URL http://127.0.0.1:5000/hello/geeksforgeeks it’ll give you the following output.

We can also use HTTP methods in Flask let’s see how to do that
The HTTP protocol is the foundation of data communication on the world wide web. Different methods of data retrieval from specified URL are defined in this protocol. The methods are described down below.
GET : Sends data in simple or unencrypted form to the server.
HEAD : Sends data in simple or unencrypted form to the server without body.Â
PUT : Replaces target resource with the updated content.
DELETE : Deletes target resource provided as URL.
By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator. In order to demonstrate the use of the POST method in URL routing, first, let us create an HTML form and use the POST method to send form data to a URL. Now let’s create an HTML login page.
Below is the source code of the file:Â
HTML
<html>
<body>
<form action = "http://localhost:5000/login" method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "nm" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
Now save this file HTML and try this python script to create the server.
Python
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
@app.route('/success/<name>')
def success(name):
return 'welcome %s' % name
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
user = request.form['nm']
return redirect(url_for('success', name=user))
else:
user = request.args.get('nm')
return redirect(url_for('success', name=user))
if __name__ == '__main__':
app.run(debug=True)
After the development server starts running, open login.html in the browser, enter your name in the text field and click submit button. The output would be the following.

The result will be something like this

And there’s much more to Flask than this. If you are interested in this web framework of Python you can dig into the links provided down below for further information.
Flask – (Creating first simple application) – FAQs
What are the basic components of a Flask application?
1. Flask Object: Main app instance.
from flask import Flask
app = Flask(__name__)
2. Routes: Define URL mappings.
@app.route('/')
def home():
return 'Hello, World!'3. Templates: HTML files for rendering.
<!-- templates/hello.html -->
<h1>Hello, {{ name }}!</h1>
4. Static Files: Assets like CSS.
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">5. Request and Response: Handle data.
from flask import request, jsonify
@app.route('/json')
def json_example():
return jsonify({"message": "Hello, JSON!"})
How to handle routing in Flask?
1. Basic Route:
@app.route('/')
def home():
return 'Hello, World!'2. Dynamic Route:
@app.route('/user/<username>')
def show_user_profile(username):
return f'User: {username}'3. HTTP Methods:
@app.route('/login', methods=['POST'])
def login():
return 'Logging in...'4. Redirects and Errors:
from flask import redirect, url_for, abort
@app.route('/redirect')
def redirect_example():
return redirect(url_for('home'))
@app.route('/error')
def error_example():
abort(404)
What are the best practices for setting up a Flask environment?
1. Virtual Environments:
python -m venv venv
source venv/bin/activate
2. requirements.txt:
pip freeze > requirements.txt
3. Project Structure:
myapp/
âââ app.py
âââ templates/
âââ static/
âââ requirements.txt
4. Environment Variables:
import os
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
5. Flask Extensions:
pip install Flask-SQLAlchemy
How to deploy a basic Flask application?
1. Local Deployment:
python app.py
2. Production Deployment (Gunicorn):
pip install gunicorn
gunicorn -w 4 app:app
3. Deploy to Cloud:
heroku create
git push heroku master
4. Docker
FROM python:3.9
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "-w", "4", "app:app"]
Similar Reads
Flask Tutorial
This Flask tutorial is the latest and comprehensive guide designed for beginners and professionals to learn Python Web Framework Flaskone, one of the most popular Python-based web frameworks. Whether you are a beginner or an experienced developer, this tutorial is specially designed to help you lear
8 min read
Flask Setup & Installation
Flask Quick Start
Flask - (Creating first simple application)
Building a webpage using python.There are many modules or frameworks which allow building your webpage using python like a bottle, Django, Flask, etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you with the versatility to program wit
6 min read
How to Run a Flask Application
The backend server Flask was created fully in Python. It is a framework made up of Python modules and packages. With its characteristics, it is a lightweight Flask application that speeds up the development of backend apps. We will learn how to execute a Flask application in this tutorial. Run Flask
4 min read
Flask App Routing
App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. Example: In our application, the URL ("/") is associated with the root URL. So if our site's
3 min read
Flask - HTTP Method
In this article, we will learn how to handle HTTP methods, such as GET and POST in Flask using Python. Here, we will understand the concept of HTTP, GET, and HTTP POST, and then we will the example and implement each in Flask. Before starting let's understand the basic terminology: GET: to request d
8 min read
Flask - Variable Rule
In this article, we will discuss Flask-Variable Rule using Python. Flask is a microweb framework written in Python it is classified as a micro framework because it doesn't require particular tools or libraries, and it has no database abstraction layer form validation or any other components where pr
4 min read
Redirecting to URL in Flask
Flask is a backend server that is built entirely using Python. It is a framework that consists of Python packages and modules. It is lightweight which makes developing backend applications quicker with its features. In this article, we will learn to redirect a URL in the Flask web application. Redir
3 min read
Python Flask - Redirect and Errors
We'll discuss redirects and errors with Python Flask in this article. A redirect is used in the Flask class to send the user to a particular URL with the status code. conversely, this status code additionally identifies the issue. When we access a website, our browser sends a request to the server,
4 min read
How to Change Port in Flask app
In this article, we will learn to change the port of a Flask application. The default port for the Flask application is 5000. So we can access our application at the below URL. http://127.0.0.1:5000/ We may want to change the port may be because the default port is already occupied. To do that we ju
1 min read
Changing Host IP Address in Flask
In this article, we will cover how we can change the host IP address in Flask using Python. The host IP address is the network address that identifies a device on a network. In the context of a Flask application, the host IP address is the address that the application listens to for incoming request
2 min read
Serve Templates and Static Files in Flask
Flask Rendering Templates
Flask is a backend web framework based on the Python programming language. It basically allows the creation of web applications in a Pythonic syntax and concepts. With Flask, we can use Python libraries and tools in our web applications. Using Flask we can set up a web server to load up some basic H
13 min read
CSRF Protection in Flask
Let's see how you can manually protect your data using CSRF protection by doing a mini-project in Flask. In this, we will have to create a webpage containing 2 forms using Python one of them is having protection. By creating forms like these we can easily see the results and advantages of using CSRF
3 min read
Template Inheritance in Flask
Template inheritance is a very good feature of Jinja templating . Jinja is a web template engine for the Python programming language . We have seen that webpages of a website contains same footer , navigation bar etc. So instead of making same footer and navigation bar in all webpages separately , w
2 min read
Placeholders in jinja2 Template - Python
Web pages use HTML for the things that users see or interact with. But how do we show things from an external source or a controlling programming language like Python? To achieve this templating engine like Jinja2 is used. Jinja2 is a templating engine in which placeholders in the template allow wri
5 min read
How to serve static files in Flask
Flask is a lightweight Web Server Gateway Interface or WSGI framework for web applications written in Python. It is designed to make web application development fast and easy and can scale to complex applications. This article describes and demonstrates how to serve various static files in Flask. S
5 min read
Uploading and Downloading Files in Flask
This article will go over how to upload and download files using a Flask database using Python. Basically, we have a section for uploading files where we can upload files that will automatically save in our database. When we upload a file and submit it, a message stating that your file has been uplo
7 min read
How to Upload File in Python-Flask
File uploading is a typical task in web apps. Taking care of file upload in Flask is simple all we need is to have an HTML form with the encryption set to multipart/form information to publish the file into the URL. The server-side flask script brings the file from the request object utilizing the r
2 min read
Upload Multiple files with Flask
In online apps, uploading files is a common task. Simple HTML forms with encryption set to multipart/form information are all that is required to publish a file into a URL when using Flask for file upload. The file is obtained from the request object by the server-side flask script using the request
2 min read
Flask - Message Flashing
In this article, we will discuss Flask - Message Flashing. As we know best Graphical User Interface provides feedback to a user when users interact, as an example, we know that desktop applications use the messages box or JS for an alert purpose. generating like same informative message is easy to d
6 min read
Create Contact Us using WTForms in Flask
WTForms is a library designed to make the processing of forms easier to manage. It handles the data submitted by the browser very easily. In this article, we will discuss how to create a contact us form using WTForms. Advantages of WT-FORM:We don't have to worry about validators.Avoidance of Cross-S
3 min read
Sending Emails Using API in Flask-Mail
Python, being a powerful language donât need any external library to import and offers a native library to send emails- âSMTP libâ. âsmtplibâ creates a Simple Mail Transfer Protocol client session object which is used to send emails to any valid email id on the internet. This article revolves around
3 min read
User Registration, Login, and Logout in Flask
How To Add Authentication to Your App with Flask-Login
Whether it is building a simple blog or a social media site, ensuring user sessions are working correctly can be tricky. Fortunately, Flask-Login provides a simplified way of managing users, which includes easily logging in and out users, as well as restricting certain pages to authenticated users.
9 min read
Add User and Display Current Username in Flask
In this article, we'll talk about how to add a User and Display the Current Username on a Flask website. When we log in using our username and password, we will be taken to the profile page where we can see the welcome message and the username we created during registration. When additional users re
9 min read
Password Hashing with Bcrypt in Flask
In this article, we will use Password Hashing with Bcrypt in Flask using Python. Password hashing is the process of converting a plaintext password into a hashed or encrypted format that cannot be easily reverse-engineered to reveal the original password. Bcrypt is a popular hashing algorithm used t
2 min read
How to store username and password in Flask
We'll discuss how to save a Username and password on a Flask website in this article. We may view the welcome message and the username we chose when registering on the profile page after logging in with our username and password. The names of subsequent users who sign up using the login information
9 min read
Flask - Role Based Access Control
Flask is a  micro-framework written in Python. It is used to create web applications using Python. Role-based access control means certain users can access only certain pages. For instance, a normal visitor should not be able to access the privileges of an administrator. In this article, we will see
14 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the ser
4 min read
Flask Cookies
Flask is a lightweight, web development framework built using python language. Generally, for building websites we use HTML, CSS and JavaScript but in flask the python scripting language is used for developing the web-applications. To know more about Flask and how to run an application in Flask: Fla
5 min read
How to return a JSON response from a Flask API ?
Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Represent
3 min read
Define and Access the Database in Flask
Flask Deployment and Error Handling
Python Flask Projects with Source Code (Beginners to Advanced)
Flask, a Python web application framework, was created by Armin Ronacher. Known for its lightweight and efficient nature, Flask is designed for quick starts and accommodates complex applications. It is based on the Werkzeug WSGI toolkit and Jinja2 template engine. In this article, weâve curated a li
4 min read