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
andLinkedIn
.
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()
As we can see from the above code snippet,
- First we have imported the Flask
- Next we have created the instance of the class as app
- We then use the route() decorator to tell the Flask what url should trigger our function
- The function returns the message that we wanted to display in the user's browser.
- 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.
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()
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!"
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)
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)
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)
You can see the output below.
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
- Web framework
- Flask framework
- HTTP methods
- minimal application of Flask
- Flask using classes
Top comments (2)
Thank you for this article :)
How can i use action function inside class? And especialy abstract class?
Can you please refer to my second blog so that you might get an idea.
dev.to/nandamtejas/implementing-fl...