TypeError:“产品”对象在Flask中无法下标

时间:2019-04-20 05:59:49

标签: python flask flask-sqlalchemy marshmallow

我是python和flask的新手,正在学习构建Flask-rest-api。我正在使用SQLAlchemy作为数据库。我试图使用邮递员将数据发布到api,但我收到TypeError:对象不可下标。我对此完全陌生,不知道如何解决此问题及其含义。

我在stackoverflow中经历了一些解决方案,但是这些解决方案无法解决我的问题。抱歉,如果我无法正确解释这一点。

这是我的代码:

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'对象不可下标' Error traceback

   * 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

有人可以帮助我解决此错误吗?预先感谢。

1 个答案:

答案 0 :(得分:0)

问题是您已覆盖class Class(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, default="") duration = models.CharField(max_length=200, default="") description = models.CharField(max_length=200, default="") assigned_professors = models.CharField(max_length=200, default="") def save(self, *args, **kwargs): self.duration = #The value you'd want to automatically set here# super(Model, self).save(*args, **kwargs) 的值,因此它期望对象列表而不是单个对象。如果将第二个赋值中的变量名称更改为其他名称,例如product_schema,则您的代码应该可以使用。