1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
import time
HTML_ROOT_DIR = "./html"
class Application(object): """框架的核心部分,也就是框架的主题程序,框架是通用的""" def __init__(self, urls): self.urls = urls
def __call__(self, env, start_response): path = env.get("PATH_INFO", "/") if path.startswith("/static"): file_name = path[7:] try: file = open(HTML_ROOT_DIR + file_name, "rb") except IOError: status = "404 Not Found" headers = [] start_response(status, headers) return "not found" else: file_data = file.read() file.close()
status = "200 OK" headers = [] start_response(status, headers) return file_data.decode("utf-8")
for url, handler in self.urls: if path == url: return handler(env, start_response)
status = "404 Not Found" headers = [] start_response(status, headers) return "not found"
def show_ctime(env, start_response): status = "200 OK" headers = [ ("Content-Type", "text/plain") ] start_response(status, headers) return time.ctime()
def say_hello(env, start_response): status = "200 OK" headers = [ ("Content-Type", "text/plain") ] start_response(status, headers) return "hello world"
def say_haha(env, start_response): status = "200 OK" headers = [ ("Content-Type", "text/plain") ] start_response(status, headers) return "hello big world"
urls = [ ("/", show_ctime), ("/ctime", show_ctime), ("/sayhello", say_hello), ("/sayhaha", say_haha), ] app = Application(urls)
|