接收空对象列表作为JSON Flask Rest API

问题描述

我正在尝试使用flask建立一个rest API。我使用sqlite作为我的数据库,使用SQLAlchemy作为我的对象关系映射器,使用棉花糖作为我的序列化库。我为客户表成功创建了POST映射API。但是,当我尝试构建像这样的获取所有客户端点时,

@app.route('/customers',methods=['GET'])
def get_customers():
    all_users = Customer.query.all()
    result = customer_schema.dump(all_users)
    return jsonify(result.data)

我收到一个错误AttributeError: 'list' object has no attribute 'data'

我使用此stackoverflow question解决了这个问题。

现在我的代码看起来像这样。

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;

database = SQLAlchemy(app)
ORM = Marshmallow(app)

#Models

##Customer Model
class Customer(database.Model):
    cus_id = database.Column(database.Integer,primary_key=True)
    first_name = database.Column(database.String(50))
    last_name = database.Column(database.String(50))
    address = database.Column(database.String(100))
    email = database.Column(database.String(100))
    nic = database.Column(database.String(10))
    telephone = database.Column(database.String(10))
    
    def __init__(self,first_name,last_name,address,email,nic,telephone):
        self.first_name = first_name
        self.last_name = last_name
        self.address = address
        self.email = email
        self.nic = nic
        self.telephone = telephone

##Customer Schema
class CustomerSchema(ORM.Schema):
    class Meta:
        Model = Customer

#Initialize Customer Schema
customer_schema = CustomerSchema(many=True)

#customer API

##Register a new customer
@app.route('/register',methods=['POST'])
def add_customer():
    first_name = request.json['first_name']
    last_name = request.json['last_name']
    address = request.json['address']
    email = request.json['email']
    nic = request.json['nic']
    telephone = request.json['telephone']

    new_customer = Customer(first_name,telephone)

    database.session.add(new_customer)
    database.session.commit()

    return customer_schema.jsonify(new_customer)

##Get all customers
@app.route('/customers',methods=['GET'])
def get_customers():
    all_users = Customer.query.all()
    result = customer_schema.dump(all_users)
    return jsonify(result)


#start the server       
if __name__ == '__main__':
    app.run(debug=True)

但是当我调用GET请求时,我只会得到一个空对象列表。(我的客户表有12个客户,而我却有12个空对象)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)