WSGI-- Middleware

本文地址:http://blog.csdn.net/spch2008/article/details/9000806


假定存在一个superSession模块,用于追踪用户访问行为。

import superSession
session = superSession.session()
print "Content-type: text/plain\n\n"

if session.has_key('visited'):
    print "You have already visited!"
else:
    session['visited'] = 1
    print "This is your first visit."

上述代码创建了一个Session对象,追踪用户访问行为。将上述思想用于WSGI程序中。


def application(environ, start_response):
    import superSession
    session = superSession.session()
    if session.has_key('visited'):
        text = "You have already visited!"
    else:
        session['visited'] = 1
        text = "This is your first visit."
    start_response('200 OK', [('Content-type','text/plain')])
    return [text]

可以将上述代码进行重构。


def exampleApplication(environ, start_response):
    if environ['superSession'].has_key('visited'):
        text = "You have already visited!"
    else:
        environ['superSession']['visited'] = 1
        text = "This is your first visit."
    start_response('200 OK', [('Content-type','text/plain')])
    return [text]
    
def session(application):
    def app(environ, start_response):
        if "superSession" not in environ:
            import superSession
            environ["superSession"] = superSession.session()
        return application(environ, start_response)
    return app
    
application = session(exampleApplication)

将session代码抽离放于session函数中,该函数专门用于判断用户访问行为。session函数将判断结果至于环境变量environ字典中。
exampleApplication通过environ字典获得用户访问行为。

我们称session函数为middleware,它处于server与application之间,对server传来的请求做相应的处理;它对于Server和application是透明的。
middleware的好处在于,通过middleware(本例中session函数)可以很简单的给WSGI程序添加新功能。


我们也可见将middleware包装成类,这样,我们可以通过继承,复用现有的中间件。类中要重载__call__。

class Session:
    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):
        if "superSession" not in environ:
            import superSession
            environ["superSession"] = superSession.session() # Options would obviously need specifying
        return self.application(environ,start_response)
        
application = Session(exampleApplication)


附录: 代码语法解释

def session(application):
    def app(environ, start_response):
        if "superSession" not in environ:
            import superSession
            environ["superSession"] = superSession.session()
        return application(environ, start_response)
    return app
    
application = session(exampleApplication)

将exampleApplication传入session函数,session函数中定义了一个新的函数app,session将app返回赋给application。

实际上相当于application = app。app函数中进行相应处理(superSession),将处理好的environ在传递给exampleApplication。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值