在pylons的文档中,有专门讲过如何添加自己的Middleware, 通过这些Middleware, 我们可以改变输入和输出。这也是WSGI(Web Server Gateway Interface)的优势和精髓所在。

 

那么在pyramid中,我们如何添加Middleware呢?

假设我们要添加一个我们自己的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')

相关文章:

  • 2021-05-10
  • 2021-09-18
  • 2021-10-10
  • 2022-02-20
  • 2022-12-23
  • 2021-04-06
  • 2021-08-04
猜你喜欢
  • 2021-09-12
  • 2022-12-23
  • 2021-08-13
  • 2021-10-08
  • 2021-08-10
  • 2021-04-17
  • 2022-01-22
相关资源
相似解决方案