本文地址: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。