Templates – In Flask

Templates are the structure of a website. Here in Python Flask. templates are treated as the views, which means these files are kept in separate folder, which will be dedicated to the UI elements, which we call templates.
 If we write the following code.

Python Code

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
   return '<html><body><h1>'Hello World'</h1></body></html>'
if __name__ == '__main__':
   app.run(debug = True)

we will get an output as an H1 tag element in the browser, which means that the return functionality can interpreter the HTML data. But the issue is, when we have a huge set of coding and that too with multiple variables being called inside the view, to show dynamic data on the page, we will have to move in and out many times. 
This is where the jinja2 comes in picture. jinja2 is a templating engine which helps in showing templates with dynamic data over Python.
The Flask is based on jinja2 templating engine, that is why its easy to return entire template as an output. The rendering of templates can be done using the render_template() function.
Have a look at the below example:

Python Code

rom flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
   return render_template(‘hello.html’)
if __name__ == '__main__':
   app.run(debug = True)

Here the entire hello.html file is passed as an argument in the render_template() function, which will be treated as a template to be rendered when user requests for the root page.
Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present.

  • Application folder
    • Hello.py
    • templates
      • hello.html

As we talk about the  web templating system, we refer to designing an HTML script in which the variable data needs to be dynamically inserted. Web template system is made up of template processor, template engine and some data source.
jinja2 is used by Flask as its templating engine. HTML syntax contains placeholders for variables and expressions which are replaced by values when the template is rendered.
The following code is saved as hello.html in the templates folder.

Hello .html

<!doctype html>
<html>
   <body>
   
      <h1>Hello {{ name }}!</h1>
      
   </body>
</html>

Next, run the following script from Python shell.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/<user>')
def hello_name(user):
return render_template('hello.html', name = user)

if __name__ == '__main__':
app.run(debug = True)

As the development server starts running, open the browser and enter URL as − http://localhost:5000/hello/Vikash

You will see the output as

Hello Vikash


The following delimiters are used to escape from HTML in jinja2

  • {% … %} for Statements
  • {{ … }} for Expressions to print to the template output
  • {# … #} for Comments not included in the template output
  • # … ## for Line Statements

Have a look at the example below, we have used a conditional statement in the template to show some data.The hello() function will accept the integer parameter in the URL rule, which will be passed to the hello.html template. Where it’s value will be compared with 50, and the rendering will be done accordingly.

The Python Script is as follows −

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/<int:score>')
def hello_name(score):
return render_template('hello.html', marks = score)

if __name__ == '__main__':
app.run(debug = True)

HTML template script of hello.html is as follows −

<!doctype html>
<html>
<body>

{% if marks>50 %}
<h1> Your result is pass!</h1>
{% else %}
<h1>Your result is fail</h1>
{% endif %}

</body>
</html>

You might have noticed a few things, like the conditional statements are enclosed in {%. %}
Run the Python script and visit URL http://localhost/hello/60 and then http://localhost/hello/30 to see the output of HTML changing conditionally.

Python loop constructs can also be employed inside the template. In the following script, the result() function sends a dictionary object to template results.html when URL http://localhost:5000/result is opened in the browser.

The Template part of result.html employs a for loop to render key and value pairs of dictionary object result{} as cells of an HTML table.

Run the following code from Python shell.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/result')
def result():
dict = {'phy':50,'che':60,'maths':70}
return render_template('result.html', result = dict)

if __name__ == '__main__':
app.run(debug = True)

Save the following HTML script as result.html in the templates folder.

<!doctype html>
<html>
<body>

<table border = 1>
{% for key, value in result.iteritems() %}

<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>

{% endfor %}
</table>

</body>
</html>

Here, again Python statements corresponding to the For loop are enclosed in {%..%} whereas, the expressions key and value are put inside {{ }}.

After the development starts running, open http://localhost:5000/result in the browser to get the output as a table.
Now as you have learnt about the templates and the way of rendering data inside the template move ahead to the following tutorials to learn more ..

Static Files – Flask

When you work for web development, you will need to use some files for javascript or CSS, here in FLASK when you need to add some static files, a special endpoint is used named as static. These static files are served from static folder in your package or next to your module and it will be available at /static in the application.
Example

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)

