假設我們要添加一個我們自己的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')
新聞熱點
疑難解答