当前位置: 首页>>代码示例>>Python>>正文


Python graphene.Mutation方法代码示例

本文整理汇总了Python中graphene.Mutation方法的典型用法代码示例。如果您正苦于以下问题:Python graphene.Mutation方法的具体用法?Python graphene.Mutation怎么用?Python graphene.Mutation使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在graphene的用法示例。


在下文中一共展示了graphene.Mutation方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: mutate

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def mutate(self, info, chatroom, text):
        """Mutation "resolver" - store and broadcast a message."""

        # Use the username from the connection scope if authorized.
        username = (
            info.context.user.username
            if info.context.user.is_authenticated
            else "Anonymous"
        )

        # Store a message.
        chats[chatroom].append({"chatroom": chatroom, "text": text, "sender": username})

        # Notify subscribers.
        OnNewChatMessage.new_chat_message(chatroom=chatroom, text=text, sender=username)

        return SendChatMessage(ok=True) 
开发者ID:datadvance,项目名称:DjangoChannelsGraphqlWs,代码行数:19,代码来源:example.py

示例2: test_keepalive

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def test_keepalive(gql):
    """Test that server sends keepalive messages."""

    print("Establish & initialize WebSocket GraphQL connection.")
    client = gql(
        query=Query,
        mutation=Mutation,
        subscription=Subscription,
        consumer_attrs={"strict_ordering": True, "send_keepalive_every": 0.05},
    )
    await client.connect_and_init()

    async def receive_keep_alive():
        response = await client.transport.receive()
        assert response["type"] == "ka", "Non keep alive response received!"

    await receive_keep_alive()
    print("Receive several keepalive messages.")
    for _ in range(3):
        await receive_keep_alive()

    print("Send connection termination message.")
    await client.send(msg_id=None, msg_type="connection_terminate")

    print("Disconnect and wait the application to finish gracefully.")
    await client.finalize()


# ---------------------------------------------------------------------- GRAPHQL BACKEND 
开发者ID:datadvance,项目名称:DjangoChannelsGraphqlWs,代码行数:31,代码来源:test_basic.py

示例3: test_middleware_called_in_query

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def test_middleware_called_in_query(gql):
    """Check that middleware called during query request."""

    middleware_called = False

    def middleware(next_middleware, root, info, *args, **kwds):
        nonlocal middleware_called
        middleware_called = True
        return next_middleware(root, info, *args, **kwds)

    print("Initialize WebSocket GraphQL connection with middleware enabled.")
    client = gql(
        query=Query,
        mutation=Mutation,
        subscription=Subscription,
        consumer_attrs={"strict_ordering": True, "middleware": [middleware]},
    )
    await client.connect_and_init()

    print("Make simple query and assert that middleware function called.")
    msg_id = await client.send(msg_type="start", payload={"query": "query { ok }"})
    await client.receive(assert_id=msg_id, assert_type="data")
    await client.receive(assert_id=msg_id, assert_type="complete")

    assert middleware_called, "Middleware is not called!"

    print("Disconnect and wait the application to finish gracefully.")
    await client.finalize() 
开发者ID:datadvance,项目名称:DjangoChannelsGraphqlWs,代码行数:30,代码来源:test_middleware.py

示例4: test_middleware_invocation_order

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def test_middleware_invocation_order(gql):
    """Check that several middleware called in a proper order."""

    middleware_invocation_log = []

    def middleware1(next_middleware, root, info, *args, **kwds):
        middleware_invocation_log.append(1)
        return next_middleware(root, info, *args, **kwds)

    def middleware2(next_middleware, root, info, *args, **kwds):
        middleware_invocation_log.append(2)
        return next_middleware(root, info, *args, **kwds)

    print("Initialize WebSocket GraphQL connection with middleware enabled.")
    client = gql(
        query=Query,
        mutation=Mutation,
        subscription=Subscription,
        consumer_attrs={
            "strict_ordering": True,
            "middleware": [middleware2, middleware1],
        },
    )
    await client.connect_and_init()

    print("Make simple query and assert that middleware function called.")
    msg_id = await client.send(msg_type="start", payload={"query": "query { ok }"})
    await client.receive(assert_id=msg_id, assert_type="data")
    await client.receive(assert_id=msg_id, assert_type="complete")

    assert middleware_invocation_log == [1, 2], "Middleware invocation order is wrong!"

    print("Disconnect and wait the application to finish gracefully.")
    await client.finalize()


# ---------------------------------------------------------------------- GRAPHQL BACKEND


# Mute Pytest for the Graphene DSL for the GraphQL setup.
# pylint: disable=arguments-differ,no-self-use 
开发者ID:datadvance,项目名称:DjangoChannelsGraphqlWs,代码行数:43,代码来源:test_middleware.py

