这期内容当中小编将会给大家带来有关 仿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服务实现是怎样的了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/tantexian/blog/625829