C/C++教程

marshmallow-sqlalchemy

本文主要是介绍marshmallow-sqlalchemy,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

marshmallow-sqlalchemy

https://marshmallow-sqlalchemy.readthedocs.io/en/latest/

https://github.com/marshmallow-code/marshmallow-sqlalchemy

 

SQLAlchemy integration with the marshmallow (de)serialization library.

 

marshmallow

https://marshmallow.readthedocs.io/en/3.0/

https://github.com/marshmallow-code/marshmallow

marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes.

In short, marshmallow schemas can be used to:

  • Validate input data.

  • Deserialize input data to app-level objects.

  • Serialize app-level objects to primitive Python types. The serialized objects can then be rendered to standard formats such as JSON for use in an HTTP API.

 

flask_marshmallow

https://flask-marshmallow.readthedocs.io/en/latest/

Flask + marshmallow for beautiful APIs

Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with Flask-SQLAlchemy.

 

https://realpython.com/flask-connexion-rest-api-part-2/

https://github.com/realpython/materials/blob/master/flask-connexion-rest-part-2/version_1/models.py

 

 

PLAY CODE

https://github.com/fanqingsong/code_snippet/blob/master/python/sqlalchemy/alchemy_serialize.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema


# 创建对象的基类:
Base = declarative_base()

# 定义User对象:
class User(Base):
    # 表的名字:
    __tablename__ = 'user'

    # 表的结构:
    id = Column(String(20), primary_key=True)
    name = Column(String(20))


class UserSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = User
        load_instance = True

# 初始化数据库连接:
engine = create_engine('sqlite:///test1.db')

# Base.metadata.create_all(engine)


# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)

# # 创建session对象:
# session = DBSession()
# # 创建新User对象:
# new_user = User(id='7', name='Bob')
# # 添加到session:
# session.add(new_user)
# # 提交即保存到数据库:
# session.commit()
# # 关闭session:
# session.close()

# 创建Session:
session = DBSession()
# 创建Query查询,filter是where条件,最后调用one()返回唯一行,如果调用all()则返回所有行:
user = session.query(User).filter(User.id=='6').one()
# 打印类型和对象的name属性:
print('type:', type(user))
print('name:', user.name)
# 关闭Session:
session.close()

user_schema = UserSchema()
dump_data = user_schema.dump(user)
print(dump_data)


load_data = user_schema.load(dump_data, session=session)
print(load_data)

 

这篇关于marshmallow-sqlalchemy的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!