Flask - bernardopnunes/SoftwareEngineeringSDUW GitHub Wiki

Groups:

  1. Wiki Master

Catalog

  • Overview
  • The design decision in Flask
  • Package referenced by Flask
  • Sources

Overview

What is Flask

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. 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. Extensions are updated far more frequently than the core Flask program.

Development history

Flask was created by Armin Ronacher of Pocoo, an international group of Python enthusiasts formed in 2004. According to Ronacher, the idea was originally an April Fool's joke that was popular enough to make into a serious application. When Ronacher and Georg Brandl created a bulletin board system written in Python, the Pocoo projects Werkzeug and Jinja were developed. Flask has become popular among Python enthusiasts. As of January 2020, it has more stars on GitHub than any other Python web-development framework, and was voted the most popular web framework in the Python Developers Survey 2018.[1]

Features

  1. Flask framework is characterized by its simple core composition but is highly extensible and compatible, allowing programmers to quickly implement a Web site or Web service in the Python language
  2. Flask consists of two core libraries, Werkzeug and Jinja2, which are responsible for business processing and security functions respectively. These basic functions provide a rich basic components for the web project development process.
  3. Flask does not support database access, authentication of Web forms, and user authentication. These functions are implemented as an extension component and then integrated with the Flask framework. Compared to other large or lightweight frameworks, Flask is highly extensible, which is irreplaceable by other Web frameworks.

The design decision in Flask

The only one instance at the time

A Python web application based on WSGI has to have one central callable object that implements the actual application. In Flask this is an instance of the Flask class. Each Flask application has to create an instance of this class itself and pass it the name of the module. Why? The most important reason is that implicit application objects require that there may only be one instance at the time.

The Routing System

Flask uses the Werkzeug routing system which was designed to automatically order routes by complexity. This means that you can declare routes in arbitrary order and they will still work as expected. This is a requirement if you want to properly implement decorator based routing since decorators could be fired in undefined order when the application is split into multiple modules.

Another design decision with the Werkzeug routing system is that routes in Werkzeug try to ensure that URLs are unique. Werkzeug will go quite far with that in that it will automatically redirect to a canonical URL if a route is ambiguous.

There is an example about many decorator based routings and their functions

from flask import Flask
app = Flask(__name__)

@app.route("/")
def log_in():
    return "successful!"

@app.route("/register1")
def register():
    return "1"

@app.route("/r")
def r():
    return "2"

@app.route("/p")
def p():
    return "3"

@app.route("/k")
def e():
    return "4"
if __name__ == '__main__':
    app.run()

The only one original template engine

Flask decides on one template engine: Jinja2. Users can obviously use a different template engine but Flask will still configure Jinja2. Template engines are like programming languages and each of those engines has a certain understanding about how things work. On the surface they all work the same: you tell the engine to evaluate a template with a set of variables and take the return value as string. Flask use Jinja2's extensive autoescaping support. Also it provides ways to access macros from Jinja2 templates.

Micro with dependencies

Flask depends on two libraries (namely Werkzeug and Jinja2).Flask is a framework that takes advantage of the work already done by Werkzeug to properly interface WSGI (which can be a complex task at times).

What can flask do and cannot do

Flask will never have a database layer. It will not have a form library or anything else in that direction. Flask itself just bridges to Werkzeug to implement a proper WSGI application and to Jinja2 to handle templating. It also binds to a few common standard library packages such as logging. Everything else is up for extensions.

People have different preferences and requirements and Flask could not meet those if it would force any of this into the core. The majority of web applications will need a template engine in some sort.

Flask just build a good foundation for applications and everything else is up to users and extensions.

Package referenced by Flask

As a lightweight Python web framework, flask have a simple core. Flask only relies on two core function libraries, Werkzeug WSGI toolbox and jinja2 template engine, and they are respectively responsible for business processing and security functions. These basic functions provide lots of basic components for the web project development process.

Werkzeug

Werkzeug is a comprehensive WSGI web application library. It began as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility libraries.[2]

So what is WSGI?

The full name of WSGI is Python web server gateway interface, which is a simple and universal interface between web server and web application (or web framework). We know that communication between the client and the server follows the HTTP protocol. But many of the web programs we write in Python don't directly handle HTTP requests, because it's too complex. So WSGI was born, and there is an additional conversion process between HTTP request and web program - from HTTP message to WSGI data format. At this time, our web program can be built on top of WSGI to directly handle the requests that WSGI parses to us, and we can focus on the writing of web program itself.[3]

Call flow between web server and WSGI server and web browser

Werkzeug is Unicode aware and doesn’t enforce any dependencies. It is up to the developer to choose a template engine, database adapter, and even how to handle requests. Werkzeug is not a framework, it’s a library with utilities to create your own framework or application and as such is very flexible.[1]

Werkzeug provides functions related to Python web WSGI development:[4]

  • Routing: how to find the corresponding view function according to the request URL
  • Request and response encapsulation: provides a better way to handle request and generate response objects
  • WSGI server: test environment running WSGI application

Jinja2

Jinja2 is one of the most used template engines for Python. It is inspired by Django's templating system but extends it with an expressive language that gives template authors a more powerful set of tools. It is fast, widely used, and provides an optional sandbox template execution environment to ensure security.

jinja-logo

It includes:[5]

  • Template inheritance and inclusion.
  • Define and import macros within templates.
  • HTML templates can use autoescaping to prevent XSS from untrusted user input.
  • A sandboxed environment can safely render untrusted templates.
  • AsyncIO support for generating templates and calling async functions.
  • I18N support with Babel.
  • Templates are compiled to optimized Python code just-in-time and cached, or can be compiled ahead-of-time.
  • Exceptions point to the correct line in templates to make debugging easier.
  • Extensible filters, tests, functions, and even syntax.

Characteristics of Jinja2:[6]

  • Execution in sandbox
  • Powerful HTML auto escape system protects the system from XSS
  • Template inheritance
  • Compile the best Python code in time
  • Optional time to precompile template
  • Easy to debug
  • Configurable syntax

Comparison between Django default template engine and jinja2 template engine:

Django's default template engine has many limitations, the most obvious is the four operations. Only addition and subtraction can be performed. Multiplication and division are not supported. When you need to judge equality, you cannot use if directly, but use ifequal. In addition, Django's default template engine is slow, and jinja2 claims to be 10-20 times faster than Django's default template engine.

Jinja2 is a typical text-based template language, very similar to Smarty or Django. It adheres to Python principles to ensure that it is friendly to designers and developers, and adds helpful functions to the template environment.

Sources

  1. wikipedia
  2. werkzeug.palletsprojects.com
  3. What is WSGI
  4. Werkzeug and WSGI
  5. Introduction of jinja2
  6. Characteristics of Jinja2