web服务器入口:
# _*_coding:utf-8_*_
from wsgiref.simple_server import make_server
def 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 str
class 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>