python mini webフレームワーク-4-ルーティング

1631 ワード

dynamic/my_web.py
import time
import os
import re

template_root = "./templates"

# ----------  ----------
#     url    
# url_route = {
#   "/index.py": index_func,
#   "/center.py": center_func
# }
g_url_route = dict()

# ----------  ----------
def route(url):
    def func1(func):
        #      ,key      url,value    url       ,         
        g_url_route[url] = func
        def func2(file_name):
            return func(file_name)
        return func2
    return func1


@route("/index.py")  # ----------  ----------
def index(file_name):
    """  index.py       """
    # return "hahha" + os.getcwd()  # for test     
    try:
        file_name = file_name.replace(".py", ".html")
        f = open(template_root + file_name)
    except Exception as ret:
        return "%s" % ret
    else:
        content = f.read()
        f.close()

        data_from_mysql = "      ,     mysql ,   mysql  ,       mysql       "
        content = re.sub(r"\{%content%\}", data_from_mysql, content)

        return content


@route("/center.py")  # ----------  ----------
def center(file_name):
    """  center.py       """
    # return "hahha" + os.getcwd()  # for test     
    try:
        file_name = file_name.replace(".py", ".html")
        f = open(template_root + file_name)
    except Exception as ret:
        return "%s" % ret
    else:
        content = f.read()
        f.close()

        data_from_mysql = "      ,,,,~~~~(>_