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

Flask GET请求触发TypeError: __init__缺失必填位置参数问题求助

报错原因

你将业务模型逻辑和Flask-RESTful的接口资源逻辑耦合到了同一个类中,并且为继承自Resource的Entry类自定义了带必填参数title的构造方法。Flask-RESTful框架实例化资源类时,只会传递内部的固定参数,不会将路由中的参数传递给__init__方法,因此实例化时缺少必填的title参数,直接抛出错误。

具体错误点
  • 为Resource子类自定义了带必填参数的构造方法,不符合Flask-RESTful的资源类定义规范
  • get方法中调用类方法find_entry_by_title时多传入了self参数,类方法调用无需传入实例
  • 接口直接返回自定义类实例,未转换为可JSON序列化的字典类型,即使解决构造参数问题后续也会报错
解决方案

推荐方案:拆分业务模型与接口资源(符合分层设计规范)

将数据库操作相关的业务逻辑抽为独立的模型类,不继承Resource,单独定义资源类处理HTTP请求:

import sqlite3
from flask import Flask
from flask_restful import Resource, Api

# 独立业务模型类,仅处理数据逻辑
class Entry:
    def __init__(self, title, language="Python", attempts=0,wins=0):
        self.title = title
        self.language = language
        self.attempts = attempts
        self.wins = wins

    def __repr__(self):
        # 原有逻辑保留
        pass

    def record_attempts_and_wins(self, a, w=0):
        # 原有逻辑保留
        pass

    @classmethod
    def find_entry_by_title(cls, title):
        connection = sqlite3.connect("data.db")
        cursor = connection.cursor()
        query = "SELECT * FROM entries WHERE title=?"
        result = cursor.execute(query, (title,))
        column = result.fetchone()
        entry = cls(*column) if column else None
        connection.close()
        return entry


# 接口资源类,仅处理HTTP请求逻辑
class EntryResource(Resource):
    def get(self, title):
        entry = Entry.find_entry_by_title(title)
        if not entry:
            return {"message": "条目不存在"}, 404
        # 转换为可序列化的字典返回
        return {
            "title": entry.title,
            "language": entry.language,
            "attempts": entry.attempts,
            "wins": entry.wins
        }

# 服务启动逻辑
app = Flask(__name__)
app.secret_key = "xyz"
api = Api(app)
api.add_resource(EntryResource, "/entry/<string:title>")

if __name__ == '__main__':
    app.run(debug=True)

临时修复方案(不推荐,仅作问题验证)

如果暂时不调整代码结构,可以修改构造方法兼容框架的实例化逻辑,同时修复调用错误:

class Entry(Resource):
    # 新增*args、**kwargs接收框架默认参数,调用父类构造
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 原有构造参数逻辑移除,业务参数从请求方法中获取
    
    # 其他原有逻辑保留,仅修改get方法
    def get(self, title):
        # 移除多余的self参数
        entry = Entry.find_entry_by_title(title)
        if not entry:
            return {"message": "条目不存在"}, 404
        return {
            "title": entry.title,
            "language": entry.language,
            "attempts": entry.attempts,
            "wins": entry.wins
        }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:42:04