您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關 仿Openstack的WSGI接口及RESTul服務實現是怎樣的,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
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()
然后是testroutes.ini文件
[DEFAULT] name=huang [composite:main] use=egg:Paste#urlmap /=show [pipeline:show] pipeline = root [app:root] paste.app_factory = testroutes:Router.app_factory
由此可見,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')
上述就是小編為大家分享的 仿Openstack的WSGI接口及RESTul服務實現是怎樣的了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。