Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask Middleware and Extensions

Flask Middleware and Extensions

In Flask, middleware and extensions are two key mechanisms for enhancing and expanding application functionality.

Through middleware and extensions, you can greatly enhance the functionality and flexibility of a Flask application, enabling it to meet various complex requirements.

The following sections introduce the concepts of both and how to use them in detail.

Flask Middleware:

Flask Extensions:

1. Flask Middleware

Flask's middleware are hooks that process requests and responses, typically used to perform operations before a request reaches the view function or before a response is sent to the client. Middleware can be used for logging, request modification, response modification, and so on.

1.1 Request Hooks

Request hooks allow you to insert code at different stages of request processing. Flask provides several hooks to handle different stages of the request lifecycle:

Code in app.py:

Example

from

flask

import

Flask

,

request

app

=

Flask

(

name

)

@

app.

before_request

def

before_request

(

)

:

   

print

(

'Before request'

)

@

app.

after_request

def

after_request

(

response

)

:

   

print

(

'After request'

)

   

return

response

@

app.

teardown_request

def

teardown_request

(

exception

)

:

   

print

(

'Teardown request'

)

@

app.

route

(

'/'

)

def

index

(

)

:

   

return

'Hello, World!'

if

name

==

'main'

:

    app.

run

(

debug

=

True

)

1.2 Custom Middleware

Flask also allows you to create custom middleware classes, which can operate at various stages of request and response processing.

Code in middleware.py:

Example

class

CustomMiddleware:

   

def

init

(

self

,

app

)

:

       

self

.

app

=

app

   

def

call

(

self

,

environ

,

start_response

)

:

       

def

custom_start_response

(

status

,

headers

)

:

            headers.

append

(

(

'X-Custom-Header'

,

'Value'

)

)

           

return

start_response

(

status

,

headers

)

       

return

self

.

app

(

environ

,

custom_start_response

)

Code in app.py:

Example

from

flask

import

Flask

from

middleware

import

CustomMiddleware

app

=

Flask

(

name

)

app.

wsgi_app

=

CustomMiddleware

(

app.

wsgi_app

)

@

app.

route

(

'/'

)

def

index

(

)

:

   

return

'Hello, World!'

if

name

==

'main'

:

    app.

run

(

debug

=

True

)

CustomMiddleware: A custom middleware class that adds a custom response header.

2. Flask Extensions

Flask extensions are plugins used to add functionality to Flask applications. Flask extensions can integrate third-party libraries, providing features such as database integration, form handling, and user authentication.

2.1 Common Flask Extensions

2.2 Installing and Using Flask Extensions

Taking Flask-SQLAlchemy as an example, install it with:



pip install flask-sqlalchemy

Configuration and usage, code in app.py:

Example

from

flask

import

Flask

from

flask_sqlalchemy

import

SQLAlchemy

app

=

Flask

(

name

)

app.

config

[

'SQLALCHEMY_DATABASE_URI'

]

=

'sqlite:///example.db'

db

=

SQLAlchemy

(

app

)

class

User

(

db.

Model

)

:

   

id

=

db.

Column

(

db.

Integer

,

primary_key

=

True

)

    username

=

db.

Column

(

db.

String

(

80

)

,

unique

=

True

,

nullable

=

False

)

@

app.

route

(

'/'

)

def

index

(

)

:

   

return

'Hello, World!'

if

name

==

'main'

:

    app.

run

(

debug

=

True

)

The SQLAlchemy extension integrates SQLAlchemy, allowing you to easily define models and interact with the database.

2.3 Creating Custom Extensions

If existing extensions don't meet your needs, you can create your own. Creating a custom extension usually involves defining a class that provides initialization configuration and related functionality.

Code in myextension.py;

Example

class

MyExtension:

   

def

init

(

self

,

app

=

None

)

:

       

if

app

is

not

None

:

           

self

.

init_app

(

app

)

   

def

init_app

(

self

,

app

)

:

        app.

config

.

setdefault

(

'MY_EXTENSION_CONFIG'

,

'default_value'

)

        app.

after_request

(

self

.

after_request

)

   

def

after_request

(

self

,

response

)

:

        response.

headers

[

'X-My-Extension'

]

=

'MyValue'

       

return

response

Code in app.py:

Example

from

flask

import

Flask

from

myextension

import

MyExtension

app

=

Flask

(

name

)

my_ext

=

MyExtension

(

app

)

@

app.

route

(

'/'

)

def

index

(

)

:

   

return

'Hello, World!'

if

name

==

'main'

:

    app.

run

(

debug

=

True

)

MyExtension: A custom extension that adds a custom response header.