Flask is a very important and popular web framework in python to create web applications, APIs, Machine Learning applications, etc. In my last few post, I discussed web application development using Django. Flask framework is more explicit and easier to learn than the Django framework. Flask is built on top of the WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine.
- Django Basic login logout tutorial
- Django stylish login logout tutorial
- Integrate Plotly Dash in Django
Basic Skeliton of Flask Python Framework
You can install Flask package by executing the below command. Note: Python 2.6 or higher is required to install Flask.
!pip install Flask
Now let me explain Flask python web framework with the below code.
Note: I use PyCharm IDE to run Flask code, you can use your preferred IDE
from flask import Flask # WSGI Application app = Flask(__name__) @app.route('/') def welcome(): return "This is the home page of Flask Application" if __name__=='__main__': app.run() # app.run(debug = True)
By running the above code string “This is the home page of Flask Application” will display on the home page (http://127.0.0.1:5000/)
Here in this code:
- ‘/’ URL (home page) is bound with wellcome() function. When the homepage of the webserver (default url: http://127.0.0.1:5000/) is opened in the browser, the output of this function (display mentioned string) will be rendered accordingly.
- @app.route(): Modern web frameworks use more meaningful URLs so that user can remember the URL and access that URL directly. route() decorator does this job in Flask. route() decorator bind the URL to a function.
In our example the URL (‘/’) is associated with root URL. and welcome() function is inside @app.route(‘/’) decorator. So it will show the string “This is the home page of Flask Application” (return of welcome() function) on the home page.
If we use @app.route(‘/page1’), it will show the string “This is the home page of Flask Application” (return of welcome() function) in http://127.0.0.1:5000/pag1 URL
- run() function is to start Flask application. Now let’s say you started Flask application and you made some changes to the code and that changes you want to reflect in the browser at the same time. To do this you can enable debug (debug = True) option. So now run function should look like: run(debug = True)
In this tutorial, I have explained Flask Python web application framework with basic skeleton Flask code. In the next few Flask tutorials, I will show you how you can develop advanced Machine Learning web applications using Flask Python framework.
Hi there, I’m Anindya Naskar, Data Science Engineer. I created this website to show you what I believe is the best possible way to get your start in the field of Data Science.