The HTML script of index.html is given below.

<html>

   <head>
      <script type = "text/javascript" 
         src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
   </head>
   
   <body>
      <input type = "button" onclick = "sayHello()" value = "Say Hello" />
   </body>
   
</html>

hello.js contains sayHello() function.

function sayHello() {
   alert("Hello World")
}

Variables in Flask

In Flask, a variable is created using tags inside route() function. To create a variable you just need to put < and end it with > , for eg. <name> this is a variable with identifies name. How to use a variable in Flask ? We can use a variable to receive data from URL (by making a part of URL dynamic). To understand this let me give you a simple example.

Python Code

from flask import Flask
app = Flask(__name__)

@app.route('/hello/<name>')
def hello_name(name):
   return 'Hello %s!' % name

if __name__ == '__main__':
   app.run(debug = True)

In the above code, you can see in route() function, a <name> tag is used to create a variable. Which is receiving some data from the URL. In simple words, the content after /hello/ will be treated as data for the <name> variable.
So, when we open the URL as – http://localhost/hello/VikashMishra then it will return Hello VikashMishra as it is taking the part after /hello/ as a string.
In case if you want to specify the data type of the variable, then you can hard-code it into the variable tag itself. for eg. : <int:data>

DATA TYPES FOR VARIABLES

  1. string – %s is used to display data at its occurrence place. Used to store string
  2. int – %d is used to display data at its occurrence place. Used to store integers
  3. float – %f is used to display data at its occurrence place. Used to store decimal values.
  4. path – accepts slashes used as directory separator character.

Example of Python Code

from flask import Flask
app = Flask(__name__)

@app.route('/blog/<int:postID>')
def show_blog(postID):
   return 'Blog Number %d' % postID

@app.route('/rev/<float:revNo>')
def revision(revNo):
   return 'Revision Number %f' % revNo

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

Run the above code and visit URL http://localhost:5000/blog/11 in the browser.

The number is used as argument of show_blog() function. The browser will display the below output:

Blog Number 11

Now enter this URL in the browser − http://localhost:5000/rev/1.1
The revision() function will take up the floating point number as an argument, and produce the result shown below in the browser

Revision Number 1.100000

So now you can understand the data type and variable type in Flask. Before we end up this chapter, I’ll like to go little further and tell you a few things more. It’ll help you understanding the URL concept better.
The URL rules in Flask are based on Werkzeug’s routing module. This ensures that the URLs formed are unique and based on precedents laid down by Apache.
Here if you are typing /home  and  /home/, it might happen that you find it similar, but there is a big difference into it. if you enter /home then home will be treated as a value in most cases. But if you enter /home/ then it will be considered as a complete URL.

Let us try this with an example of python Code

from flask import Flask
app = Flask(__name__)

@app.route('/dashboard')
def hello_flask():
   return 'Hello Dashboard'

@app.route('/home/')
def hello_python():
   return 'Hello Home'

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

Both the rules appear to be similar, but in the second rule, trailing slash (/) is used, due to which it becomes a canonical URL. That is why, using /home or /home/ returns the same output. However, in case of the first rule, /dashboard/ URL results in 404 Not Found page.
Woohh,,,,,, completed the big part, now we can move on the interesting ones… stay tuned..

Flask – Binding URL

First thing that comes to mind when we hear binding is – I guess – BOOKBINDING / PAPER BINDING. Well, this is something similar to that but not exactly. Here, in Flask, binding URL means adding functionalities to some URL.
url_for() is a very useful function used to dynamically build URLs for a specific function. It accepts the first parameter to be the function that needs to be bind, followed by one or more keyword arguments, each corresponding to the variable part of the URL.

