Flask in Python Simplified – Part 2 ( Route )

Reading Time: 3 minutes

Flask in Python (Routes) – In this Series, we are going to learn the complete Flask framework step by step. This is part two of this series.

In this Part, We are going to learn about the route in the flask.

If you missed the first part please find the link here and read that amazing flask in python Installation guide with your first Hello Flask Program.

Every web framework is use URL to server end users request, We can use a different pattern of URLs.Routes help us to make URLs user friendly and serve content to the user(Such as https://technetconsultancy.in/blog/ or  https://java4school.com/constructor ).

@app.Route(‘/’) is a  decorator used in the flask to assign URLs in our apps.

If we are writing route like this @app.Routes(‘/’)  for that URL will be like this if you running on localhost ( http://127.0.0.1:5000)

Here is sample code

 

from flask import Flask

app = Flask(__name__)

@app.route(‘/’)

def index():

return ‘<h1> Hello ! </h1>’

 

It will show Hello on Screen when you open http://127.0.0.1:5000

Another example code

from flask import Flask

app = Flask(__name__)

@app.route(‘/’)

def index():

return ‘<h1> Hello ! </h1>’

@app.route(‘/home’)

def home():

return ‘<h1> You are at Home ! </h1>’

@app.route(‘/about’)

def about():

return ‘<h1> You are at About ! </h1>’

if __name__ == ‘__main__’:

app.run(host=’0.0.0.0′, port=5000)

 

routes example

 

 

 

We can have multiple routes with a single function by stacking additional route decorators above any route.+

from flask import Flask

app = Flask(__name__)

@app.route(‘/’)

@app.route(‘/index’)

@app.route(‘/home’)

def index():

return ‘<h1> Hello Flask ! </h1>’

multiple routes , flask in python

The above is a valid program with three different routes for a single output Hello Flask!

 

By default, app.route use the GET method if you want to use another method instead of getting like a POST or PUT. Define the method inside the declarator as shown below.

@app.route(‘/home’,methods=[‘POST’,’GET’])

We can pass multiple methods in the app.route decorator.

 

Code Part is coming on 3 April 2020 this and other interesting concepts.

 

Keep reading this will update with other routes concept for the flask in python.

 

 

 

 

Leave a Comment

Need Help? Chat with us