Installing Flask using pip tool
We can install Flask using Python pip tool. As we are using Python3, the below command will install Flask framework on to your machine.
$ pip3 install flask
The above command will install Flask and its dependencies.
Writing our first Flask application
We will write a simple Flask application with two routes, index route (“/”) and something line “/
<user>” route. Route is nothing but the URL structure. Before that we will create the structure of our application:
- Create a folder called flask-app.
- Create a file called simple_flask.py inside flask-app folder.
Copy the below code to simple_flask.py file:
Execute the application locally using
$ python3 simple_flask.py
Flask comes with inbuilt development server which runs on http://127.0.0.1:5000. Open the link in the browser and you will see the message “Welcome to Flask”. If you change the route to http://127.0.0.1:5000/saisyam you will see the message “Hi saisyam!”.
When the base URL is called, I mean, http://127.0.0.1:5000, Flask will check for the appropriate root, in our example, it is:
@app.route('/') def index(): return "Welcome to Flask"
The base route is “/” and hence Flask will show the message under this route. Similarly for the second route, http://127.0.0.1/saisyam the below code is executed:
@app.route('/<user>') def hi_user(user): return "Hi "+user+"!"
<user> is a variable which is substituted with a string, in our case it is, “saisyam”.
So, we have successfully created our first Flask web application. Hope you got the basic idea of how routes work in a web application.