为sqlalchemy模型映射jsonschema

alchemyjsonschema的Python项目详细描述


https://travis-ci.org/podhmo/alchemyjsonschema.svg

功能

alchemyjsonschema是用于将sqlalchemys的模型转换为jsonschema的库。

  • 使用alchemyjsonschema作为命令
  • 使用alchemyjsonschema作为库

作为库

有三种输出样式。

  • noforeignkeywalker–忽略关系
  • foreignkeywalker–期望有关关系的信息是外键
  • StructuralWalker–完整集输出(期望有关关系的信息是完整的JSON数据)

示例

转储具有以上三种输出样式的json。

目标模型在这里。组和用户。

# -*- coding:utf-8 -*-importsqlalchemyassaimportsqlalchemy.ormasormfromsqlalchemy.ext.declarativeimportdeclarative_baseBase=declarative_base()classGroup(Base):"""model for test"""__tablename__="Group"pk=sa.Column(sa.Integer,primary_key=True,doc="primary key")name=sa.Column(sa.String(255),default="",nullable=False)classUser(Base):__tablename__="User"pk=sa.Column(sa.Integer,primary_key=True,doc="primary key")name=sa.Column(sa.String(255),default="",nullable=True)group_id=sa.Column(sa.Integer,sa.ForeignKey(Group.pk),nullable=False)group=orm.relationship(Group,uselist=False,backref="users")

非外星键行者

importpprintasppfromalchemyjsonschemaimportSchemaFactoryfromalchemyjsonschemaimportNoForeignKeyWalkerfactory=SchemaFactory(NoForeignKeyWalker)pp.pprint(factory(User))"""
{'properties': {'name': {'maxLength': 255, 'type': 'string'},
                'pk': {'description': 'primary key', 'type': 'integer'}},
 'required': ['pk'],
 'title': 'User',
 'type': 'object'}
"""

外国键行者
importpprintasppfromalchemyjsonschemaimportSchemaFactoryfromalchemyjsonschemaimportForeignKeyWalkerfactory=SchemaFactory(ForeignKeyWalker)pp.pprint(factory(User))"""
{'properties': {'group_id': {'type': 'integer'},
                'name': {'maxLength': 255, 'type': 'string'},
                'pk': {'description': 'primary key', 'type': 'integer'}},
 'required': ['pk', 'group_id'],
 'title': 'User',
 'type': 'object'}
"""

结构步行机
importpprintasppfromalchemyjsonschemaimportSchemaFactoryfromalchemyjsonschemaimportStructuralWalkerfactory=SchemaFactory(StructuralWalker)pp.pprint(factory(User))"""
{'definitions': {'Group': {'properties': {'pk': {'description': 'primary key',
                                                 'type': 'integer'},
                                          'name': {'maxLength': 255,
                                                   'type': 'string'}},
                           'type': 'object'}},
 'properties': {'pk': {'description': 'primary key', 'type': 'integer'},
                'name': {'maxLength': 255, 'type': 'string'},
                'group': {'$ref': '#/definitions/Group'}},
 'required': ['pk'],
 'title': 'User',
 'type': 'object'}
"""pp.pprint(factory(Group))"""
{'definitions': {'User': {'properties': {'pk': {'description': 'primary key',
                                                'type': 'integer'},
                                         'name': {'maxLength': 255,
                                                  'type': 'string'}},
                          'type': 'object'}},
 'description': 'model for test',
 'properties': {'pk': {'description': 'primary key', 'type': 'integer'},
                'name': {'maxLength': 255, 'type': 'string'},
                'users': {'items': {'$ref': '#/definitions/User'},
                          'type': 'array'}},
 'required': ['pk', 'name'],
 'title': 'Group',
 'type': 'object'}
"""

作为命令

使用alchemyjsonschema as命令(命令名也是alchemyjsonschema)。

帮助

$ alchemyjsonschema --help
usage: alchemyjsonschema [-h][--walker {noforeignkey,foreignkey,structural}][--decision {default,fullset}][--depth DEPTH][--out OUT]
                         target

