网络编程
位置:首页>> 网络编程>> 网络编程>> Pyramid添加Middleware的方法实例

Pyramid添加Middleware的方法实例

  发布时间:2022-11-25 18:50:34 

标签:Pyramid,Middleware,python

假设我们要添加一个我们自己的Middleware,用来记录每次请求的日志
下面就是一个符合规范的Middleware, 构造函数中接受一个WSGI APP, __call__返回一个WSGI APP.


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 Exception, e:
            # write logs
            pass
        finally:
            # write logs
            pass

在项目的__init__.py的main函数中, 在config.make_wsgi_app上包上一层我们的Middleware:


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')

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com