Python Flask tutorial

Filed Under: Python

Welcome to Python Flask tutorial. In previous lesson we have learnt about python lambda. Python flask is an API that helps us to build web based application in python. Let’s get started with python flask tutorial for beginners now.

Python Flask

First of all, we have to install python flask module. You can do it either by command prompt or by the help of IDE. I am using PyCharm Community Edition 2017.2. So I will install Flask using this IDE.

Open PyCharm then, click on file>settings. Then expand project and click on the Project Interpreter. You will see as following:

Python Flask install

I have already installed Flask, so the list is showing Flask. You have to click the + button on the right side of the window.

Then Available package window will pop up. In the search bar type Flask, then it will appear.

Click on Flask and in the bottom of the window press install. Flask will be installed to your python if you are connected to the internet.

You can install python flask module using pip through below command.


$pip install flask

So our installation of python flask module is done. Now we will start coding.

First Web page on Python Flask

Create a new project named FlaskTutorial. Then I am creating a python file named Main.py. In this file we have the following code segment:


# importing flask module
from flask import Flask

# initializing a variable of Flask
app = Flask(__name__)


# decorating index function with the app.route
@app.route('/')
def index():
   return "WELCOME!!! This is the home page"

if __name__ == "__main__":
   app.run()

Then run the python file and you will see following in the console log:


 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Now open your browser and copy paste the url (http://127.0.0.1:5000/) that is shown in the console. Then you will get html response like below image.

python flask example

So this is our basic webpage served by python flask.

Explanation of the Code

In the very first line we have imported Flask class of the flask module.

Then @app.route() is the decorator that is decorating the index() function.

And we are setting the url of the index page as only ‘/’.

The index() function returns a string which we see in the webpage. We can return html code also here. Finally we are checking whether the __main__ is directly running or not. If yes then running the app. Then we see the result in the browser.

Python Flask Tutorial

Now let’s look at another example where we will submit some data in the form and then display it in the next page.

First create a templates folder. In this templates folder create two html file. As following:
python flask tutorial

login.html
Now write the login.html code as shown below.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Home Page</title>
</head>
<body>
<h1> Welcome to the Flask Tutorial</h1>
<h4>Please Register to Get the tutorials</h4>
<form method="post" action="/FlaskTutorial">
    <input type="text" name="email" placeholder="Enter Email Address">
    <br><br>
    <input type="password" name="pass" placeholder="Password">
    <input type="submit" value="Submit" name="ok"/>
</form>
</body>
</html>

The main functionality of this html file is to create a form having two input field and a submit button. Notice in the form tag we have written action="/FlaskTutorial". We will discuss about it later. Right now just remember it. All other is as usual for a html file.

Now to see the output write in the Main.py file. As we will use template of html, so in the first line we have imported render_template.


# importing flask modules
from flask import Flask, render_template, request

# initializing a variable of Flask
app = Flask(__name__)


# decorating index function with the app.route with url as /login
@app.route('/login')
def index():
   return render_template('login.html')


if __name__ == "__main__":
   app.run()

In the browser paste this url ( http://127.0.0.1:5000/login ) and enter. You will see the output as below:

python flask tutorial

Now we want to do what the submit button do. Submit button will send the email address to another Html file named success.html that will show the email address with a success message.

Now let’s write the success.html code as shown below.

success.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Success</title>
</head>
<body>
<center><h2>You have successfully registered with email {{ email }} </h2></center>
</body>
</html>

Notice that in the body tag there is a double curly brace. Inside this the email is the value that is sent from the login page. All other is as usual html code.

Now again back to the Main.py file, we have to write the following code.

Main.py


# importing flask module fro
from flask import Flask, render_template,request

# initializing a variable of Flask
app = Flask(__name__)


# decorating index function with the app.route with url as /login
@app.route('/login')
def index():
   return render_template('login.html')


@app.route('/FlaskTutorial',  methods=['POST'])
def success():
   if request.method == 'POST':
       email = request.form['email']
       return render_template('success.html', email=email)
   else:
       pass
if __name__ == "__main__":
   app.run()

Notice that we have added another route named /FlaskTutorial. This one takes another argument named methods. In the return function we have sent an argument name email that we get from the text field of the login.html using the action=/FlaskTutorial and we have embed it in the success.html file.

Now if we run the Main.py, open browser with the url and give input as follows:

python flask example

Then pressing submit it will output:

python flask tutorial

So this is how you can send data from one html file to another html file using python flask. Download the complete code Here.

You can also send these data to your database using python mysql. To write python code in the html file you have to start with {% # some statements of python for inserting values in the database %}. Start playing with python Flask.

That’s all for python flask tutorial for beginners.

Reference: Github, Official Webpage.

Comments

  1. sanjee says:

    could u tell what ,blogger s/w u r using…………?
    bcz when i move cursor on code ,it allowing me to copy codes……….

    thanks in advance

  2. Saurabh Suthar says:

    Its showing erroe like this. I need help.
    “C:\Users\dr kiran\PycharmProjects\untitled\venv\Scripts\python.exe” “C:/Users/dr kiran/PycharmProjects/untitled/gg.py”
    C:\Users\dr kiran\PycharmProjects\untitled\venv\Scripts\python.exe: can’t open file ‘C:/Users/dr kiran/PycharmProjects/untitled/gg.py’: [Errno 2] No such file or directory

    Process finished with exit code 2

  3. Chandu says:

    HI , Thanks for the POST. Could you share any advanced tutorials on Flask please

  4. Balasubramanian Duraisamy says:

    Hi,

    i tried above Flask code in Pycharm 2018 and getting below error

    Error:-

    http://127.0.0.1:5000/

    Not Found
    The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

    1. Pankaj says:

      Can you please check the console log and see if there is any error? If no error, then what is the message getting printed as “Running on xxx”? Also try to run through command line if possible.

      1. Gustavo Bustamante da Rosa says:

        after include the argument ‘/login’ into the line @app.route(‘/login’)
        I needed to use http://127.0.0.1:5000/login to see the page working

        is it expected?

  5. aishwarya says:

    we instaled the PyCharm Community Edition 2017.2.Given steps are doned,Now i want to do create pycharm,how can i do that

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages