Python Flask

Flask is a web framework. Usually the flask allows to create a web application like blog, website and so on. Flask is a part of the micro framework.

Template

If we create a web application with few pages, it will be easy to maintain. But incase of large website, it is not so easy to handle. So we can use template engine which is used for creating the application and also easy to update and maintain it.

“Hello World” application

First of all, we can create a structure of the project.

$mkdir -p hello/{template,static}

Thus the two folder static and templates are created. Template folders contains the templates and the static folder will contains the javascript, css, html which is required for the development of the web application. Change the directory and put the following code inside the file.

import flask

APP = flask.Flask(__name__)

@APP.route(‘/’)

def index():

return flask.render_template(‘index.html’)

if __name__ == ‘__main__’:

APP.debug=True

APP.run()

Now we can create the template file (temp.html) and place it in the template module.

<!DOCTYPE html>

<html>

<head>

<title> Website </title>

</head>

<body>

<h1> Hello World </h2>

</body>

</html>

When we run this program, the output will shown in the default browser.

Using arguements in flask

Create a program which will fetch the name from the current user. After fetching, the name is returned to the template file where the name of the current user is displayed.

@APP.route(‘/hello/<name>/’)

def hello(name):

return flask.render_template(‘hello.html’, name=name)

Then we want to add the html file according to this argument.

<!DOCTYPE html>

<html>

<head>

<title> Website </title>

</head>

<body>

Hello {{name}}

</body>

</html>

The output will be “Hello Chandru”.

Links

To create link in the template, flask uses url_for(). This will add the link of the next page or any other page.

<a href=”{{ url_for(‘temp’) }}”><button>Home</button></a>

Leave a comment