positional arguments:
  target                the module or class to extract schemas from

optional arguments:
  -h, --help            show this help message and exit
  --walker {noforeignkey,foreignkey,structural}
  --decision {default,fullset}
  --depth DEPTH
  --out OUT             output to file

以上两种模型定义(用户、组)存在于 AljyjjSnase.Test.Mask中。

目标是类位置或模块位置。例如,

  • 类位置–alchemyjsonschema.tests.models:user
  • 模块位置–alchemyjsonschema.tests.models

示例

通过命令行使用structural walker(–walker structural)。 当然,noforeignkeywalker是noforeignkey,而foreignkeywalker是foreignkey。

$ alchemyjsonschema --walker structural alchemyjsonschema.tests.models:Group

{"definitions": {"Group": {"properties": {"color": {"enum": ["red",
            "green",
            "yellow",
            "blue"],
          "maxLength": 6,
          "type": "string"},
        "created_at": {"format": "date-time",
          "type": "string"},
        "name": {"maxLength": 255,
          "type": "string"},
        "pk": {"description": "primary key",
          "type": "integer"},
        "users": {"items": {"$ref": "#/definitions/User"},
          "type": "array"}},
      "required": ["pk"],
      "title": "Group",
      "type": "object"},
    "User": {"properties": {"created_at": {"format": "date-time",
          "type": "string"},
        "name": {"maxLength": 255,
          "type": "string"},
        "pk": {"description": "primary key",
          "type": "integer"}},
      "required": ["pk"],
      "type": "object"}}}

直接使用walker类时,输出不相同。这是类似于swagger(openapi 2.0)工具的便捷输出。

附录:什么是“决定”?

什么是“决定”?(待办事项:温和描述)

$ alchemyjsonschema --walker structural alchemyjsonschema.tests.models:User | jq . -S > /tmp/default.json
$ alchemyjsonschema --decision useforeignkey --walker structural alchemyjsonschema.tests.models:User | jq . -S > /tmp/useforeignkey.json
$ diff -u /tmp/default.json /tmp/useforeignkey.json
--- /tmp/default.json 2017-01-02 22:49:44.000000000 +0900
+++ /tmp/useforeignkey.json   2017-01-02 22:53:13.000000000 +0900
@@ -1,43 +1,14 @@
 {
   "definitions": {
-    "Group": {
-      "properties": {
-        "color": {
-          "enum": [
-            "red",
-            "green",
-            "yellow",
-            "blue"
-          ],
-          "maxLength": 6,
-          "type": "string"
-        },
-        "created_at": {
-          "format": "date-time",
-          "type": "string"
-        },
-        "name": {
-          "maxLength": 255,
-          "type": "string"
-        },
-        "pk": {
-          "description": "primary key",
-          "type": "integer"
-        }
-      },
-      "required": [
-        "pk"
-      ],
-      "type": "object"
-    },
     "User": {
       "properties": {
         "created_at": {
           "format": "date-time",
           "type": "string"
         },
-        "group": {
-          "$ref": "#/definitions/Group"
+        "group_id": {
+          "relation": "group",
+          "type": "integer"
         },
         "name": {
           "maxLength": 255,

0.6.0

  • 修复jsonschema更新

0.4.2

  • 修复用模块(不是模型类)调用命令的错误

0.4.0

  • 删除不必要的功能(11)

0.3

  • 夸张的支持(感谢iSysd)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java数据未插入SQLite数据库   Java中内存有效的对象创建   java在方法内部使用“this”(不用于调用方法、构造函数或变量)   java为什么这里会出现NullPointerException?   在REST中使用HATEOAS导致的java循环依赖   java如何定制spring boot横幅?   Java数字基数计算器(即基数10到基数5)   如果在Kotlin vs Java中声明,用作全局上下文的安卓 MainApplication类将崩溃   用于过滤对象的Java lambda函数   java从字符串数组中获取整数列表   java为什么Maven找不到org。json JPMS自动模块?   java将字符串数组转换为int   仅当与阈值字节匹配时,java才会在映射中填充字符串值