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>