Pyramid: Method Instance for adding Middleware

Source: Internet
Author: User

Suppose we want to add our own Middleware to record the logs of each request.
The following is a standard Middleware. The constructor accepts a wsgi app and _ call _ returns a wsgi app.

Copy codeThe Code is as follows:
Class LoggerMiddleware (object ):
'''Wsgi middleware '''

Def _ init _ (self, application ):

Self. app = application

Def _ call _ (self, environ, start_response ):

# Write logs

Try:
Return self. app (environ, start_response)
Except t Exception, e:
# Write logs
Pass
Finally:
# Write logs
Pass

In the main function of Project _ init _. py, package a layer of our Middleware on config. make_wsgi_app:

Copy codeThe Code is as follows:
From pyramid. config import Configurator
Config = Configurator ()
Config. scan ()
App = config. make_wsgi_app ()

# Put middleware
App = LoggerMiddleware (app)

Serve (app, host = '0. 0.0.0 ')

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.