INTRODUCTION TO PYTHON FLASK

 

INTRODUCTION TO PYTHON FLASK



Introduction

Python is the most sort after language for web application development and data science as well. It has risen to this height for its ease of use and variety of supportive libraries. There are legacy frameworks like Java’s Enterprise edition and ASP. NET’s MVC framework is still popular for enterprise-level development. But Python is the favourite for new POC and small-time development where an audience that of an enterprise is not immediately expected. And, of course, the fact that Python and most of its libraries are open sources and free is an exceptionally helpful and useful factor too. 

In Python, for web application development, the leaders are Django and Flask. Django is very much similar to the MVC framework of ASP. NET. But Flask is different. Let’s see how.

What is a Web Framework?

To understand Flask, we need to understand what is the traditional web framework.  A web application framework is a collection of libraries and modules which helps developers write the business layer without worrying about the protocol, thread management, etc. And Python’s Django follows a traditional web framework which is also called an enterprise framework. 

What is Micro-framework?

In contrast to a traditional web framework, a micro-framework is a minimalistic framework where developers are provided with a lot of freedom to build the web application layer. As compared to an enterprise framework, a developer would not need to set up many things in a micro-framework to get the web app hosted and running. This is incredibly useful in cases of small web app development where the needs are not the same as an enterprise-level framework which would save lots of development ~ maintenance time and money as a consequence. 

What is flask?

Flask is a micro web framework written in Python. It is classified as a micro framework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions. However, Flask supports extensions that can add application features as if they were implemented in Flask itself. Extensions exist for object-relational mappers, form validation, upload handling, various open authentication technologies and several common framework related tools.

What is WSGI?

Web Server Gateway Interface (WSGI) is the standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications.  

Werkzeug is one of the most advanced WSGI modules that contain various tools and utilities that facilitate web application development. Flask implements Werkzeug.

What is Jinja 2?

Jinja 2 is a template rendering engine. It renders the web pages for the server with any specified custom content given to it by the webserver. Flask renders its HTML based templates using Jinja 2. 

Why Flask?

Now, you would be able to understand, when we define Flask as a micro-framework that is built using WSGI and Jinja 2 template engine. 

Major advantages of Flask are: 

1.     Ease of setup and use.

2.     Freedom to build the structure of the web application. 

With freedom comes responsibility, similarly, Flask needs the developers to carefully structure it, since Flask doesn’t have “flask rules” to follow as compared to frameworks like Django. As the web app increases in complexity, this structuring is what is going to be the foundation. 

Your 1st Flask Application

To start with a boilerplate application, let’s use the default as mentioned in the Flask documentation.

I have used PYCHARM here; you can choose any text editor of your choice. 

Create a `app.py` file in the virtual environment and write the following code:



Save this file and run this through the command prompt, just as you would any other python file. 

`python app.py

Note: Ensure that you never save this as ‘Flask’ as it would conflict with the Flask itself. 

It will give you the following output:


Open the localhost URL mentioned in the command prompt to show an output like:

Congratulations, on running your first Flask application! If you had followed through all the steps, there wouldn’t be any errors in running the Flask application. 

Let’s understand the syntax of the program

1.     The first line of code `from flask import Flask` is basically importing Flask package in the file. 

2.     We next create an object of the flask class using `app = flask()`

3.     We send the following argument to the default constructor `__name__`, this will help Flask look for templates and static files. 

4.     Next, we use the route decorator to help define which routes should be navigated to the following function. `@app.route(/)`

5.     In this, when we use `/` it lets Flask direct all the default traffic to the following function. 

6.     We define the function and the action to be performed. 

7.     The default content type is HTML, so our string will be wrapped in HTML and displayed in the browser. 

8.     In the main function created, `app.run()` will initiate the server to run on the local development server. 

Debugging 

When developing a Flask application, it is important to consider using the debugging mode for these two reasons:

1.     It will trace errors if and display it.

2.     Each time a change is made, you would have to restart the app to be able to view the change, in order to avoid that, the app can be started in debugging mode where the changes will reflect instantaneously. 

To debug the code, you need to add to add the following to your code:



Routes

There are few basic functionalities about routes that should be discussed to construct a basic application. The `route()` as noted earlier is a Flask decorator:

`app.route(rule, options)`

·        Rule is the URL for which the particular function should be called upon

·        options are the list of parameters which can be sent to the function as input

You can also use `app.add_url_rule()` to bind a function to the URL. 

HTTP Methods

HTTP methods are at the core of communication between different parties of the world wide web, one of them being the Flask app you will be designing. These methods are standard across any frameworks, so let’s see how Flask handles them.

1.     GET

It is the most basic and unencrypted form of sending data to the website by appending the content to the URL. It can be used in cases where data of invaluable nature (which will not be an issue if disclosed) is being shared with the server. It is most commonly used in cases of fetching data or loading a new HTML page. 

 

2.     POST

The POST method is the second most used method after GET. The data is encrypted and sent to the server. It is not appended to the URL, it is sent in the body of HTML, most commonly as part of HTML form data. It is also not cached on the system. This is one of the most trusted methods to send sensitive data to the server like login credentials, etc. 

3.     HEAD

The HEAD method is very similar to the Get method. This is can be cached on the end-user’s system, is unencrypted but it is not supposed to have a response body. For example, a URL request can have a large download attached to it, but, using HEAD method, the URL can request to check the `content-length` from the header alone to get the file size without downloading the entire file. 

4.     PUT

The PUT method is similar to the POST method, except for the fact, calling a POST method multiple times will send that many requests to the server as opposed to the PUT method, wherein it will just replace the current result or response with the same response.

In a nutshell, PUT is used to create a resource most often, so that subsequent requests do not create redundant resources (and end-user receives a `201 created error`) whereas, POST should be used when updating resources, there can be multiple update requests. 

5.     DELETE

The DELETE sends a request to erase the particular resource to the server. 

Templates in Flask

Web Templating system’ refers to displaying an HTML page to the end-user. This revolves around 3 parts:

1.     A Core template engine: In this case it is Jinja2

2.     Data source: It can be any content hard-coded in HTML or passed to the HTML file

3.     Template processor: In this, python expressions will help in processing the templates. 

Static Files

Similar to the HTML files, all the necessary static files such as images, videos, CSS files, JS files, etc need to be placed under the folder name of static. This needs to be created in the root folder same as Templates

Jinja 2

Jinja2 being the web templating system has few templates which would allow us to create Python expressions in the HTML file. 

1.     {{ ….. }} : This will process the Python code written and display accordingly. Example seen earlier.

2.     { %…..% } : For statements.

3.     {# …. #} : For comments not to be included in the template output. 

Request object

The communication from end-user to server running Flask happens through the usage of Flask’s global Request object. This has to be specifically imported from Flask module. Request objects important attributes are:

1.     method:- It defines the HTTP method request object type. 

2.     Form:- It contains a dictionary object of all the Form attributes and its values. 

3.     args:- contents sent as part of query string in the URL after a (?) mark.

4.     files:- data in which was uploaded to the application.







Conclusion

The above was a basic overview of Flask for beginners. There’s a lot more to still explore, but, using this you will be able to kickstart your very own Flask application in no time.

 

Comments

Popular posts from this blog

Oracle Database Server Architecture: Overview

Oracle E-Business Suite (EBS) - Introduction

Why enterprises must not ignore Azure DevOps Server