Overview of Python Flask Framework
Web apps are developed to generate content based on retrieved data that changes based on a user’s interaction with the site. The server is responsible for querying, retrieving, and updating data. This makes web applications to be 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.Analyze Big Data and make predictions out of the data requires training with Machine Learning Algorithms. Source: Machine Learning Model on Kubernetes
What is Web Framework?
A web framework is an architecture containing tools, libraries, and functionalities suitable to build and maintain massive web projects using a fast and efficient approach. They are designed to streamline programs and promote code reuse. To create the server-side of the web application, you need to use a server-side language. Python is home to numerous such frameworks, famous among which are Django and Flask. Its framework is a lightweight micro-framework based on Werkzeug, Jinja2. It is called a micro framework because it aims to keep its core functionality small yet typically extensible to cover an array of small and large applications. It depends on two external libraries: The Jinja2 template, Werkzeug WSGI toolkit. Even though we have a plethora of web apps at our disposal, Flask tends to be better suited due to -- Built-in development server, fast debugger
- Integrated support for unit testing
- RESTful request dispatching
- Jinja2 Templating
- Support for secure cookies
- Lightweight and modular design allows for a flexible framework
What are the critical elements of the Python Flask Framework?
Initialization: flask applications must create an application instance. The web server passes all the requests it receives from clients to objects for handling using a protocol for WSG from flask import Flask app = Flask (__name__) (An application instance is an object of class Flask.)The layout of the Python Flask Framework
- Module Init - (project_root/app_name/admin/__init__.py) - required to enable the app
- Module URL - (project_root/app_name/admin/url.py) - Url definitions of each module
- App root Init - (project_root/app_name/__init__.py) - Not necessary to define the entire app within __init__.py
- Module Views - (project_root/app_ame/admin/views.py) - Defines views for each module. Separate ‘.py.’ Files as the project scale to ensure they are accessible to URLs.
- Module Templates - (project_root/app_name/admin/templates/admin/main.html) - Normal template folder.
Continuous delivery concentrates on automating the software delivery process to deploy the code at production at any point. Source: CI and CD Pipeline for Python
Routes and View Functions in Flask Framework Instance
Clients send requests to the webserver, in turn, sends them to the Flask application instance. The instance needs to know what code needs to run for each URL requested and map URLs to Python functions. The association between a URL and the function that handles it is called a route. The most convenient way to define a route in a Flask application is through the (app.route). Decorator exposed by the application instance, which registers the ‘decorated function,’ decorators are python feature that modifies the behavior of a function.@app.route('/')
def index():
return 'Xenonstack'
The index is a view function, and the response can even be a string format HTML.
- Server Startup - The application instance has a ‘run’ method that launches flask’s integrated development webserver -
if __name__ == '__main__':
app.run(debug=True)
Once the script starts, it waits for requests and services in a loop.
- Local-Host - Run a python script in a virtual environment. Flask starts the server listening on 127.0.0.1 and port 5000 by default. To accept connection from any remote address, use host = ‘0.0.0.0.’
HTTP Methods
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
Templates
To maintain the site. Flask uses a powerful template engine, ‘Jinja2’, in its simplest form. A Jinja2 template is a file that contains the text of a response, returned by a view function that has a dynamic component represented by a variable.Linking
Dynamic url routing support is included using ‘url_for()’ helper function. For example, url_for('sagar', name='project_file', _external=True) would return http://localhost:5000/sagar/project_file.Security
CSRF(Cross-Site-Request-Forgery) occurs when a malicious website sends requests to a different website on which the victim logs in. Flask-WTF protects against all such attacks. Apart from that, Flask also implements some common security mechanisms like session-based management, role mgmt, password hashing, basic HTTP and token-based authentication, optional log-in tracking.Database Connectivity
Flask has no restrictions for the use of databases; there’s no native support for databases. However, they can be broadly divided into two categories.- That following relational model for, e.g., SQL, sqlite3 mainly for structured data.
- That not following the relational model for, e.g., NoSQL primarily for unstructured data.
Build and Pipelines
Travis can be used for continuous integration to upload application images to docker hubs. After the publishing image to the Docker hub, it triggers a webhook to pull onto target servers.Nginx Reverse Proxy
serve static files directly. Forward other requests to the application’s web server listening on the localhost. Testing - End-to-End tests are carried out using Flask test client and Selenium.-
- Unittest - built-in unit test framework. xUnit based.
- Py.test - module to build unit tests.
Test-Driven Development is an approach in which we build a test first, then fail the test and finally refactor our code to pass the test. Source: Test-Driven Development and Unit Testing in Python
Deploying Python Flask Framework on Heroku Cloud
-
Install Heroku client and Foreman (to test simulated Heroku environment on pc).
-
Create an application using Heroku CLI and Git.
-
Add ‘procfile’ to the application using a gunicorn webserver run ‘ Heroku create <unique-app-name>-api-heroku’ in the application folder.
-
Push application to master branch https://git.heroku.com/kbucket-api-heroku.git , clone the repository, and push to heroku-master.
-
Note the app URL like (https://<unique-app-name>-api-heroku.herokuapp.com/ ). The application lives here. Heroku will assign the data that will garner to a PostgreSQL database.
-
One can also test the live API of the application, and if successfully deployed, it will return a 201 status code.
What is Flask Over Django?
Django is a full-stack web framework, while Flask is a micro lightweight f/w. But in recent times, Flask seems to have outdone Django, with more and more developers focusing on microservices and micro-frontends to reduce the loading time of a webpage. All of the user capability is available on a compact yet powerful f/w in Flask as compare to a host of additional resources in Django. Ease of development and faster deployment times in Flask.
- Discover more about Continuous Integration and Delivery Pipeline
- Click to explore about Apache Spark Architecture