DEV Community

nandamtejas
nandamtejas

Posted on • Edited on

Implementing Flask application using Object Oriented Programming (OOP's) [Part-1]

Content

  • Introduction to Flask Framework
  • Why Flask framework?
  • HTTP methods used in Flask
  • A Minimal application of Flask
  • A new approach using OOP's concept with Flask

Introduction to Flask Framework

  • Flask is a micro web framework written in Python.
  • It is classified as a microframework 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.
  • 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.

  • Applications that use the Flask framework include Pinterest and LinkedIn.

Why Flask framework?

Web apps are developed to generate the content based on retrieved data that changed on the basis of the user's interaction with the browser. The server is responsible for querying, creating, updating and also deleting data. This makes the web applications slower and slower and more complicated to deploy than static websites for simple applications. There are two primary coding environments for the whole web app ecosystem. This article will give an overview of the Python Flask Framework and Its best practices.

Client-Side Scripting

The code executed on the user’s browser visible to anyone who has access to the system, generating the first results.

Server-Side Scripting

This type of code is run on the backend on a web server. To enable developers to design, build, maintain, host web apps over the internet, a web framework necessary.

What is web framework?

A web framework is the architecture containing tools, libraries and functionalities suitable to build and maintain massive web projects using fast and efficient approach.

To create the server-side web application, we need to use the server-side programming language.

python is one of the server-side language which is the home to numerous such frameworks i.e; Django and Flask.

We choose to work with Flask framework because it is suited due to

  • Built-in development server, fast debugger.
  • Integrated support for unit testing.
  • RESTful request dispatching.
  • Support for secure cookies.
  • Lightweight and modular design allows for a flexible framework.

HTTP methods used in Flask

Request

To process incoming data in Flask, you need to use the request object, including mime-type, IP address, and data. HEAD: Un-encrypted data sent to server w/o response.

GET

Sends data to the server requesting a response body.

POST

Read form inputs and register a user, send HTML data to the server are methods handled by the route. Flask attaches methods to each route so that different view functions can handle different request methods to the same URL.

Response

Flask invokes a view function. It has to return a response value to the client. HTTP requires it to be more than a string response, a status code.

  • Informational – 1xx
  • Successful – 2xx
  • Redirection – 3xx
  • Client Error – 4xx
  • Server Error – 5xx

A Minimal application of Flask

As we know that the Flask framework is one of the python's framework which concentrates on the field of WEB development either in Backend or Full stack WEB development.



from flask import Flask

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return "Hello World!"

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


Enter fullscreen mode Exit fullscreen mode

As we can see from the above code snippet,

  1. First we have imported the Flask
  2. Next we have created the instance of the class as app
  3. We then use the route() decorator to tell the Flask what url should trigger our function
  4. The function returns the message that we wanted to display in the user's browser.
  5. We then save the above code as hello.py and run the application using the command python hello.py. This launches a very simple builtin server, which is good enough for testing.

Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting.

flask_minimal_output

From the above code snippet, we have used the route method to tell the Flask what url should trigger the function. Well there is another method of triggering the url's using add_url_rule() method.
Flask code snippet using add_url_rule() method



from flask import Flask

app = Flask(__name__)

def hello_world():
    return "<p>Hello, World!</p>"

# The hello_world function is triggered at endpoint '/'
app.add_url_rule('/', view_func=hello_world)

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


Enter fullscreen mode Exit fullscreen mode

The above code snippet is slightly different from the 1st one, Here we didn't use the decorator instead we have used the add_url_rule method which works the same.
Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting.

A new approach using OOP's concept with Flask

Flask application using the classes
Sounds Interesting!!

Flask using Classes and Objects?

Let's see how can we approach this!

Consider the small function which returns the Hello world as an action



def action():
    """ This function returns the Hello world """
    return "Hello world!"


Enter fullscreen mode Exit fullscreen mode

The above function returns Hello World, That need to be called by url

Let us do one thing, We just create the Flask app wrapper class which wraps the functionality of the Flask app



class FlaskAppWrapper(object):

    def __init__(self, app, **configs):
        self.app = app
        self.configs(**configs)

    def configs(self, **configs):
        for config, value in configs:
            self.app.config[config.upper()] = value

    def add_endpoint(self, endpoint=None, endpoint_name=None, handler=None, methods=['GET'], *args, **kwargs):
        self.app.add_url_rule(endpoint, endpoint_name, handler, methods=methods, *args, **kwargs)

    def run(self, **kwargs):
        self.app.run(**kwargs)


Enter fullscreen mode Exit fullscreen mode

In the above class ​FlaskAppWrapper​, mainly there are 3 methods, i.e; ​configs​, ​add_endpoint​ and ​run​

​​- configs​ adds all the configurations of the flask app
​​- add_endpoint​ adds the endpoint url and the handler function to tell the Flask app to trigger the handler function
​​- run​ which runs the Flask app

Now we have to initialize the FlaskAppWrapper as an app and add the action function to the flask app.



from flask import Flask

flask_app = Flask(__name__)

app = FlaskAppWrapper(flask_app)

def action():
    """ Function which is triggered in flask app """
    return "Hello World"

# Add endpoint for the action function
app.add_endpoint('/action', 'action', action, methods=['GET'])
if __name__ == "__main__":
    app.run(debug=True)


Enter fullscreen mode Exit fullscreen mode

Now we save the above code as ​class_hello.py​ and run the above code by using the command ​python class_hello.py​ and check the output.

After heading over to the url http://127.0.0.1:5000/action , we get to see ​Hello world​ in the display of the browser. That means the flask app using the classes method is working. But still we have to make changes in our code.

So the whole code looks like



from flask import Flask

class FlaskAppWrapper(object):

    def __init__(self, app, **configs):
        self.app = app
        self.configs(**configs)

    def configs(self, **configs):
        for config, value in configs:
            self.app.config[config.upper()] = value

    def add_endpoint(self, endpoint=None, endpoint_name=None, handler=None, methods=['GET'], *args, **kwargs):
        self.app.add_url_rule(endpoint, endpoint_name, handler, methods=methods, *args, **kwargs)

    def run(self, **kwargs):
        self.app.run(**kwargs)

flask_app = Flask(__name__)

app = FlaskAppWrapper(flask_app)

def action():
    """ Function which is triggered in flask app """
    return "Hello World"

# Add endpoint for the action function
app.add_endpoint('/action', 'action', action, methods=['GET'])
if __name__ == "__main__":
    app.run(debug=True)


Enter fullscreen mode Exit fullscreen mode

You can see the output below.

flask_action_output

So Why using classes and objects?

This is the good question you may get, we can use only functions and it works well by using functions. But why using classes?

The answer is I don't know!

There are some problems which can be approached by one or many methods.

In our case using classes to define the endpoints for the web application in Flask, reduces the number of functions to be used for the same endpoint. These functions can be wrapped up in a single object by creating classes and giving a common endpoint for that class makes all the methods in that class to be executed in that method.

This is the 1st part of my current blog.
The second part will be released soon.

Hope you all like this!!

Summary

We have discussed about

  1. Web framework
  2. Flask framework
  3. HTTP methods
  4. minimal application of Flask
  5. Flask using classes

Link to my second blog.

Top comments (2)

Collapse
 
konradlaskowski profile image
Konrad Laskowski

Thank you for this article :)
How can i use action function inside class? And especialy abstract class?

Collapse
 
nandamtejas profile image
nandamtejas

Can you please refer to my second blog so that you might get an idea.

dev.to/nandamtejas/implementing-fl...