Python Code

from flask import Flask, redirect, url_for
app = Flask(__name__)

@app.route('/admin')
def hello_admin():
   return 'Hello Admin'

@app.route('/guest/<guest>')
def hello_guest(guest):
   return 'Hello %s as Guest' % guest

@app.route('/user/<name>')
def hello_user(name):
   if name =='admin':
      return redirect(url_for('hello_admin'))
   else:
      return redirect(url_for('hello_guest',guest = name))

if __name__ == '__main__':
   app.run(debug = True)

In the above example see that the redirect() function is being used to navigate the page to url_for() function page. 
The above script shows a function user(name) that accepts data from a variable to its argument from the URL.
The User() function checks if an argument received matches ‘admin’ or not. If it matches, the application is moved to the hello_admin() function using url_for(), otherwise, it is moved to the hello_guest() function passing the received argument as a guest parameter to it.

When you run the code, launch browser, and open URL − http://localhost:5000/user/admin you will get an output –

Hello Admin

Now use this URL to see the change – http://localhost:5000/user/Vikash you will get output as – 

Hello Vikash as Guest 
So now, when we know the few basic things of Flask, it'll become even easy and better to move forward..

FLASK ROUTING

Let me introduce you to the routing concepts of the Flask framework. Routing is a major and basic part of this framework as it defies which data has to be forwarded to the client on different URL requests.
Moving to the depth of routing, route() is called the decorator in Flask, which is used to bind URL to functions as shown below.

Python Code

@app.route(‘/hello’)
def hello_world():
   return ‘hello world’

In the above line of codes, the URL ‘/hello‘ rule is bounded to the hello_world() function, due to which if a client requests for the hello page using URL – http://localhost:5000/hello  an output of “hello world” is displayed on the browser.
The add_url_rule() function of an application object is also available to bind a URL with a function as in the above example, route() is used.
Also, use of add_url_route() function can be done to bind a URL with a function as done by route() function in above example. How?? Let’s see.

Python Code

def hello_world():
   return ‘hello world’
app.add_url_rule(‘/’, ‘hello’, hello_world)

Here also, the same thing is being performed, the difference is, you do not need to define the function just below the decorator, you can define the functions first and then add the URL rules at the end, one after another. It helps to keep the code a little cleaner.
Are you getting interested?? There’s a lot to go.. stay tuned…

“HELLO WORLD” – Python Flask

We need to test our python flask set up before we move further and learn a big thing. To try out the setup that we did in the last part of this tutorial, we need to create a small “Hello World” program and run it on the browser to check if everything is working well. So let’s begin.

Write the following code in your text editor, I prefer Sublime text.

Python Flask Code

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello World’

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

What does the above code do? Well, the above code creates a Flask class object. Then it calls the constructor and passes the current module name (__name__). Once the constructor is called, a route() function is called which defines the calling of functions for each URL. In other words, route() tells what has to be done when some URL is requested by the client.
We will go through each line of statement one by one but before that, we need to test if the Flask is working as per our requirements or not! So, to run the above project, go to terminal/command prompt and type the below code.

python hello.py

NOTE: hello.py is the name of the file in which we will write the above code.

Once the above code is run, you will get a message on the console like the one below:

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

To see the output on the browser, navigate to the URL shown in the console and see if everything seems to be good.

Now, once everything is working fine, let us go through some lines of codes in the above snippet.

The route function

app.route(rule, options)

The route function takes in two parameters to define the work flow of the requested URL.

  • The rule – this represents defines the URL binding with the function.
  • The options – this is a list of parameters to be forwarded to the underlying Rule object

In the example demonstrated above, The  ‘/’ URL is bound with hello_world() function. So, when the home page is requested by the client, the output of this function will be rendered.

The app.run function

app.run(host, port, debug, options)

