溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

仿Openstack的WSGI接口及RESTul服務(wù)實(shí)現(xiàn)是怎樣的

發(fā)布時(shí)間:2021-11-24 15:58:46 來源:億速云 閱讀:103 作者:柒染 欄目:云計(jì)算

這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān) 仿Openstack的WSGI接口及RESTul服務(wù)實(shí)現(xiàn)是怎樣的,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

Openstack的WSGI接口通過webob,pastedeploy,routes實(shí)現(xiàn)了Controller類,和Router類,這里仿照Openstack的WSG接口實(shí)現(xiàn)簡單的測試程序

首先是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函數(shù),返回的是Router().根據(jù)調(diào)用過程,初始化__init__->__call__返回self._routers.根據(jù)__init__下寫的映射規(guī)則,能識別類似/test/123這樣的路徑,其處理函數(shù)調(diào)用"Controller"的"action"函數(shù),也就是getMessage。

測試運(yùn)行,在瀏覽器下輸入127.0.0,1:8282/test/123

返回OK,如

return webob.Response('OK')

上述就是小編為大家分享的 仿Openstack的WSGI接口及RESTul服務(wù)實(shí)現(xiàn)是怎樣的了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI