Flask Framework

Neha Kumawat

a year ago

Flask is micro-framework which has very little dependency on external libraries. It is a very light framework and gives us freedom to do whatever we want.
In this chapter, we are going to build a project using Python and Flask framework.

Flask Startup and Configuration

Like most widely used python libraries, the Flask package is installable from the Python Package Index (PPI). Let’s create a directory first (In this chapter, we have created a directory called flask project) then created a virtual environment (and called it flaskEnv) where all the project related dependencies will be loaded (including flask). You can also install flask-sqlalchemy so that your flask application has a simple way to communicate with the SQL database.
After installing the flask, your flaskEnv (our virtualEnvironment name) will show something like below −

Creating an app with flask

By installing flask, we can create a simple “hello application in flask” with very few lines of code as follows −
Type the following in the terminal −

$python flaskapp.py
And you can see the following output −
Running on http://127.0.0.1:5000/ or on localhost:5000
Below is the explanation of what we did in our example code −
  • Firstly, we import the Flask class library. An instance from this class is the WSGI app.
Firstly, we import the Flask class library. An instance from this class is the WSGI app.
  • Secondly, we create an instance of this class. Application package or module name is our first argument. It is mandatory that flask knows where to find static files, templates and other files.
Secondly, we create an instance of this class. Application package or module name is our first argument. It is mandatory that flask knows where to find static files, templates and other files.
  • Next is the route() decorator we use to know which URL should trigger our method/function.
Next is the route() decorator we use to know which URL should trigger our method/function.

Creating URL Routing

URL Routing makes URLs in your Web app easy to remember. We will now create some URL routes −

/hello
/members
/members/name
We can write the following code based on the above URL and save it as app.py.

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
   return "Index!"
	
@app.route('/Hello')
def hello():
   return "Hello, World!"
	
@app.route("/members")
def members():
   return "Members"
	
@app.route("/members//")
def getMember(name):
   return name
	
if __name__ == '__main__':
   app.run(debug=True)
To learn more about python, visit the InsideAIML page.

Submit Review