V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
tangkikodo
V2EX  ›  Python

上次聊前后端分工还是有点空洞, 这次来贴一个 demo

  •  1
     
  •   tangkikodo · 44 天前 · 893 次点击
    这是一个创建于 44 天前的主题,其中的信息可能已经有所发展或是发生改变。

    https://www.v2ex.com/t/1055357?p=1#reply32 上期回顾

    项目地址

    https://github.com/allmonday/pydantic-resolve-demo

    主要介绍如何借助 graphql resolver 和 dataloader 这两个工具

    将 graphql 中对数据组合的便利性带到 fastapi/ django ninja (支持 pydantic )项目中来

    • 通过继承来复用查询接口
    • 通过 dataloader 来扩展需要的字段
    • 通过 openapi.json 把方法和 schema 暴露到前端快速使用。
    class MyBlogSite(BaseModel):
        name: str
        # blogs: list[Blog] = []  # this will not include comments and comment_count
        blogs: list[MyBlog] = []
        async def resolve_blogs(self):
            return await get_blogs()
    
        comment_count: int = 0
        def post_comment_count(self):
            return sum([b.comment_count for b in self.blogs])
            
    class MyBlog(Blog):
        # comments: list[Comment] = []  # this will not include user field
        comments: list[MyComment] = []
        def resolve_comments(self, loader=LoaderDepend(blog_to_comments_loader)):
            return loader.load(self.id)
    
        comment_count: int = 0
        def post_comment_count(self):
            return len(self.comments)
    
    class MyComment(Comment):
        user: Optional[User] = None
        def resolve_user(self, loader=LoaderDepend(user_loader)):
            return loader.load(self.user_id)
    
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2050 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 01:32 · PVG 09:32 · LAX 18:32 · JFK 21:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.