i am doubtful about my code. After looking for hours, was still not able to figure it out.
it's a very simple thing where i am trying to query a table with a given id. Then i want to update the 'name' attribute with the passed name.
But it's giving me an error- TypeError: 'Bucket' object does not support item assignment
. it'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 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)
From the docs and link , it is clearly visible that we can update the details as dictionary
, but here its not working.
bucket_to_update['name'] = name
TypeError: 'Bucket' object does not support item assignment
ps- i am creating a Resource class to have different creation/deletion methods using flask-restful
As pointed on comments and answers, its an object than a dictionary, you should access it as bucket.name=name
. Plus I had missed a colon while returning.
I don't have access to my coding environment but I reckon if you do following it should work fine.
bucket_to_update.name = name
Adding (3) at the end of def put(self, id):
, Correct return {"status" "success"}, 200
to return {"status":"success"}, 200
(1) In your class Bucket(db.Model):
you define the initialization function __init__
so you override that of the parent class db.Model
, so the __init__
function of the parent class will not be invoked.
Therefore, try:
def __init__(self, name):
db.Model.__init__(self) ## *** invoke __init__ of the parent class
self.name = name
(2) to update the modification in bucket_to_update
in:
bucket_to_update['name'] = name # >>>>>>>>>>>>>>>>>>>> PRODUCES AN ERROR
db.session.commit()
add db.session.add(bucket_to_update)
before commit:
bucket_to_update['name'] = name # >>>>>>>>>>>>>>>>>>>> PRODUCES AN ERROR
db.session.add(bucket_to_update)
db.session.commit()
looking for your comments.
Good Luck.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.