1

我正在尝试使用flask-restful、flask-sqlalchemy和flask-marshmallow来实现一个restful API。我知道有很多关于这个问题的问题,但我仍然无法弄清楚。在棉花糖模式中使用strict=True或将.data添加到user_schema.dump(result)等解决方案不会让我在响应正文中看到我的结果。

这是我的代码:

# User.py file

from flask import jsonify, request
from flask_restful import Resource
from src import db
from src.models.user import User
from src.validation import UserSchema


class Users(Resource):
    def get(self):
        try:
            data = request.get_json()
            user = User.query.filter_by(email=data['email']).first()
            user_schema = UserSchema()
            result = user_schema.dump(user)
            return jsonify(result)
        except:
            return jsonify({'error_message': 'User not found'})

    def post(self):
        try:
            data = request.get_json()
            user = User(data["firstName"], data["lastName"],
                        data["email"], data["password"])
            db.session.add(user)
            db.session.commit()
            user_schema = UserSchema()
            result = user_schema.dump(user)
            return result
        except:
            return jsonify({'error_message': 'User already exists in database'})

初始化.py文件:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Api
from flask_marshmallow import Marshmallow


app = Flask(__name__)
app.config["DEBUG"] = True
app.config["SQLALCHEMY_ECHO"] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql:///gauss"

ma = Marshmallow(app)
api = Api(app)
db = SQLAlchemy(app)

from src import routes

验证.py文件:

from src import ma
from src.models.user import User

class UserSchema(ma.SQLAlchemySchema):
    class Meta:
        model = User

以及数据库的User.py架构:

from src import db
from datetime import datetime

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    firstName = db.Column(db.String(20))
    lastName = db.Column(db.String(20))
    email = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(), nullable=False)
    createdAt = db.Column(db.DateTime, default=datetime.utcnow)

    def __init__(self, firstName, lastName, email, password):
        self.firstName = firstName
        self.lastName = lastName
        self.email = email
        self.password = password

几天来我一直在寻找解决方案,例如,当使用 .all( )方法查询时,似乎棉花糖返回空 json 主要发生,因为棉花糖.dump()方法错过了Many=True配置。

我可能错过了一些东西,但我无法理解它。任何帮助表示赞赏!

4

1 回答 1

0

我有同样的问题,我的问题的解决方案是更改UserSchema(ma.SQLAlchemySchema):UserSchema(ma.SQLAlchemyAutoSchema):

于 2021-11-04T10:42:16.157 回答