python---web框架本质(2)

目录
controllers    //存放控制方法
models         //存放模型方法
views            //存放视图模板
    index.html
    new.html
    show.html

index.py    //用户访问入口
bin.py        //程序人口
controller.py    //控制器(暂时放在根目录)
urls.py    //类似中间件
index.py
import bin

if __name__ == "__main__":
    bin.run();
View Code
bin.py
from wsgiref.simple_server import  make_server
from urls import URLS

def RunServer(environ, start_respone):
    start_respone('200 OK',[('Content-Type','text/html')]);
    url = environ['PATH_INFO'] #用户访问路径

    if url in URLS.keys():
        func_name = URLS[url]
        ret = func_name()
    else:
        ret = "<h1 style='color:red;'>404</h1>"

    return ret

def run():
    httpd=make_server('',8080,RunServer)
    httpd.serve_forever()
View Code
urls.py
import os
import time
#直接返回html字符
def new():
    file_path = os.path.join("views", "new.html")
    fp = open(file_path, 'r')
    content = fp.read()
    fp.close()
    return content

def index():
    file_path = os.path.join("views", "index.html")
    fp = open(file_path, 'r')
    content = fp.read()
    fp.close()
    content = content.replace("{{item}}",str(time.time()))
    return content


#改进,读取文件
def showFile():
    file_path=os.path.join("views","04模态对话框.html")
    fp = open(file_path,'r')
    content = fp.read()
    fp.close()

    return content
View Code
controller.py
import controller

#类似中间件
URLS ={
    "/new":controller.new,
    "/index":controller.index,
    "/show":controller.showFile,
}
View Code

 

posted @ 2018-03-05 15:10  山上有风景  阅读(298)  评论(0编辑  收藏  举报