【问题标题】:Graphene resolver for an object that has no model没有模型的对象的石墨烯解析器
【发布时间】:2017-11-02 21:08:13
【问题描述】:

我正在尝试编写一个解析器,它返回一个由函数创建的对象。它从 memcached 中获取数据,因此没有实际的 model 我可以将其绑定到。

我认为我的主要问题是我无法弄清楚要使用什么 type 以及如何设置它。我将它与 Django 结合使用,但我认为这不是 django 问题(afaict)。到目前为止,这是我的代码:

class TextLogErrorGraph(DjangoObjectType):

    def bug_suggestions_resolver(root, args, context, info):
        from treeherder.model import error_summary
        return error_summary.bug_suggestions_line(root)

    bug_suggestions = graphene.Field(TypeForAnObjectHere, resolver=bug_suggestions_resolver)

请注意,我不知道要使用什么 typefield。有人能帮我吗? :)

【问题讨论】:

    标签: python django graphql


    【解决方案1】:

    GraphQL 设计为与后端无关,而 Graphene 旨在支持各种 Python 后端,例如 DjangoSQLAlchemy。要集成您的自定义后端,只需使用 Graphene 的 type system 定义您的模型并推出您自己的解析器。

    import graphene
    import time
    
    class TextLogEntry(graphene.ObjectType):
    
        log_id = graphene.Int()
        text = graphene.String()
        timestamp = graphene.Float()
        level = graphene.String()
    
    def textlog_resolver(root, args, context, info):
        log_id = args.get('log_id') # 123
        # fetch object...
        return TextLogEntry(
            log_id=log_id,
            text='Hello World',
            timestamp=time.time(),
            level='debug'
        )
    
    class Query(graphene.ObjectType):
    
        textlog_entry = graphene.Field(
            TextLogEntry,
            log_id=graphene.Argument(graphene.Int, required=True),
            resolver=textlog_resolver
        )
    
    
    schema = graphene.Schema(
        query=Query
    )
    

    【讨论】:

    • 即使在 3 年后也是一个很好的例子,谢谢
    猜你喜欢
    • 2018-01-29
    • 2018-06-28
    • 2019-06-13
    • 2021-03-14
    • 2021-03-19
    • 2020-08-25
    • 2019-04-28
    • 2019-01-02
    • 2021-07-08
    相关资源
    最近更新 更多