问题导读:
1.Openstack的WSGI接口通过什么实现了Controller类,和Router类?
2.这里测试程序主要测试什么功能?
3.测试的目的是什么?
Openstack的WSGI接口通过webob,pastedeploy,routes实现了Controller类,和Router类,这里仿照Openstack的WSG接口实现简单的测试程序
首先是testroutes.py文件
- import logging
- import os
-
- import webob.dec
- import webob.exc
- from paste.deploy import loadapp
- from wsgiref.simple_server import make_server
-
- import routes.middleware
- # Environment variable used to pass the request context
- CONTEXT_ENV = 'openstack.context'
-
-
- # Environment variable used to pass the request params
- PARAMS_ENV = 'openstack.params'
-
- LOG = logging.getLogger(__name__)
-
- class Controller(object):
- @webob.dec.wsgify
- def __call__(self, req):
- arg_dict = req.environ['wsgiorg.routing_args'][1]
- action = arg_dict.pop('action')
- del arg_dict['controller']
- context = req.environ.get(CONTEXT_ENV, {})
- context['query_string'] = dict(req.params.iteritems())
- context['headers'] = dict(req.headers.iteritems())
- context['path'] = req.environ['PATH_INFO']
- params = req.environ.get(PARAMS_ENV, {})
-
- for name in ['REMOTE_USER', 'AUTH_TYPE']:
- try:
- context[name] = req.environ[name]
- except KeyError:
- try:
- del context[name]
- except KeyError:
- pass
-
- params.update(arg_dict)
-
- # TODO(termie): do some basic normalization on methods
- method = getattr(self, action)
-
-
- result = method(context, **params)
-
- return webob.Response('OK')
-
- def getMessage(self,context, user_id):
- return {'Message': 'TestMessage'}
- pass
-
- class Router(object):
- def __init__(self):
- self._mapper = routes.Mapper()
- self._mapper.connect('/test/{user_id}',
- controller=Controller(),
- action='getMessage',
- conditions={'method': ['GET']})
-
- self._router = routes.middleware.RoutesMiddleware(self._dispatch, self._mapper)
-
- @webob.dec.wsgify
- def __call__(self, req):
- return self._router
-
- @staticmethod
- @webob.dec.wsgify
- def _dispatch(req):
- match = req.environ['wsgiorg.routing_args'][1]
-
- if not match:
- return webob.exc.HTTPNotFound()
-
- app = match['controller']
- return app
-
- @classmethod
- def app_factory(cls, global_config, **local_config):
- return cls()
-
-
- if __name__ == '__main__':
- configfile='testroutes.ini'
- appname="main"
- wsgi_app = loadapp("config:%s" % os.path.abspath(configfile), appname)
- httpd = make_server('localhost', 8282, wsgi_app)
- httpd.serve_forever()
复制代码
由此可见,ini文件按照pastedeploy的模式配置了根目录/,指向pipeline show,pipeline又指向app root。app下指向的是Router的app_factory函数,返回的是Router().根据调用过程,初始化__init__->__call__返回self._routers.根据__init__下写的映射规则,能识别类似/test/123这样的路径,其处理函数调用"Controller"的"action"函数,也就是getMessage。
测试运行,在浏览器下输入127.0.0,1:8282/test/123
返回OK,如
- return webob.Response('OK')
复制代码
测试完毕。
bluefire1991
2013.11.2
19:59:12
|