Create a python flask application

How to setup a python flask application

Python being one of most used language in the world, makes it very easy to develop web applications.

In Python several different frameworks to develop web applications. Two of most popular frameworks are

  1. Django
  2. Flask

Django is mainly used for large applications and Flask is mainly used for light weight applications. In this article we are going to cover the basics of Python flask.

Steps to setup a python flask application

Step 0 : Configuration

  • Install Python 3: Go to Python.org and install the latest Python package (You can use python 2 as well, but here we will be using python 3).

    Verify if installation is successfull, by opening the command line(in windows) or open terminal (in MacOs or linux) and type python --version. If python is installed successfully, version will be displayed.

  • Visual Studio Code : We will using visual studio code as our IDE. You can install it from here Visual Studio homepage

Step 1

Now we need to install flask. Open Visual Studio Code and open a new terminal. There type below command. This will install flask. powershell pip install flask

Step 2:

Create a new .py file and import flask.

from flask import Flask , render_template , request

As we can see there are other libraries other than Flask that we need to use. So run below command to install the rest of them powershell pip install request pip install render_template

Step 3 :

Now lets create a .html file.

Create a new folder called ‘templates’ in the project root directory. Name it as ‘index.html’. In this html add the below HTML code

<h1>Hello World!</h1L

As we see from above code , we are going to display ‘Hello World!’ in our our example Python application.

Step 4:

Now coming to the final step, all we need to do is to add routing in python application for it to open ‘index.html’ file. Routing is like an address for a web page.

So in your main python file, add below code,

@app.route('/')
def index():
    return render_template("index.html")

This makes the default url for our application route to index.html.

And that’s it! we have a default address for ‘index.html’ file.

Now if you go to your terminal and type,

flask run

The python application will be available. Open any browser and type in

localhost:5000

Your application will be up and running!

Bonus Step :

If you want route ‘index.html’ to something else like localhost:5000/hello, in your main python file change the routing, as show below,

app.route('/hello')
def index():
    return render_template("index.html")

Stop and Start the flask application and go to localhost:5000/hello, index.html will be rendered.

Check more articles on Python here