【问题标题】:flask SQL-Alchmey not returning a dictionary while querying烧瓶 SQL-Alchmey 在查询时不返回字典
【发布时间】:2021-04-09 22:53:20
【问题描述】:

我怀疑我的代码。找了几个小时还是没搞明白。

这是一件非常简单的事情我正在尝试查询具有给定 ID 的表。然后我想用传递的名称更新“名称”属性。

但这给了我一个错误-TypeError: 'Bucket' object does not support item assignmentit's like its not returning a dictionary

    # PUT REQUEST
    def put(self, id):
        bucket_to_update = bucket_db.query.get(id)   #### returns <Bucket id> , not dict
        print(bucket_to_update)  # prints the bucket as string

        if not bucket_to_update:
            return {"status": "failure"}, 404

        args = BucketAPI.parser.parse_args()
        name = args.get('name', None)

        bucket_to_update['name'] = name  # >>>>>>>>>>>>>>>>>>>> PRODUCES AN ERROR
        db.session.commit()

        return {"status" "success"}, 200

模型 - Bucket / bucket_db


"""Bucket model"""
from todo_app import db


class Bucket(db.Model):
    __tablename__ = 'buckets'

    def __init__(self, name):
        self.name = name

    id = db.Column(
        db.Integer,
        primary_key=True
    )

    name = db.Column(
        db.Text,
        index=True,
        unique=True,
        nullable=False
    )

    items = db.relationship('Item',
                            backref=db.backref('bucket', lazy='joined'),
                            lazy=True)

    def __repr__(self):
        return '<bucket-{}> '.format(self.name)


docslink 可以清楚地看到我们可以更新details as dictionary,但是这里它不起作用。

错误日志

    bucket_to_update['name'] = name
   TypeError: 'Bucket' object does not support item assignment

p.s- 我正在创建一个 Resource 类以使用 flask-restful 具有不同的创建/删除方法

更新(已解决)

正如 cmets 和答案所指出的,它是一个对象而不是字典,您应该以 bucket.name=name 访问它。另外,我在返回时错过了一个冒号。

【问题讨论】:

  • 这些链接都没有表明您可以将对象用作字典,而只是用作对象。 bucket_to_update.name = name 将匹配您链接答案中的语法,not bucket_to_update['name'] = name。也(通常)不需要使用 Flask-SqlAlchemy 显式提交,因为只要返回的状态不是 4xx 或 5xx 错误,它就会这样做。
  • @MatsLindh,我被那本字典蒙蔽了双眼,有一半时间我很担心!非常感谢

标签: python flask sqlalchemy flask-sqlalchemy flask-restful


【解决方案1】:

我无法访问我的编码环境,但我认为如果你遵循它应该可以正常工作。

    bucket_to_update.name = name

【讨论】:

    【解决方案2】:

    添加(3)在def put(self, id):末尾, 将return {"status" "success"}, 200 更正为return {"status":"success"}, 200

    (1) 在您的class Bucket(db.Model): 中定义了初始化函数__init__,因此您覆盖了父类db.Model 的初始化函数,因此不会调用父类的__init__ 函数。

    因此,请尝试:

        def __init__(self, name):
            db.Model.__init__(self) ## *** invoke __init__ of the parent class
            self.name = name
    

    (2)在bucket_to_update中更新修改:

            bucket_to_update['name'] = name  # >>>>>>>>>>>>>>>>>>>> PRODUCES AN ERROR
            db.session.commit()
    

    在提交前添加db.session.add(bucket_to_update)

            bucket_to_update['name'] = name  # >>>>>>>>>>>>>>>>>>>> PRODUCES AN ERROR
            db.session.add(bucket_to_update)
            db.session.commit()
    

    正在寻找您的 cmets。

    祝你好运。

    【讨论】:

    • @Hussein,我试过你的东西......它不起作用
    • 我在答案中添加了第(3)点修改,等待您的cmets
    • @Hussein,非常感谢.. 终于解决了!!
    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多