Pyramid添加Middleware的方法实例

yipeiwu_com6年前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')

相关文章

Python + Requests + Unittest接口自动化测试实例分析

Python + Requests + Unittest接口自动化测试实例分析

本文实例讲述了Python + Requests + Unittest接口自动化测试。分享给大家供大家参考,具体如下: 1. 介绍下python的requests模块 Python Re...

Python中list查询及所需时间计算操作示例

本文实例讲述了Python中list查询及所需时间计算操作。分享给大家供大家参考,具体如下: # -*-coding=utf-8 -*- #! python2 #filename:...

python 多进程共享全局变量之Manager()详解

Manager支持的类型有 list,dict,Namespace,Lock,RLock,Semaphore,BoundedSemaphore,Condition,Event,Queue...

Python Tkinter模块 GUI 可视化实例

我就废话不多说了,直接上代码: coding:utf-8 #自带的Tkinter模块 from Tkinter import * from ScrolledText impo...

详解使用Python下载文件的几种方法

在使用Python进行数据抓取的时候,有时候需要保持文件或图片等,在Python中可以有多种方式实现。今天就一起来学习下。 urllib.request 主要使用的是urlretrie...