跳转到主要内容

为SQLAlchemy加载YAML数据固定值

项目描述

为SQLAlchemy加载YAML数据固定值

https://img.shields.io/pypi/v/sqla_yaml_fixtures.svg https://img.shields.io/pypi/l/sqla_yaml_fixtures.svg https://img.shields.io/pypi/pyversions/sqla_yaml_fixtures.svg https://github.com/schettino72/sqla_yaml_fixtures/workflows/test/badge.svg https://ko-fi.com/img/githubbutton_sm.svg

此包允许您在YAML中定义一些数据并将其加载到数据库中。yaml数据应与SQLAlchemy声明性映射器相对应。

示例

- User:
  - __key__: joey
    username: joey
    email: joey@example.com
    profile:
      name: Jeffrey

  - __key__: dee
    username: deedee
    email: deedee@example.com

- Profile:
  - user: dee
    name: Douglas

- Group:
  - name: Ramones
    members: [joey.profile, dee.profile]
  • YAML的根包含一个映射器名称序列,例如- User- Profile

  • 这些名称的顺序应遵循关系依赖关系

  • 每个名称应包含一个实例序列

  • 每个实例都是一个属性->的映射

  • 属性来自映射器 __init__()(通常一个属性映射到一个列)

  • 特殊字段 __key__ 可以用于在关系引用中标识此实例,例如 Profile.user

  • 注意,任何 __key__ 必须是全局 唯一

  • 在一对一关系(to-one)中,数据可以直接嵌套在父数据定义中

  • 引用可以使用 表示法访问属性,例如 joey.profile

  • 可以将 多对多 关系添加为引用列表

此示例的映射器定义在 测试文件 中。

安装

pip install sqla-yaml-fixtures

API

此模块公开一个单一函数 load(ModelBase, session, fixture_text, loader=None)

其中

  • ModelBase 是 SQLAlchemy 声明式基类

  • session 是 SQLAlchemy 会话

  • fixture_text 是包含 YAML 固件的字符串

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session

import sqla_yaml_fixtures

BaseModel = declarative_base()

class User(BaseModel):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    username = Column(String(150), nullable=False, unique=True)
    email = Column(String(254), unique=True)


def main():
    engine = create_engine('sqlite://')
    BaseModel.metadata.create_all(engine)
    connection = engine.connect()
    session = Session(bind=connection)

    fixture = """
    - User:
      - username: deedee
        email: deedee@example.com
      - username: joey
        email: joey@example.commit
    """
    sqla_yaml_fixtures.load(BaseModel, session, fixture)

    print('\n'.join(u.username for u in session.query(User).all()))

if __name__ == '__main__':
    main()

注意:load() 函数执行 session.commit()。

load() 返回 Store 的实例。使用此对象 方法,您可以通过传递作为参数的 获取添加到数据库中的对象的引用。这对于轻松获取数据库生成的属性很有用。

store = sqla_yaml_fixtures.load(BaseModel, session, fixture)
my_obj = store.get('dee')
print('Created object id: {}'.format(my_obj.id))

命令行

对于基本用法,还有命令行。示例

$ python -m sqla_yaml_fixtures --db-url sqlite:///dev.db --db-base mypkg.models:Base --reset-db --alembic-stamp fixture.yaml

所有可用选项

$ python -m sqla_yaml_fixtures --help
usage: sqla_yaml_fixtures [-h] --db-base DB_BASE --db-url DB_URL [--yes]
                          [--reset-db] [--alembic-stamp] [--jinja2]
                          FILE [FILE ...]

load fixtures from yaml file into DB

positional arguments:
  FILE               YAML file with DB fixtures

optional arguments:
  -h, --help         show this help message and exit
  --db-base DB_BASE  SQLAlchemy Base class with schema metadata in the format
                     my_package.my_module:MyClass
  --db-url DB_URL    Database URL in the format
                     dialect+driver://username:password@host:port/database
  --yes              Do NOT ask for confirmation before applying fixtures
  --reset-db         Drop DB schema and data and re-create schema before
                     loading fixtures
  --alembic-stamp    Perform `alembic stamp head`
  --jinja2           load fixture files as jinja2 templates

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

sqla_yaml_fixtures-1.1.0.tar.gz (9.4 kB 查看哈希值)

上传时间

构建分发

sqla_yaml_fixtures-1.1.0-py3-none-any.whl (9.1 kB 查看哈希值)

上传时间 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面