示例5: __init__

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def __init__(self):
        self._typeMap = {}
        self.Field = create_registry_field(self)
        self.Argument = create_registry_argument(self)
        self.List = create_registry_list(self)
        self.NonNull = create_registry_nonnull(self)
        registering_metaclass = create_registering_metaclass(self)
        self.Union = create_union(registering_metaclass, self)
        self.Enum = create_enum(registering_metaclass)
        self.Mutation = graphene.Mutation

        # Not looping over GRAPHENE_TYPES in order to not fool lint
        self.ObjectType = create_registering_class(graphene.ObjectType, registering_metaclass)
        self.InputObjectType = create_registering_class(
            graphene.InputObjectType, registering_metaclass
        )
        self.Interface = create_registering_class(graphene.Interface, registering_metaclass)
        self.Scalar = create_registering_class(graphene.Scalar, registering_metaclass)

        # Not looping over GRAPHENE_BUILTINS in order to not fool lint
        self.String = graphene.String
        self.addType(graphene.String)
        self.Int = graphene.Int
        self.addType(graphene.Int)
        self.Float = graphene.Float
        self.addType(graphene.Float)
        self.Boolean = graphene.Boolean
        self.addType(graphene.Boolean)
        self.ID = graphene.ID
        self.addType(graphene.ID)
        self.GenericScalar = GenericScalar
        self.addType(GenericScalar) 
开发者ID:dagster-io,项目名称:dagster,代码行数:34,代码来源:dauphin_registry.py

示例6: create_schema

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def create_schema(self):
        return DauphinSchema(
            query=self.getType('Query'),
            mutation=self.getTypeOrNull('Mutation'),
            subscription=self.getTypeOrNull('Subscription'),
            types=self.getAllImplementationTypes(),
            registry=self,
        ) 
开发者ID:dagster-io,项目名称:dagster,代码行数:10,代码来源:dauphin_registry.py

示例7: test_should_create

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def test_should_create(fixtures):
    class CreateArticle(graphene.Mutation):
        class Arguments:

            headline = graphene.String()

        article = graphene.Field(ArticleNode)

        def mutate(self, info, headline):
            article = Article(headline=headline)
            article.save()

            return CreateArticle(article=article)

    class Query(graphene.ObjectType):

        node = Node.Field()

    class Mutation(graphene.ObjectType):

        create_article = CreateArticle.Field()

    query = """
        mutation ArticleCreator {
            createArticle(
                headline: "My Article"
            ) {
                article {
                    headline
                }
            }
        }
    """
    expected = {"createArticle": {"article": {"headline": "My Article"}}}
    schema = graphene.Schema(query=Query, mutation=Mutation)
    result = schema.execute(query)
    assert not result.errors
    assert result.data == expected 
开发者ID:graphql-python,项目名称:graphene-mongo,代码行数:40,代码来源:test_mutation.py

示例8: test_should_update

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def test_should_update(fixtures):
    class UpdateEditor(graphene.Mutation):
        class Arguments:
            id = graphene.ID()
            first_name = graphene.String()

        editor = graphene.Field(EditorNode)

        def mutate(self, info, id, first_name):
            editor = Editor.objects.get(id=id)
            editor.first_name = first_name
            editor.save()
            return UpdateEditor(editor=editor)

    class Query(graphene.ObjectType):

        node = Node.Field()

    class Mutation(graphene.ObjectType):

        update_editor = UpdateEditor.Field()

    query = """
        mutation EditorUpdater {
            updateEditor(
                id: "1"
                firstName: "Tony"
            ) {
                editor {
                    firstName
                }
            }
        }
    """
    expected = {"updateEditor": {"editor": {"firstName": "Tony"}}}
    schema = graphene.Schema(query=Query, mutation=Mutation)
    result = schema.execute(query)
    # print(result.data)
    assert not result.errors
    assert result.data == expected 
开发者ID:graphql-python,项目名称:graphene-mongo,代码行数:42,代码来源:test_mutation.py

示例9: graphql_mutation_from_summary

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def graphql_mutation_from_summary(summary):
    """
        This function returns a graphql mutation corresponding to the provided
        summary.
    """
    # get the name of the mutation from the summary
    mutation_name = summary['name']

    # print(summary)

    # the treat the "type" string as a gra
    input_name = mutation_name + "Input"
    input_fields = build_native_type_dictionary(summary['inputs'], name=input_name, respect_required=True)

    # the inputs for the mutation are defined by a class record
    inputs = type('Input', (object,), input_fields)

    # the outputs for the mutation are attributes to the class record
    output_name = mutation_name + "Output"
    outputs = build_native_type_dictionary(summary['outputs'], name=output_name)

    # a no-op in order to satisfy the introspection query
    mutate = classmethod(lambda *_, **__ : 'hello')

    # create the appropriate mutation class record
    mutation = type(mutation_name, (graphene.Mutation,), {
        'Input': inputs,
        'mutate': mutate,
        **outputs
    })

    # return the newly created mutation record
    return mutation 
