TypeError: 'Product' object is not subscriptable in Flask

TypeError: 'Product' object is not subscriptable in Flask

我是 python 和 Flask 的新手,我正在学习构建 Flask-rest-api。我正在使用 SQLAlchemy 作为数据库。我尝试使用 postman 将 post 数据发送到 api,但我得到了 TypeError: Object is not subscriptable。我对此完全陌生,不知道如何解决这个问题以及它意味着什么。

我在 Whosebug 中查看了一些解决方案,但我无法用这些解决方案解决我的问题。对不起,如果我不能正确解释这一点。

这是我的代码:

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + 
os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

ma = Marshmallow(app)

class Product(db.Model):
   id = db.Column(db.Integer, primary_key=True, unique=True)
   name = db.Column(db.String(100))
   description = db.Column(db.String(200))
   price = db.Column(db.Float)
   qty = db.Column(db.Integer)

   def __init__(self, name, description, price, qty):
     self.name = name
     self.description = description
     self.price = price
     self.qty = qty

class ProductSchema(ma.Schema):
   class Meta:
      fields = ('id', 'name', 'description', 'price', 'qty')     

product_schema = ProductSchema(strict = True)   
product_schema = ProductSchema(many=True, strict = True)   

@app.route('/product', methods=['POST'])
def add_product():
   name = request.json['name']
   description = request.json['description']
   price = request.json['price']
   qty = request.json['qty']

   new_product = Product(name, description, price, qty)

   db.session.add(new_product)
   db.session.commit()

   return product_schema.jsonify(new_product)

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

我在发送时收到的错误是“TypeError: 'Product' object is not subscriptable”

   * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
   127.0.0.1 - - [20/Apr/2019 10:58:19] "POST /product HTTP/1.1" 400 -
   Product
   127.0.0.1 - - [20/Apr/2019 10:58:46] "POST /product HTTP/1.1" 500 -
   Traceback (most recent call last):
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask\app.py", line 2309, in __call__
   return self.wsgi_app(environ, start_response)
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask\app.py", line 2295, in wsgi_app
   response = self.handle_exception(e)
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask\app.py", line 1741, in handle_exception
   reraise(exc_type, exc_value, tb)
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask\_compat.py", line 35, in reraise
   raise value
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask\app.py", line 2292, in wsgi_app
   response = self.full_dispatch_request()
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask\app.py", line 1815, in full_dispatch_request
   rv = self.handle_user_exception(e)
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask\app.py", line 1718, in handle_user_exception
   reraise(exc_type, exc_value, tb)
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask\_compat.py", line 35, in reraise
   raise value
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask\app.py", line 1813, in full_dispatch_request
   rv = self.dispatch_request()
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask\app.py", line 1799, in dispatch_request
   return self.view_functions[rule.endpoint](**req.view_args)
   File "D:\workspace\backend\flask_sqlalchemy_rest\app.py", line 50, in 
   add_product
   return product_schema.jsonify(new_product)
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\flask_marshmallow\schema.py", line 41, in jsonify
   data = self.dump(obj, many=many).data
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\marshmallow\schema.py", line 508, in dump
   self._update_fields(processed_obj, many=many)
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\marshmallow\schema.py", line 777, in _update_fields
   ret = self.__filter_fields(field_names, obj, many=many)
   File "C:\Users\Asus\.virtualenvs\flask_sqlalchemy_rest-UOz-c0A6\lib\site- 
   packages\marshmallow\schema.py", line 824, in __filter_fields
   obj = obj[0]
   TypeError: 'Product' object is not subscriptable

谁能帮我解决这个错误?提前致谢。

问题是您覆盖了 product_schema 的值,因此它需要一个对象列表而不是单个对象。如果您将第二个赋值中的变量名称更改为其他名称,例如 products_schema,那么您的代码应该可以工作。

product_schema = ProductSchema()
products_schema = ProductSchema(many=True)

删除严格参数。它不再有效。