写一个简单的WEB框架
2019-01-30 本文已影响13人
飘涯
前面都是从httpserver中添加功能,下面希望把添加web功能写成框架的形式,如果进行开发,只需要响应的功能模块就行,而不是在httpserver中改写。
想要实现的功能
外部调用,外部功能更新
urls=[
("/",show_ctime),
("/ctime",show_ctime),
("/sayhello",say_hello)
]
app = Applittation(urls)
http_server = HTTPServer(app)
http_server.bind(8000)
http_server.start()
创建一个通用框架的类
class Applittation(object):
'''框架的核心部分,框架的主题程序'''
def __init__(self,urls):
self.urls = urls
def __call__(self, env, start_response):
path = env.get("PATH_INFO","/")
print(path)
for url,handler in self.urls:
if path == url:
print(handler)
return handler(env,start_response)
#代表未找到路由信息404错误
status ="404 Not Found"
headers =[]
start_response(status,headers)
return "not found"
外部随便编写几个功能模块
def show_ctime(env,start_response):
states = "200 OK"
headers = {
("Content-Type", "text/plain")
}
start_response(states, headers)
return time.ctime()
def say_hello(env,start_response):
states = "200 OK"
headers = {
("Content-Type", "text/plain")
}
start_response(states, headers)
return "say hello"
精简服务模块
传入框架app模块
def __init__(self,application):
'''构造函数application指的是框架的app'''
self.serves_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
self.serves_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.app = application
总结
- 用回调函数,对类直接进行调用
def __call__(self, env, start_response):
- 把功能进行路由分发
path = env.get("PATH_INFO","/")
print(path)
结果
image.png启动更新,通过服务器启动程序
- 直接通过app对象调用框架里面的urls
urls = [
("/", show_ctime),
("/ctime", show_ctime),
("/sayhello", say_hello)
]
app = Applittation(urls)
- 启动设置
ef main():
sys.path.insert(1,WSGI_PYTHON_DIR)
#启动方式 python MyServer.py MyWebFramework:app
if len(sys.argv)<2:
sys.exit("python mywebserver.py mpdule:app")
module_name, app_name = sys.argv[1].split(":")
m = __import__(module_name)
app = getattr(m,app_name)
http_server = HTTPServer(app)
http_server.bind(8000)
http_server.start()