lundi 20 mai 2019

How do I dynamically create a graphene Object? For example, I want to at run time add fields and resolvers based off of a configuration file

I want to be able to create a GraphQL Server dynamically from a given configuration file. So for example, my configuration file will include what fields should exist, and some of the fields will have a flag indicating them as the primary key or secondary key which will map to them getting a resolver. How would I achieve dynamically creating a graphene object type?

I tried taking graphene's example code and adding fields to it. But it won't accept them. I tried diving into the meta data and updating some options, but that hasn't panned out either.

class User(graphene.ObjectType):
    id = graphene.ID()
    name = graphene.String()


class Query(graphene.ObjectType):
    me = graphene.Field(User)

    def resolve_me(self, info):
        return info.context["user"]

schema = graphene.Schema(query=Query)
query = """
    query something{
      me {
        name
        temp
      }
    }
"""

if __name__ == "__main__":
    userobj = User
    print(dir(userobj._meta.fields))
    setattr(userobj,"temp", graphene.String())
    print((userobj._meta.fields))

    userobj._meta.fields.update({"temp": graphene.String()})
    print(userobj._meta.fields)

    print((userobj._meta.fields))
    result = schema.execute(query, context={"user": userobj(id="X", name="Console", temp="hey")})
    print(result.data)
    print(result.data["me"])

Currently I get None with this attempt. Taking out the portion where I update _meta.fields, I get 'temp isn't a valid argument' for creating a userobj. 'temp' is an invalid keyword argument for User





Aucun commentaire:

Enregistrer un commentaire