import eventlet
from eventlet import wsgi
from paste.deploy import loadapp
import routes
import routes.middleware as middleware
import webob.dec
import webob.exc
class Resource(object):
def __init__(self, controller):
self.controller = controller()
@webob.dec.wsgify
def __call__(self, req):
match = req.environ['wsgiorg.routing_args'][1]
action = match['action']
if hasattr(self.controller, action):
method = getattr(self.controller, action)
return method(req)
return webob.exc.HTTPNotFound()
class CatController(object):
def index(self, req):
return 'List cats.'
def create(self, req):
return 'create cat.'
def delete(self, req):
return 'delete cat.'
def update(self, req):
return 'update cat.'
class DogController(object):
def index(self, req):
return 'List dogs.'
def create(self, req):
return 'create dog.'
def delete(self, req):
return 'delete dog.'
def update(self, req):
return 'update dog.'
class AnimalApplication(object):
def __init__(self):
self.mapper = routes.Mapper()
self.mapper.resource('cat', 'cats', controller=Resource(CatController))
self.mapper.resource('dog', 'dogs', controller=Resource(DogController))
self.router = middleware.RoutesMiddleware(self.dispatch, self.mapper)
@webob.dec.wsgify
def __call__(self, req):
return self.router
@classmethod
def factory(cls, global_conf, **local_conf):
return cls()
@staticmethod
@webob.dec.wsgify
def dispatch(req):
match = req.environ['wsgiorg.routing_args'][1]
return match['controller'] if match else webob.exc.HTTPNotFound()
class IPBlacklistMiddleware(object):
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
ip_addr = environ.get('HTTP_HOST').split(':')[0]
if ip_addr not in ('127.0.0.1','192.168.0.51'):
start_response('403 Forbidden', [('Content-Type', 'text/plain')])
return ['Forbidden']
return self.application(environ, start_response)
@classmethod
def factory(cls, global_conf, **local_conf):
def _factory(application):
return cls(application)
return _factory
if '__main__' == __name__:
application = loadapp('config:D:/asynchronous/animal.ini')
server = eventlet.spawn(wsgi.server,
eventlet.listen(('', 8080)), application)
server.wait()
配置文件
[composite:main]
use = egg:Paste#urlmap
/ = animal_pipeline
[pipeline:animal_pipeline]
pipeline = ip_blacklist animal
[filter:ip_blacklist]
paste.filter_factory = animals:IPBlacklistMiddleware.factory
[app:animal]
paste.app_factory = animals:AnimalApplication.factory
- wsgi就是一个规范,规范应用的接收参数必须是一个http的环境变量与一个返回http状态的回掉函数
return一个可迭代的对象
1.pastedeploy 首先要有一个.ini的配置文件,配置文件里面包括app的入口与中间件 app的执行过程
如果想定义中间件必须定义一个管道,也就是http请求要经过的一个顺序,比如 管道定义为 ip白名单黑名单
处理http请求应用
2.中间件与应用的本质是一样的对于wsgi来说都是应用。
3.应用使用router.mapper来建立restful的映射关系,主要通过http请求的环境变量里的req.environ['wsgiorg.routing_args'][1]的
action变量来映射restful的处理方法。
4.可以使用eventlet,协程来增加web的并发能力
网友评论