The Wayback Machine - https://web.archive.org/web/20240905235524/https://www.geeksforgeeks.org/flask-creating-first-simple-application/
Open In App

Flask – (Creating first simple application)

Last Updated : 18 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

  1. 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. 
  2. 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.
  3. 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:
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"]


Previous Article
Next Article

Similar Reads

Documenting Flask Endpoint using Flask-Autodoc
Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features - Helps to document endpoints of
4 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 server.The data in the Session is stored on the top o
4 min read
How to Integrate Flask-Admin and Flask-Login
In order to merge the admin and login pages, we can utilize a short form or any other login method that only requires the username and password. This is known as integrating the admin page and Flask login since it simply redirects users to the admin page when they log in. Let's is how to implement this in this article. Integrate Flask Admin and Fla
8 min read
Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library - Flask-Minify. Advantages of MinificationWebsites load faster as fewer lines are there to upload and download.Ban
12 min read
Flask URL Helper Function - Flask url_for()
In this article, we are going to learn about the flask url_for() function of the flask URL helper in Python. Flask is a straightforward, speedy, scalable library, used for building, compact web applications. It is a micro framework, that presents developers, useful tools, and, features, for coding REST APIs, and backend data processing, of web apps
11 min read
How to Build a Simple Android App with Flask Backend?
Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries
8 min read
How to write a simple Flask API for hello world?
Prerequisites: Introduction to REST API REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set of rules/constraints for a web application to send and receive data. In this article, we are going to learn how to create a simple REST API that returns 'Hello World', with the help o
3 min read
Creating Custom Commands in Flask
This article revolves around how to create custom commands in flask. Every time one runs flask using flask run, run is actually a command which initiates a function called run in flask config files. Similarly, if you have ever used something like flask migrate then you are probably familiar with flask DB migrate or upgrade. To create such a manual
2 min read
Creating Your First Application in Python
Python is one of the simplest programming language out there. In fact, it was developed for the sole purpose of simplifying the process of learning a programming language and exposed beginners to the concepts of Programming. In this article, we will be building a Python Application. Not to worry it won't be anything fancy or complex. But before we
5 min read
Creating first web application using Bottle Framework - Python
There are many frameworks in python which allow you to create a webpage like bottle, flask, django. In this article, you will learn how to create a simple app using bottle web framework. Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no dependencies other than the Pyth
2 min read
Creating your first application using Kivy
Prerequisites: Introduction to Kivy, Hello World in Kivy Kivymd is graphical user interface library in python based on kivy that allows you to develop multi-platform applications on Windows, MacOS, Android, iOS, Linux, and Raspberry Pi. The best thing about kivy is, it performs better than HTML5 cross-platform alternatives. Kivymd requires fewer li
2 min read
Profile Application using Python Flask and MySQL
A framework is a code library that makes a developer's life easier when building web applications by providing reusable code for common operations. There are a number of frameworks for Python, including Flask, Tornado, Pyramid, and Django. Flask is a lightweight web application framework. It is classified as a micro-framework because it does not re
10 min read
Create Postman collection from Flask application using flask2postman
Prerequisite: Introduction to Postman, First App using Flask Since Postman is gaining popularity in the development domain, this article explains a way in which it can be easily integrated with Flask APIs using command-line utility written in Python. We will be using the flask2postman module. But you will be why this module. Here's why - It is a st
3 min read
Build a Flask application to validate CAPTCHA
In this article, we are going a build a web application that can have a CAPTCHA. CAPTCHA is a tool you can use to differentiate between real users and automated users. CAPTCHAs are usually found on the login pages or on payment pages. What is CAPTCHA? Captcha is strategy used to ensure sites against spam. Objective is to prevent intuitive sites fro
5 min read
Load Balancing Flask Application using Nginx and Docker
Load balancing means efficiently distributing the incoming traffic to different server instances. Nginx is open-source software that can be used to apply load balancing to backend systems. Nginx also can be serve services such as reverse proxy, caching, web server, etc. Docker is a tool that gives a virtualization solution for a complete software p
5 min read
How To Use Web Forms in a Flask Application
A web framework called Flask provides modules for making straightforward web applications in Python. It was created using the WSGI tools and the Jinja2 template engine. An example of a micro-framework is Flask. Python web application development follows the WSGI standard, also referred to as web server gateway interface. It is recognized as the spe
5 min read
Implement ChatGPT in a Flask Application
You can build dynamic and interactive chat interfaces by integrating ChatGPT into a Flask application. This article's instructions can help you integrate ChatGPT into your Flask project and give users engaging chat experiences. Improve the user interface, try out new prompts, and look into new options to make your chat program more functional. Step
3 min read
Flask NEWS Application Using Newsapi
In this article, we will create a News Web Application using Flask and NewsAPI. The web page will display top headlines and a search bar where the user can enter a query, after processing the query, the webpage will display all relevant articles (up to a max of 100 headlines). We will create a simple user interface using HTML and bootstrap. You can
7 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 application SyntaxWe can run the Flask applicatio
4 min read
Python | Creating a Simple Drawing App in kivy
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial - Learn Kivy with Examples. Drawing App: In this we are going to create a simple drawing App with th
4 min read
Creating a simple browser using PyQt5
In this article we will see how we can create a simple browser using PyQt5. Web browser is a software application for accessing information on the World Wide Web. When a user requests a web page from a particular website, the web browser retrieves the necessary content from a web server and then displays the page on the screen. PyQt5 is cross-platf
4 min read
Creating a simple Range Slider in Bokeh
The range slider widget allows you to select a floating-point range from a slider with start and endpoints. The Bokeh widget RangeSlider consists of start and end values, a step size, an initial value, and a title. Syntax: range_slider = RangeSlider(start, end, value, step, title) range_slider.js_on_change("value", CustomJS(code)) Let us look at th
3 min read
Creating a simple JSON based API using Node.js
API (Application Programming Interface) results are commonly used by applications, sometimes to withdraw information from their huge databases, check the status of a particular data, or sometimes they depend on third-party APIs to display additional information related to users. Here we will make a simple public JSON based Chemistry API, which can
3 min read
Creating a Simple Image Editor using JavaScript
In this article, we will be creating a Simple Image Editor that can be used to adjust the image values like brightness, contrast, hue, saturation, grayscale, and sepia. Image editors allow one to quickly edit pictures after they have been captured for enhancing them or completely changing their look. Using a combination of various values, one can g
10 min read
Python | Create simple animation for console-based application
As we know Python is a scripting language, and can be easily used to automate simple tasks. In this article, we will learn how to create a simple console-based animation, which can be used while developing a console based project as a utility. We will try to replicate the loading animation as shown below: We will be using following modules - sys mo
2 min read
Building a Simple Application using KivyMD in Python
KivyMD is an extension of the Kivy framework. KivyMD is a collection of Material Design widgets for use with Kivy, a GUI framework for making mobile applications. It is similar to the Kivy framework but provides a more attractive GUI. In this article, we will see how to make a simple application in KivyMD using Screen, Label, TextFieldInput, and Bu
3 min read
Create a Simple Login Web Application with Encrypted Password in Java
Security is an important concept in any web application. We need to have the passwords stored in an encrypted way i.e. the passwords are not easily accessible by hackers or unauthorized users. Let's see a small demo application in this article using MySQL, Java, Servlet, and JSP technology. Step by Step Implementation Required MySQL Script -- Here
10 min read
Simple chat Application using Websockets with FastAPI
In this article, we'll delve into the concept of WebSockets and their role in facilitating bidirectional communication between clients and servers. Subsequently, we'll embark on the journey of building a real-time multi-client chat application. This application will empower numerous users to connect to the server via the WebSocket protocol, fosteri
6 min read
Simple Chatbot application using Python, GoogleAPIKey
Google-GenerativeAI is Google AI Python SDK. It uses Gemini to build AI-powered features. In this article, we will see how to create a Simple Chatbot application using Python GoogleAPIKey. What is Google-GenerativeAI?Google-GenerativeAI is nothing but Google AI Python SDK. It enables to use of Gemini to build AI-powered features and applications. T
4 min read
Create a Simple Form Application using React Redux
In this article, we make a simple project of form application built using React and Redux. The main purpose of the application is to collect user information through a form consisting of fields for name, email, message and submit button. It's built with React for the user interface and Redux for managing the form data. Prerequisites Nodejs and NPMR
3 min read
Article Tags :
Practice Tags :