FastAPI自定义JSONAPIResponse子类无法访问content_object_type字段问题
问题原因
最可能的触发原因是FastAPI在处理响应流程中会调用响应对象的copy()方法,而父类JSONResponse的copy()方法仅会传递自身定义的参数(如content、status_code等)创建新实例,不会携带你自定义的content_object_type参数。这就导致新创建的JSONAPIResponse实例没有初始化该属性,当render()方法访问self.content_object_type时,就会抛出AttributeError。
另外你原代码中的render()方法仅访问属性却没有返回值,不符合父类要求的返回格式,也是潜在的问题点。
解决方案
修改自定义响应类,补充**kwargs兼容父类所有参数,并重写copy()方法确保自定义属性被正确复制,同时实现符合JSON:API规范的响应渲染逻辑:
from typing import Any from fastapi.responses import JSONResponse import json class JSONAPIResponse(JSONResponse): def __init__(self, content: Any, content_object_type: str, **kwargs): # 先不传递content给父类,后续在render中处理为JSON:API格式 super().__init__(content=None, **kwargs) self.content = content self.content_object_type = content_object_type def render(self, content: Any) -> bytes: # 构造JSON:API标准格式的响应体 jsonapi_content = { "data": { "type": self.content_object_type, "attributes": content or self.content } } return json.dumps(jsonapi_content).encode("utf-8") def copy(self) -> "JSONAPIResponse": # 重写copy方法,确保自定义属性被复制 return self.__class__( content=self.content, content_object_type=self.content_object_type, status_code=self.status_code, headers=dict(self.headers), media_type=self.media_type, background=self.background, )
调用方式保持不变即可:
return JSONAPIResponse(content=jsonable_encoder(content_object), content_object_type="bla")
内容的提问来源于stack exchange,提问作者oblio
相关产品推荐
相关产品推荐

