FastAPI子类继承报错AttributeError: 'myFastAPI'无router属性的解决
FastAPI子类继承后出现AttributeError: 'myFastAPI' object has no attribute 'router'的问题解决
问题描述
我创建了一个继承自FastAPI的子类myFastAPI,希望在类内部定义lifespan函数。为实现lifespan,我在myFastAPI类中编写了构造函数,示例代码如下:
class myFastAPI(FastAPI): def __init__(self): self.lifespan = self.lifeSpan @asynccontextmanager def lifeSpan(self): print("Start before Application") notification = Notification() yield {'client': notification} app.state.client.close() @app.get("/check") async def index(placeHolder: str) -> str: message = "API is up and running" client = request.app.state.client //some operations return message @app.post("/a/b/c") async def index(request, data) -> str: client = request.app.state.client result = somefunc(data, client) return result
启动API时出现如下错误:
File "/sdfjjgjg/File1.py", line 89, in <module> @app.get("/check") File "/asjgjgj/python3.8/site-packages/fastapi/applications.py", line 469, in get return self.router.get( AttributeError: 'myFastAPI' object has no attribute 'router'
我需要在myFastAPI类内部实现lifespan,而非文档中常见的外部定义方式,请问错误原因是什么?如何修复?
错误原因
自定义的myFastAPI类重写了__init__方法,但未调用父类FastAPI的__init__方法。FastAPI的核心组件(包括router属性)都是在父类的__init__中完成初始化的,子类实例因此缺少router属性,导致使用@app.get()等路由装饰器时触发AttributeError。
此外你的lifespan实现还有两处问题:
- 异步上下文管理器需要用
async def定义(当前用了普通def) - 关闭客户端时引用的全局
app对象可能不正确,应通过上下文获取当前应用实例
修复方案
核心修复步骤
- 在子类
__init__中调用父类构造函数,确保初始化所有FastAPI核心属性 - 修正lifespan的异步定义,正确处理应用状态和资源释放
- 修复路由函数中的语法错误(如Python注释用
#而非//、request需导入、POST路由参数顺序问题)
修复后的完整代码
from fastapi import FastAPI, Request from contextlib import asynccontextmanager # 假设Notification和somefunc是已定义的类/函数 class Notification: def close(self): print("Notification client closed") def somefunc(data, client): return f"Processed data with client: {client}" class myFastAPI(FastAPI): def __init__(self): # 必须调用父类构造函数,初始化router等核心属性 super().__init__() self.lifespan = self.lifeSpan @asynccontextmanager async def lifeSpan(self, app): # 接收FastAPI自动传入的app实例 print("Start before Application") notification = Notification() # 将客户端存入app.state供路由函数调用 app.state.client = notification yield # 通过传入的app参数关闭客户端,避免全局变量依赖 app.state.client.close() # 创建子类实例 app = myFastAPI() @app.get("/check") async def index(placeHolder: str, request: Request) -> str: message = "API is up and running" client = request.app.state.client # some operations return message @app.post("/a/b/c") async def post_index(request: Request, data: dict) -> str: client = request.app.state.client result = somefunc(data, client) return result
关键修复点说明
super().__init__():触发父类FastAPI的初始化逻辑,创建router等必要属性async def lifeSpan(self, app):FastAPI的lifespan上下文管理器必须是异步函数,且接收app参数(框架会自动传入当前应用实例)- 操作
app.state:通过传入的app参数管理状态,避免引用全局变量导致的潜在问题 - 路由函数中显式声明
Request参数:FastAPI需要显式声明该参数才能获取应用状态 - 修正语法细节:Python注释用
#,POST路由调整参数顺序(先声明Request,再声明请求体)
内容的提问来源于stack exchange,提问作者LOrD_ARaGOrN
相关产品推荐
相关产品推荐

