Overview of Flask Framework
Web apps are developed to generate content based on retrieved data that changes based on a user’s interaction with the site, where 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 Python Flask Framework and It’s 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 is required.
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.Python Flask 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. Flask Framework 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.
Critical elements of 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__) (The application instance is an object of class Flask.)
Layout of the Python Flask Framework
- App root Init – (project_root/app_name/__init__.py) – Not necessary to define the entire app within __init__.py
- 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
- 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.
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, keeps a mapping of URLs to Python functions.
The association between a URL and the function that handles it is called a route, 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 web server –
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.’
Request – To process incoming data in Flask, you need to use the request object, which includes 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 is logged 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.
Flask-SQLAlchemy is a Flask extension that simplifies the use of SQLAlchemy inside Flask applications. SQLAlchemy is a robust relational database framework that supports several database back ends. It offers a high-level ORM and low-level access to the database’s native SQL functionality.
Build and Pipelines –Travis can be used for continuous integration to upload application images to docker hubs. After the image is published to the Docker hub, it triggers a web hook allowing it to be pulled on to 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.
- 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 web server 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 be garnered a PostgreSQL database.
- One can also test the live API of the application, and if it is successfully deployed, it will return a 201 status code.
We can also test each part of a flask application individually.
Deploying Python Flask Framework on to Heroku Cloud
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 compared to a host of additional resources in Django. Ease of development and faster deployment times in Flask.
A Holistic Strategy
To know more about web app development frameworks we recommend taking the following steps –
How useful was this post?