极简fastapi框架
# 自己手写一个极简版 FastAPI 框架 class MiniFastAPI: def __init__(self): # 路由表存储 {(GET, /url1): 对应函数} self.router_map {} # 模仿 app.get(/path) 装饰器 def get(self, path: str): def decorator(func): # 把 请求方法路径 绑定到函数存入路由表 self.router_map[(GET, path)] func return func return decorator # ASGI 入口方法Uvicorn 固定会调用这个方法 async def __call__(self, scope, receive, send): # 只处理 http 请求 if scope[type] ! http: return # 1. 从请求里拿到 请求方法、URL路径 http_method scope[method] path scope[path] # 2. FastAPI 核心URL 匹配路由就是你问的分发匹配 key (http_method, path) if key in self.router_map: # 找到对应函数执行 res self.router_map[key]() response_body str(res).encode(utf-8) status_code 200 else: # 404 找不到路由 response_body b404 Not Found status_code 404 # 3. 返回响应给 Uvicorn await send({ type: http.response.start, status: status_code, headers: [(bcontent-type, btext/plain)], }) await send({ type: http.response.body, body: response_body, }) # ------------------- 用我们自己写的框架写接口 ------------------- # 实例化框架等价于 app FastAPI() app MiniFastAPI() # 注册 url1 接口 app.get(/url1) def url1_func(): return 这是 url1 对应的函数执行结果 # 注册 url2 接口 app.get(/url2) def url2_func(): return 这是 url2 对应的函数执行结果
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2618939.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!