Fundamentals of Flask

Fundamentals of Flask

Flask is the most easy to learn framework.

Initializing Flask in python file

  1. Create a python file with .py extension

  2. Then we import Flask into our application. Use the below code.

from flask import Flask
  1. Declare variable as your app name
app = Flask(__name__)
  1. The setup running of app
If __name__ == "__main__":
app.run(debug="True",host="0.0.0.0",port="6000")

The above code says if the app is execute directly from the file then run the app or not.

  • Debug=True, it says that debugging is turned on

  • Host="0.0.0.0", it means we say python engine to run app on our default local host

  • Port="6000", tells on what port the app should be running.

Url Routing

Url Routing is the basic and most important feature in flask. Which allows us to give a specific unique path in Url to load documents or templates of our application. The Url paths are associated with pages content.

Ex. If our website has a contact page we need to add path as follows www.mywebapp.com/contact

Here contact is a path where our page is present

Print Hello World with Flask

Here we will learn how to insert content on that particular path

@app.route("/")
def homepage():
     return "<h1>Hello World</h1>"

So the above code will create a html page with a Hello world as header on the default path ("/") forward slash refers as the default path which loads when the web app is loaded it's basically the main page. I don't need any character path.

Dynamic Routing

Dynamic Routing refers to the dynamic path name which is changed as per users requirement

@app.route("/square/<int:number>")
def calculate_sqaure(number):
    return number ** 2

Here we are creating a path where there are two path name www.myapp.com/square/number_enteredbyuser the last path should be the number whose square will be printed on the page. The dynamic thing in this path is that the number is not static and differs from user to user. Here int:number here number is a variable which takes value from the user and stores in it and int is a converter which converts the value from string to integer.

! By default any value entered by user is string. No matter you enter special characters, numbers or boolean

The function is given a parameter of variable number which contains the value entered by user. After that the function returns the square value of the number in the page