zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Pyramid添加Middleware的方法实例

实例方法 添加 Middleware Pyramid
2023-06-13 09:15:13 时间

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

复制代码代码如下:


classLoggerMiddleware(object):
   """WSGImiddleware"""

   def__init__(self,application):

       self.app=application

   def__call__(self,environ,start_response):

       #writelogs

       try:
           returnself.app(environ,start_response)
       exceptException,e:
           #writelogs
           pass
       finally:
           #writelogs
           pass

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

复制代码代码如下:


frompyramid.configimportConfigurator
   config=Configurator()
   config.scan()
   app=config.make_wsgi_app()

   #Putmiddleware
   app=LoggerMiddleware(app)

   serve(app,host="0.0.0.0")