开发者ID:AlecAivazis,项目名称:graphql-over-kafka,代码行数:35,代码来源:graphql_mutation_from_summary.py

示例10: test_confirmation_enabled

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def test_confirmation_enabled(gql):
    """Test subscription confirmation message received when enabled."""

    print("Establish WebSocket GraphQL connections with subscription confirmation.")

    client = gql(
        mutation=Mutation,
        subscription=Subscription,
        consumer_attrs={"strict_ordering": True, "confirm_subscriptions": True},
    )
    await client.connect_and_init()

    print("Subscribe & check there is a subscription confirmation message.")

    sub_op_id = await client.send(
        msg_type="start",
        payload={
            "query": "subscription op_name { on_trigger { is_ok } }",
            "operationName": "op_name",
        },
    )

    resp = await client.receive(assert_id=sub_op_id, assert_type="data")
    assert resp == {"data": None}

    print("Trigger the subscription.")

    mut_op_id = await client.send(
        msg_type="start",
        payload={
            "query": """mutation op_name { trigger { is_ok } }""",
            "operationName": "op_name",
        },
    )
    await client.receive(assert_id=mut_op_id, assert_type="data")
    await client.receive(assert_id=mut_op_id, assert_type="complete")

    print("Check that subscription notification received.")

    resp = await client.receive(assert_id=sub_op_id, assert_type="data")
    assert resp["data"]["on_trigger"]["is_ok"] is True

    await client.assert_no_messages(
        "Unexpected message received at the end of the test!"
    )
    await client.finalize() 
开发者ID:datadvance,项目名称:DjangoChannelsGraphqlWs,代码行数:48,代码来源:test_confirm_subscriptions.py

示例11: test_confirmation_disabled

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def test_confirmation_disabled(gql):
    """Test subscription confirmation message absent when disabled."""

    print("Establish WebSocket GraphQL connections w/o a subscription confirmation.")

    client = gql(
        mutation=Mutation,
        subscription=Subscription,
        consumer_attrs={"strict_ordering": True, "confirm_subscriptions": False},
    )
    await client.connect_and_init()

    print("Subscribe & check there is no subscription confirmation message.")

    sub_op_id = await client.send(
        msg_type="start",
        payload={
            "query": "subscription op_name { on_trigger { is_ok } }",
            "operationName": "op_name",
        },
    )

    await client.assert_no_messages("Subscribe responded with a message!")

    print("Trigger the subscription.")

    mut_op_id = await client.send(
        msg_type="start",
        payload={
            "query": """mutation op_name { trigger { is_ok } }""",
            "operationName": "op_name",
        },
    )
    await client.receive(assert_id=mut_op_id, assert_type="data")
    await client.receive(assert_id=mut_op_id, assert_type="complete")

    print("Check that subscription notification received.")

    resp = await client.receive(assert_id=sub_op_id, assert_type="data")
    assert resp == {"data": {"on_trigger": {"is_ok": True}}}

    await client.assert_no_messages(
        "Unexpected message received at the end of the test!"
    )
    await client.finalize() 
开发者ID:datadvance,项目名称:DjangoChannelsGraphqlWs,代码行数:47,代码来源:test_confirm_subscriptions.py

示例12: test_middleware_called_in_subscription

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def test_middleware_called_in_subscription(gql):
    """Check that middleware called during subscription processing.

    Middleware expected to be called two times: during subscribing to
    the subscription and during a notification.
    """
    middleware_call_counter = 0

    def middleware(next_middleware, root, info, *args, **kwds):
        nonlocal middleware_call_counter
        middleware_call_counter += 1
        return next_middleware(root, info, *args, **kwds)

    print("Initialize WebSocket GraphQL connection with middleware enabled.")
    client = gql(
        query=Query,
        mutation=Mutation,
        subscription=Subscription,
        consumer_attrs={"strict_ordering": True, "middleware": [middleware]},
    )
    await client.connect_and_init()

    print("Subscribe to GraphQL subscription.")
    sub_id = await client.send(
        msg_type="start", payload={"query": "subscription { on_trigger{ ok } }"}
    )
    await client.assert_no_messages()

    assert (
        middleware_call_counter == 1
    ), "Middleware is not called during subscribing to the subscription!"

    print("Manually trigger the subscription.")
    await OnTrigger.broadcast()

    # Receive subscription notification to guarantee that the
    # subscription processing has finished.
    await client.receive(assert_id=sub_id, assert_type="data")

    assert (
        middleware_call_counter == 2
    ), "Middleware is not called two times for subscription!"

    print("Disconnect and wait the application to finish gracefully.")
    await client.finalize() 
