Building a Simple Flask Application

Building a Simple Flask Application

Getting started with Python Flask

Table of contents

No heading

No headings in the article.

Flask is a popular Python web framework used for developing web applications. It is lightweight, flexible, and easy to use, making it an excellent choice for building small to medium-sized web applications. In this article, we will walk through building a simple Flask application that displays a web page with some text.

Prerequisites Before we start, we need to make sure we have Python and Flask installed on our computers. If you haven’t already, download and install Python from the official website. Once installed, open your terminal or command prompt and type the following command to install Flask:

pip install Flask

Once Flask is installed, we can start building our simple Flask application.

Creating the Application First, create a new folder called “simple_app”.

mkdir simple_app

Inside the folder, create a new Python file called “app.py”.

touch app.py

After creating the app.py file, open it in an IDE or text editor. This is where we will write our Flask application.

In app.py we need to import Flask and create an instance of the Flask class:

from flask import Flask
app = Flask(__name__)

The __name__ argument is a special variable in Python that represents the name of the current module. When we use __name__ as the argument for Flask, it tells Flask where to find the resources it needs for the application.

Next, we need to define a route that will display a web page when a user visits the application. To do this, we use the @app.route decorator and define a function that returns the text we want to display:

@app.route('/')
def home():
    return 'Welcome to my simple Flask application!'

In this example, we defined a route for the root of the application (i.e., /). When a user visits the root URL, Flask will call the home() function and return the text "Welcome to my simple Flask application!".

Finally, we need to start the Flask application by adding the following code at the bottom of app.py:

if __name__ == '__main__':
    app.run()

Here is the complete code of “app.py”:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Welcome to my simple Flask application!'

This code checks if we are running the script directly and starts the Flask application if we are. We can now run our Flask application by navigating to the simple_app folder in the terminal and run the command:

flask run

This will start the Flask development server and output the following message:

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Eureka 🎉

You have successfully made your first application with Flask! Stay tuned with us to see more exciting articles like this!

Have a great day!!!