The app.run function takes in four parameters, all of which is optional to provide.

  • host – Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have the server available externally.
  • port – Defaults to 5000.
  • debug – Defaults to false. If set to true, provides debug information.
  • options – To be forwarded to the underlying Werkzeug server.

Debug mode

In Flask application development, we need to start/run the application by calling run() method. While developing the application, you will need to restart the application multiple times manually as the changes will be reflected only if the script is restarted. To avoid this, while the project is in a development phase, you can pass debug = True in run() function to track the error, if any, and avoid restarting the project each time you make changes in the code.

app.debug = True
app.run()
app.run(debug = True)

Try making some changes in the first program you wrote, and try reading out the errors, if any, and see the changes in output.

Stay tuned, you will love things coming up in this tutorial series….

Flask Introduction

So, before moving further, it will be good to know a few basic things like What is a web framework ? Well, the answer is – Web framework is a collection of libraries and modules which enables a web application developer to write codes without bothering about the low-level things like protocols and thread management, etc.

What is Flask?

Flask is a web based application framework, which is written in Python and is developed by Armin Roncher, who also heads the international group of Python enthusiasts, known as Pocco. Flask is based on 2 major projects of Pocco group,WorkzengWSGI toolkit and Jinja2 template engine.

Now, we talked about a few things in the above description Let’s learn about them first..

What is WSGI ?
And the answer is WSGI stands for Web Server Gateway Interface and has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications.

What is Workzeng ?
It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases.  –  The best answer that I found on the web.


What is Jinja2 ?
jinja2 is a popular templating engine for Python. Basically a web templating system contains the HTML structure of web pages which are put together with some variable / data by the system to generate dynamic website.

Flask is generally referred as mirror framework. Flask keeps the core of the application as the simplest yet extensible. Flask supports extensions to be added on for getting new features which we will discuss in the course as we move..

Flask – HTTP

What is HTTP?

HTTP is defined as HyperText Transfer Protocol. In World Wide Web, HTTP is considered the foundation of data transfer over the network. There are different methods of data transfer defined in the HTTP (protocol), I have tried listing some below:

  • GET – Sends data in unencrypted form to the server. Most common method.
  • POST – Used to send HTML form data to the server. Data received by the POST method is not cached by the server. Also, large data can be sent using the POST method
  • PUT – Replaces all current representations of the target resource with the uploaded content.
  • DELETE – Removes all current representations of the target resource given by a URL.

As in other languages, the default method of data transfer is GET which can be changed to POST by explicitly mentioning it into the route() decorator function.

To understand this better, let us create two files. The first file will contain the HTML form which we will use to send data. While the second will contain the python flask script to catch the data coming from the first file.
HTML FILE WITH FORM CODE

<html>
   <body>
      
      <form action = "http://localhost:5000/signin" method = "post">
         <p>Enter Name:</p>
         <p><input type = "text" name = "usernaem" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>
      
   </body>
</html>

PYTHON FLASK FILE

from flask import Flask, redirect, url_for, request
app = Flask(__name__)

@app.route('/dashboard/<name>')
def success(name):
   return 'welcome %s' % name

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      user = request.form['username']
      return redirect(url_for('success',name = user))
   else:
      user = request.args.get('username')
      return redirect(url_for('success',name = user))

if __name__ == '__main__':
   app.run(debug = True)

Now, turn on the python server from terminal / command prompt and in the browser, open the HTML file.  Fill in the form and hit the submit button. What you will see is, the welcome message on the next page.
In the first case, the line of code to receive the data in POST method is

request.form['username']

 Now change the method to GET in HTML file, form tag. And try to submit the form again from the browser, now also you will see the same message on the browser. But this time if you notice, then you will be able to see that the data is being passed in the URL, and is using the GET method, so the data is being received by another statement, i.e.

request.args.get('username')

So, now you know how to pass and receive data using HTTP GET & POST methods in Flask.
As we move on, there are lot more interesting things, stay tuned.