簡體   English   中英

石墨烯:如何在查詢執行前添加 function?

[英]Graphene: How to add a function before query execute?

有沒有辦法在所有查詢之前執行 function ?

當我在查詢 class 上面添加注釋時,它會出錯

AssertionError: Type <function Query at 0x104d1dd30> is not a valid ObjectType.


def my_func(f):
    @wraps(f)
    def my_func_wrap(*args, **kwargs):
        //do something
        return f(*args, **kwargs)

    return my_func_wrap

@my_func
class Query(graphene.ObjectType):
    node = relay.Node.Field()

    users = graphene.List(lambda: UserSchema)

    def resolve_users(self, info):
        //do something
        return User.query.all()


schema = graphene.Schema(query=Query)

如果我將注釋添加到每個解析器,它工作正常。

但我將添加 20 多個解析器,我認為向每個解析器添加注釋並不是一個好主意。

是的你可以。 只需創建一個自定義視圖 class 繼承自GraphQLView並覆蓋dispatch方法,然后使用您自己的視圖 class 作為 graphql 端點處理程序。 像這樣的東西:

    class CustomGraphQLView(GraphQLView):
        def dispatch(self, request, *args, **kwargs):
            // do something
            super(CustomGraphqlView, self).dispatch(request, *args, **kwargs)

如果您想操作查詢集本身,我建議使用graphene-django-extras並在其查詢字段上覆蓋list_resolver方法( DjangoFilterListFieldDjangoFilterPaginateListField ,...)class 並使用您自己的自定義 class。

您可以在覆蓋方法上調用 super 或從其源中復制確切的代碼並進行編輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM