/pydantic-resolve

retrive your data from root to leaves, and tweak the data from leaves to root.

Primary LanguagePythonMIT LicenseMIT

pypi Downloads Python Versions Test Coverage CI

Pydantic-resolve is a schema based, hierarchical solution for data fetching and crafting.

It can compose schemas together with resolver (and dataloader), and then expose typescript types and methods to client.

It can be a super simple alternative solution for GraphQL

Features:

  1. with pydantic schema and instances, resolver recursively resolve uncertain nodes and their descendants.
  2. nodes could be modified during post-process
  3. plugable, easy to combine together and reuse.

Install

User of pydantic v2, please use pydantic2-resolve instead.

pip install pydantic-resolve

Hello world

build blogs with comments

import asyncio
import json
from pydantic import BaseModel
from pydantic_resolve import Resolver

class Comment(BaseModel):
    id: int
    content: str

class Blog(BaseModel):
    id: int
    title: str
    content: str

    comments: list[Comment] = []
    def resolve_comments(self):
        return get_comments(self.id)


def get_blogs():
    return [
        dict(id=1, title="hello world", content="hello world detail"),
        dict(id=2, title="hello Mars", content="hello Mars detail"),
    ]

def get_comments(id):
    comments = [
        dict(id=1, content="world is beautiful", blog_id=1),
        dict(id=2, content="Mars is beautiful", blog_id=2),
        dict(id=3, content="I love Mars", blog_id=2),
    ]
    return [c for c in comments if c['blog_id'] == id]


async def main():
    blogs = [Blog.parse_obj(blog) for blog in get_blogs()]
    blogs = await Resolver().resolve(blogs)
    print(json.dumps(blogs, indent=2, default=lambda o: o.dict()))

asyncio.run(main())
[
  {
    "id": 1,
    "title": "hello world",
    "content": "hello world detail",
    "comments": [
      {
        "id": 1,
        "content": "world is beautiful"
      }
    ]
  },
  {
    "id": 2,
    "title": "hello Mars",
    "content": "hello Mars detail",
    "comments": [
      {
        "id": 2,
        "content": "Mars is beautiful"
      },
      {
        "id": 3,
        "content": "I love Mars"
      }
    ]
  }
]

Documents

Sponsor

If this code helps and you wish to support me

Paypal: https://www.paypal.me/tangkikodo

Discussion

Discord