Webob WSGI 装饰器

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


wsgify装饰器将一个普通函数转变成WSGI应用程序。

class webob.dec.wsgify(func=None, RequestClass=None, args=(), kwargs=None, middleware_wraps=None)


小示例

from wsgiref.simple_server import make_server
from webob import Request, Response
from webob.dec import *

@wsgify
def test(req):
    res = Response()
    res.status = 200
    res.body   = "spch"
    return res

class MyApp:
    def __call__(self, environ, start_response):
        
        req = Request(environ)
        
        return test(environ, start_response)
        
application = MyApp()

httpd = make_server('localhost', 8081, application)  
httpd.serve_forever() 
其中,参数req为一个Request实例,可以通过req读取相应环境变量。

而且,我们可以定制装饰器

from wsgiref.simple_server import make_server
from webob import Request, Response
from webob.dec import *
from webob.exc import *

class MyRequest(Request):
    @property
    def is_local(self):
        return self.remote_addr == '127.0.0.1'
    
@wsgify(RequestClass=MyRequest)
def myfunc(req):
    if req.is_local:
        return Response('hi!')
    else:
        raise HTTPForbidden

class MyApp:
    def __call__(self, environ, start_response):
        
        req = Request(environ)
        
        return myfunc(environ, start_response)
        
application = MyApp()

httpd = make_server('localhost', 8081, application)  
httpd.serve_forever() 

如何是本机访问,则输出’hi‘,否则不允许


你可能感兴趣的:(Webob WSGI 装饰器)