Blog

Python Flask Tutorial For Beginners

  • (4.0)
  • | 421 Ratings

Introduction:

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.

  • It’s ease of use
  • Provision of a built-in development server and a debugger
  • Provision for integrated unit testing support
  • Provision for RESTful request dispatching
  • Completely WSGI 1.0 compliant and Unicode based
  • Provides a great deal of documentation for various scenarios to explore
Enroll now for the ultimate Python Training from Mindmajix.

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 the 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 how to achieve that as well.

Related Page: Introduction to Python Programming

Python Flask Uses

Let’s see Python Flask with an example:

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 with this, you could set up Python and then have a virtual environment setup 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 the routing logic in order to ease the process of remembering the application-specific URLs. It also provides the 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).

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 ‘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 by accessing the URL -> http://localhost:5000/welcome/Hulk. Accessing that would display  the following on the browser:

Hey there, Hulk!

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 the variable part of the URL. The following code snippet uses the use of url_for() function.

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 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() 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!!!

Frequently Asked Python Interview Questions & Answers

Conclusion:

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.

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!