web架構之利用python的反射類比小web架構(二)動態匯入模組__web

來源:互聯網
上載者:User

web伺服器入口:

# _*_coding:utf-8_*_from wsgiref.simple_server import make_serverdef RunServer(environ, start_response):    start_response('200 OK',[('Content-Type','text/html')])    url = environ['PATH_INFO']    _, home, temp = url.split('/')    print temp    # home和temp是都是字串類型    module = __import__(home+'001')    # 將容器名字以字串形式匯入    # 此時 import home 是做不到的,即無法做到動態匯入模組    # module = __import__(model) 等價於 import model as module    is_exist = hasattr(module, temp)    print is_exist    if is_exist:        func = getattr(module, temp)        if dir(func)[0] == '__class__':            obj = func()            #執行個體對象建立在獨立於類對象的記憶體裡,但執行個體對象的記憶體裡有指向類的指標            # getattr會首先根據func對象(class)的dict,去找static_name屬性            # 這裡單純為了介紹嵌套反射,從容器home到容器admin_auth            var = getattr(func, 'static_name')            return var, "\t", obj.other()        else:            ret = func()            return ret    else:        return '404 not found!!!'if __name__ == '__main__':    httpd = make_server('', 8001, RunServer)    print 'Serving HTTP on port 8000'    httpd.serve_forever()

web後台控制:

  # _*_coding:utf-8_*_"""反射的第一層容器"""def index():    with open('index.html') as f:        str = f.readlines()    return strclass admin_auth(object):    """反射的第二層容器"""    static_name = "static_name:A string in admin"    def __init__(self):        self.name = 'ChangerLee'    def other(self):        return self.name

視圖views 模組:

        <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Test</title></head><body><h1>index</h1></body></html>
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.