You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask项目出现RecursionError递归深度超限问题,求解决方案

解决Flask中RecursionError: maximum recursion depth exceeded的问题

这个递归错误的根源是模型类的__repr__方法之间形成了循环引用,导致调用时无限递归。我帮你分析下原因和解决办法:

问题原因

你贴出了User类的代码,但应该还有一个Post类(因为User里定义了posts = db.relationship('Post', backref='author', lazy=True))。大概率你的Post类的__repr__方法是这样的:

class Post(db.Model):
    # ... 其他字段 ...
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"Post('{self.title}', '{self.date_posted}', '{self.author}')"

这里的self.author会直接调用User对象的__repr__方法,而当User的__repr__被调用时,在某些场景(比如调试环境自动加载关联对象、打印查询结果)下,会触发posts关系的加载,进而调用每个Post对象的__repr__,如此往复就形成了无限递归,最终超出Python的递归深度限制。

解决办法

只需要打破这个循环引用即可,有两种简单的方式:

方式1:修改Post类的__repr__,引用关联对象的属性而非实例

把Post的__repr__里的self.author改成具体的属性(比如用户名),这样就不会触发User的__repr__调用:

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        # 用self.author.username替代self.author
        return f"Post('{self.title}', '{self.date_posted}', '{self.author.username}')"

方式2:确保User的__repr__不会触发关联对象加载

你的User类的__repr__已经没有引用posts属性了,这部分是没问题的。但如果后续你想在User的__repr__里展示关联内容,也要用属性而非实例,比如:

def __repr__(self):
    # 不要直接写self.posts,而是用len(self.posts)或者其他属性
    return f"User('{self.username}', '{self.email}', '{self.image_file}', {len(self.posts)} posts)"

额外提示

如果是在Flask Shell中测试时出现这个错误,也可以避免直接打印整个查询结果(比如print(User.query.all())),而是逐个打印对象的属性,比如:

for user in User.query.all():
    print(user.username, user.email)

内容的提问来源于stack exchange,提问作者xu0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:16:54