了解marshmallow嵌套模式与列表数据

时间:2016-10-19 06:40:37

标签: python flask marshmallow

是python的新手,我正在使用marshmallow序列化。无法使用嵌套的scehma。  ,我的代码

from sqlalchemy import Column, Float, Integer, String, Text, text,ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()
metadata = Base.metadata




class CompanyDemo(Base):
    __tablename__ = 'company_demo'

    company_id = Column(Integer, primary_key=True,                                                     
    server_default=text("nextval('company_demo_company_id_seq'::regclass)"))
    name = Column(Text, nullable=False)
    address = Column(String(50))
    location = Column(String(50))


 class UsersDemo(Base):
    __tablename__ = 'users_demo'

    id = Column(Integer, primary_key=True,                                                                                                                    
    server_default=text("nextval('users_demo_id_seq'::regclass)"))
    company_id = Column(Integer,ForeignKey('company_demo.company_id'), nullable=False)
    email = Column(String)

company = relationship('CompanyDemo')

架构

    from marshmallow import Schema, fields, pprint


    class CompanySchema(Schema):
        company_id = fields.Int(dump_only=True)
        name = fields.Str()
        address = fields.Str()
        location = fields.Str()


    class UserSchema(Schema):
        email = fields.Str()   
        company = fields.Nested(CompanySchema)


    user = UserSchema()
    user = UserSchema(many=True)
    company = CompanySchema()
    company = CompanySchema(many=True)

和我的烧瓶应用

    from flask import Flask, jsonify, url_for, render_template
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker
    from flask_sqlalchemy import SQLAlchemy
    from model import CompanyDemo, UsersDemo
    from schemas.userschema import user, company

    app = Flask(__name__)
    app.secret_key = "shiva"


    def db_connect():
        engine = create_engine('postgresql://ss@127.0.0.1:5432/test')
        Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        # create a Session
        session = Session()
        session._model_changes = {}
        return session


    @app.route('/company', methods=["GET", "POST"])
    def get_all_company():
        db = db_connect()
        allcompany = db.query(CompanyDemo).join(UsersDemo).all()
        return jsonify(company.dump(allcompany, many=True).data)  # company is marshmallow schema


    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=15418, debug=True)

我的代码有什么问题?并且我遇到嵌套模式的问题,无法在输出中获取嵌套数据。

以下的输出
  

[{       “地址”:“qqq”,       “company_id”:1,       “location”:“www”,       “name”:“eee”},{       “地址”:“www”,       “company_id”:2,       “location”:“qqq”,       “名字”:“aaa”}]

1 个答案:

答案 0 :(得分:4)

使用内存中SQLite的自包含示例:

before_validation :set_slug    
validates :slug, uniqueness: true

private

def set_slug
...
end