Python Web Development Libraries - Flask Framework



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). Lets create a directory first (In this chapter, we're using flask virtual environment 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 SQL database.

(myenv) D:\Projects\python\myenv>pip3 install flask flask-sqlalchemy

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 −

main.py

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello, Flask!"
    
if __name__ == '__main__':
   app.run(debug=True)   

Type the following in the terminal −

(myenv) D:\Projects\python\myenv>py main.py
 * Serving Flask app 'main'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 109-558-382

And you can see the following output −

Running on http://127.0.0.1:5000/ or on localhost:5000

Running Localhost

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.

  • 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.

Advertisements