fastapi 路由表机制

"""
第一步:路由注册

目标:搞懂「带参数的装饰器」。
本步不涉及 HTTP、异步、校验,只是纯 Python。

对应 fastapi 里的:@app.get("/path")
"""

class App:
    def __init__(self):
        # 路由表,本质就是一个字典:
        #   key 是 (方法, 路径),value 是处理函数
        # fastapi 内部也是类似的注册表,只是结构复杂得多
        self.routes = {}

    def get(self, path):
        """
        这是一个「带参数的装饰器工厂」。注意它有三层:
          第一层 get(path)      —— 接收装饰器的参数(路径)
          第二层 decorator(func) —— 接收被装饰的函数
          第三层 return func     —— 把原函数还回去(注册的副作用已经发生)
        """
        def decorator(func):
            self.routes[("GET", path)] = func   # 副作用:把函数存进路由表
            return func                          # 把原函数原样返回
        return decorator

    def post(self, path):
        def decorate(func):
            self.routes[("POST", path)] = func
            return func
        return decorate

    def handle(self, method, path):
        """模拟「来了一个请求」:在路由表里查到函数并调用。"""
        func = self.routes.get((method, path))
        if func is None:
            return "404 Not Found"
        return func()


app = App()


# 关键理解:下面这个写法
#
#     @app.get("/hello")
#     def hello(): ...
#
# 完全等价于:
#
#     def hello(): ...
#     hello = app.get("/hello")(hello)
#
# 也就是:先执行 app.get("/hello") 得到 decorator,
# 再用 decorator(hello) 去注册并返回 hello。
@app.get("/hello")
def hello():
    return "你好,世界"


@app.get("/ping")
def ping():
    return "pong"

@app.post("/insert")
def insert():
    return "data has been inserted"

if __name__ == "__main__":
    # 看一眼路由表里到底存了什么
    print("路由表:", app.routes)
    print()

    # 模拟几个请求
    print("GET /hello ->", app.handle("GET", "/hello"))
    print("GET /ping  ->", app.handle("GET", "/ping"))
    print("GET /nope  ->", app.handle("GET", "/nope"))
    print("POST /insert  ->", app.handle("POST", "/insert"))

输出结果:

路由表: {('GET', '/hello'): <function hello at 0x10786aca0>, ('GET', '/ping'): <function ping at 0x10786ade0>, ('POST', '/insert'): <function insert at 0x10786ae80>}

GET /hello -> 你好,世界
GET /ping  -> pong
GET /nope  -> 404 Not Found
POST /insert  -> data has been inserted
posted @ 2026-07-03 12:37  RolandHe  阅读(8)  评论(0)    收藏  举报