Why build Python web applications with Flask, you may ask? There are various reasons for which Python Flask is chosen for and the very important reasons are provided here for your quick reference.
|If you want to become a Python certified professional, then visit Mindmajix - A Global online training platform: “Python Certification Course”. This course will help you to achieve excellence in this domain.|
After taking a look at the advantages that Flask brings to the table in web application development with Python, let us try to see what exactly is Flask and how / why is it beneficial? Flask is a Web application framework that was actually written in pure Python. Now that we have brought about a technical jargon called Web application framework, let us understand that too. A Web application framework is nothing but a collection of libraries put together to ease the whole process of web applications for a web application developer. It is completely based on the Werkzeug WSGI (Web Server Gateway Interface) toolkit and Jinja2 template engine. With a very basic understanding of Python and some basic HTML, any Python enthusiast can excel in Flask within no time. We shall now look at an example of how to achieve that as well.
|Related Article: Python Language Introduction|
As a pre-requisite to get into this, the developer environment should be having Python 2.6 or above with all the required Flask extensions. If you are a total stranger to this, you could set up Python and then have a virtual environment set up for the required development. To keep this article intact with the required details, we will not be going into the nitty-gritty details of the whole setup itself. Once you have your installation ready, you can test your Flask installation with a sample as shown below:
from flask import Flask app = Flask(__name__) @app.route(‘/’) def helloWorld(): return ‘Hello guys, this is your Hello World program…’ if __name__ == ‘__main__’: app.run()
You should be wondering what these lines mean to you if you are seeing them for the very first time. Let us go line by line to understand everything, starting with the first line which is a mandatory step to import the flask module into your project. The next line indicates that the FlaskDemo class takes an argument named __name__. The URL that is mentioned is bound to the method helloWorld() and hence when the home page of the web browser is hit, it will render this welcome message, and finally, the run() method runs the application on your local development server.
What you’ve just seen is a default mapping to the only method available in your program and what if you want to make additional mappings to different methods for various other functionalities, let us take a look at how this can be achieved? To answer that, you could do that in two different ways:
@app.route(‘/welcome’) def helloWorld(): return ‘Hello guys, this is your Hello World program…’
Here we have used the route() decorator in Flask, that binds a specific URL to a function. Most of the modern web frameworks use routing logic in order to ease the process of remembering the application-specific URLs. It also provides ease of use to the users to get to the specific page without having to bother to come from the home page (of course, after logging in to the application only).
|Related Article: Variable Types in Python|
The same can be achieved using the add_url_rule() function as well, let us take a look at that as well. This will also perform the very same action as the code snippet shown earlier but in a different manner.
def helloWorld(): return ‘Hello guys, this is your Hello World program…’ app.add_url_rule(‘/’, ’welcome’, helloWorld)
Alongside that, you could build your URL dynamically as well by providing the variable parts to the rule parameter. You will now look at a code snippet that contains a variable part in the rule part of the route() decorator. By the following code snippet, we would also be trying to append this to the ‘welcome’ URL part. Let us take a look at the following code snippet.
from flask import Flask app = Flask(__name__) @app.route(‘/welcome/’) def helloName(): return ‘Hey there, %s!’ % name if __name__ = ‘__main__’: app.run(debug=True)
To run this program, you could save this under the name of HelloName.py and then run it from the Python shell. Accessing that would display the following on the browser:
Hey there, Hulk!
|Related Article: Advanced Python Interview Questions|
Dynamic URLs can also be built using the function
url_for() for a specific function as well. This function accepts the first parameter as the function name and then on, the next arguments are considered to be the variable part of the URL. The following code snippet uses the use of
from flask import Flask, redirect, url_for app = Flask(__name__) @app.route(‘/batsman’) def helloBatsman(): return ‘Hey there, batsman!!!’ @app.route(‘/bowler/’) def helloBowler(bowlername): return ‘Hello %s, please bowl well today!!!’ % bowlername @app.route(‘player/’) def helloPlayer(playername): if playername == ‘Virat’: return redirect(url_for(‘helloBatsman’)) else: return redirect(url_for(‘helloBowler’, bowlername = playername)) if __name__ == ‘__main__’: app.run(debug = True)
In the above script, you have a function named helloPlayer() that accepts a value and here I match it with ‘Virat’ and if it is ‘Virat’ then I consider him a batsman and then redirect to the method helloBatsman(), or else he is a bowler and gets redirected to helloBowler() a method. You could save the above code snippet and run this from the Python Shell and open a browser to access the URL -> http://localhost:5000/player/Virat to see the following response.
Hey there, batsman!!!
|Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!|
In this article, we have tried to understand what Flask is all about and how it gets along with Python. We have also tried to understand the advantages that it brings to the table and how easy it is to go ahead and program web applications with Python along with Flask. We have also gone through simple code snippets to understand how easy it gets to know about Python along with Flask again and also understood some nitty-gritty details. Hope you would have got all the information that you were in need to understand what is Flask in conjunction with Python.
Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!
|Python Training||Jan 15 to Jan 30|
|Python Training||Jan 17 to Feb 01|
|Python Training||Jan 22 to Feb 06|
|Python Training||Jan 24 to Feb 08|
Ravindra Savaram is a Content Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.
Copyright © 2013 - 2022 MindMajix Technologies