Building a Web application using Python Flask

tenthplanet blog pentaho Building a Web application using Python Flask

Introduction

Python Flask is a micro-framework that provides functionalities to build a web application. Micro-frameworks are normally frameworks with little to no dependencies on external libraries. This has both pros and cons.

Pros

Flask framework is light, there are little dependencies and there is no need to watch for security bugs.

Cons

Sometimes you will have to do more work by yourself or increase the list of dependencies by adding plug-ins.

Why Flask

There are several python frameworks like Django, bottle, tornado, etc., but what separates Flask from all the others are:

  • It is simple to learn and extensively scalable.
  • Absence of application architectures and data abstraction layers.
  • Flask is very flexible and easy to use.

Flask takes care of the processing by receiving requests from the program and also figures out what response to send to the user. This is done using HTTP.

Flask can also be used for connecting databases and web applications.

Requirement of templates while working with Flask

Creating mock objects is a useful technique that allows you to concentrate on one part of the application without having to worry about other parts of the system that don’t exist yet. These separate applications can be imported into our main python code by using the render_template() method from the flask framework. This method will look for HTML files in the templates folder and it will render the files which you ask for.

Creating basic application using Flask in Python

import Flask
app = flask.Flask(__name__)
app.config[“DEBUG”] = True

@app.route(‘/’, methods=[‘GET’])
def home():
return “<h1>Flask Application</h1><p>my first webapp using Flask</p>”

app.run()

After we run the program we get the following output:

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

When we connect to the Flask server at http://127.0.0.1:5000/, Flask checks if there is a match between the path provided and a defined function. Flask runs the code in the function and displays the returned result in the browser.

Conclusion

Webpage creation is easier with Python Flask, since it involves the use of HTML/CSS, provides simplicity, flexibility & fine-grained control and is extensively documented.