FastAPI对接Neo4j报TypeError: unhashable type:'list'如何解决
报错根因
触发TypeError: unhashable type: 'list'的直接原因是最后一行return {data}的写法错误:Python中{单值}的语法是创建集合(set),集合要求元素必须为可哈希的不可变类型;而你定义的data是列表(可变类型,不可哈希),无法作为集合元素,因此抛出类型错误。
需调整的代码点
- 修正返回值写法:禁止用集合包裹返回数据,FastAPI原生支持序列化列表、字典类型为JSON响应,如需包装响应结构请使用标准字典键值对格式。
- 优化Neo4j连接资源管理:原代码手动创建session后未做关闭处理,长期运行会出现连接泄漏,建议使用
with上下文管理器自动回收session资源。 - 修正字段拼写不一致问题:原Pydantic模型中字段写为
brith_type(拼写错误),与Cypher语句中使用的birth_type参数名不匹配,会导致参数传递异常,建议统一修正拼写。
修正后完整代码
from fastapi import FastAPI from pydantic import BaseModel # connection为你自行实现的Neo4j驱动初始化方法,保留原有引入逻辑即可 app = FastAPI() class UserModel(BaseModel): name: str age: int weight: int nativety: str birth_type: str # 修正原brith_type的拼写错误 @app.post('/createuser') async def createusernode(node: UserModel): driver_neo4j = connection() # 上下文管理器自动关闭session,避免连接泄漏 with driver_neo4j.session() as session: create_cypher = """ CREATE(n:user{name:$name, age:$age, weight: $weight, nativety: $nativety, birth_type: $birth_type}) RETURN n.name as name """ params = { "name": node.name, "age": node.age, "weight": node.weight, "nativety": node.nativety, "birth_type": node.birth_type } result = session.run(create_cypher, params) data = [{"Data": row["name"]} for row in result] # 标准JSON响应结构,不再使用集合包裹 return { "code": 200, "msg": "用户节点创建成功", "data": data }
效果说明
- 修正后接口不会再触发不可哈希类型报错,可正常返回JSON格式响应
- 新创建的用户节点会正确写入Neo4j,返回结果中携带新建节点的名称字段
- session资源会在请求处理完成后自动释放,无连接泄漏风险
内容的提问来源于stack exchange,提问作者daylightisminetocommand
相关产品推荐
相关产品推荐