开发者ID:datadvance,项目名称:DjangoChannelsGraphqlWs,代码行数:47,代码来源:test_middleware.py

示例13: test_concurrent_queries

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def test_concurrent_queries(gql):
    """Check a single hanging operation does not block other ones."""

    print("Establish & initialize WebSocket GraphQL connection.")
    client = gql(query=Query, mutation=Mutation)
    await client.connect_and_init()

    print("Invoke a long operation which waits for the wakeup even.")
    long_op_id = await client.send(
        msg_type="start",
        payload={
            "query": "mutation op_name { long_op { is_ok } }",
            "variables": {},
            "operationName": "op_name",
        },
    )

    await client.assert_no_messages()

    print("Make several fast operations to check they are not blocked by the long one.")
    for _ in range(3):
        fast_op_id = await client.send(
            msg_type="start",
            payload={
                "query": "query op_name { fast_op_sync }",
                "variables": {},
                "operationName": "op_name",
            },
        )
        resp = await client.receive(assert_id=fast_op_id, assert_type="data")
        assert resp["data"] == {"fast_op_sync": True}
        await client.receive(assert_id=fast_op_id, assert_type="complete")

    print("Trigger the wakeup event to let long operation finish.")
    WAKEUP.set()

    resp = await client.receive(assert_id=long_op_id, assert_type="data")
    assert "errors" not in resp
    assert resp["data"] == {"long_op": {"is_ok": True}}
    await client.receive(assert_id=long_op_id, assert_type="complete")

    print("Disconnect and wait the application to finish gracefully.")
    await client.assert_no_messages(
        "Unexpected message received at the end of the test!"
    )
    await client.finalize()


# NOTE: Large `requests_number` values may lead to errors in `select`. 
开发者ID:datadvance,项目名称:DjangoChannelsGraphqlWs,代码行数:51,代码来源:test_concurrent.py

示例14: _add_form

# 需要导入模块: import graphene [as 别名]
# 或者: from graphene import Mutation [as 别名]
def _add_form(cls: Type[AbstractForm], node: str, dict_params: dict) -> Type[graphene.Mutation]:
    if node in registry.forms:  # pragma: no cover
        return registry.forms[node]

    registry.page_prefetch_fields.add(cls.__name__.lower())
    dict_params['Meta'].interfaces += (Page,)
    dict_params['form_fields'] = graphene.List(FormField)

    def form_fields(self, _info):
        return list(FormField(name=field_.clean_name, field_type=field_.field_type,
                              label=field_.label, required=field_.required,
                              help_text=field_.help_text, choices=field_.choices,
                              default_value=field_.default_value)
                    for field_ in self.form_fields.all())

    dict_params['resolve_form_fields'] = form_fields
    registry.pages[cls] = type(node, (DjangoObjectType,), dict_params)

    args = type("Arguments", (), {'values': GenericScalar(),
                                  "url": graphene.String(required=True)})
    _node = node

    def mutate(_self, info, url, values):
        url_prefix = url_prefix_for_site(info)
        query = wagtailPage.objects.filter(url_path=url_prefix + url.rstrip('/') + '/')
        instance = with_page_permissions(
            info.context,
            query.specific()
        ).live().first()
        user = info.context.user
        # convert camelcase to dashes
        values = {camel_case_to_spaces(k).replace(' ', '-'): v for k, v in values.items()}
        form = instance.get_form(values, None, page=instance, user=user)
        if form.is_valid():
            # form_submission
            instance.process_form_submission(form)
            return registry.forms[_node](result="OK")
        else:
            return registry.forms[_node](result="FAIL", errors=[FormError(*err) for err in form.errors.items()])

    dict_params = {
        "Arguments": args,
        "mutate": mutate,
        "result": graphene.String(),
        "errors": graphene.List(FormError),
    }
    tp = type(node + "Mutation", (graphene.Mutation,), dict_params)  # type: Type[graphene.Mutation]
    registry.forms[node] = tp
    return tp 
开发者ID:tr11,项目名称:wagtail-graphql,代码行数:51,代码来源:actions.py


注:本文中的graphene.Mutation方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。