Python graphql.graphql() Examples

The following are 13 code examples of graphql.graphql(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module graphql , or try the search function .
Example #1
Source File: cli.py    From dagster with Apache License 2.0 6 votes vote down vote up
def execute_query_against_remote(host, query, variables):
    parsed_url = urlparse(host)
    if not (parsed_url.scheme and parsed_url.netloc):
        raise click.UsageError(
            'Host {host} is not a valid URL. Host URL should include scheme ie http://localhost'.format(
                host=host
            )
        )

    sanity_check = requests.get(urljoin(host, '/dagit_info'))
    sanity_check.raise_for_status()
    if 'dagit' not in sanity_check.text:
        raise click.UsageError(
            'Host {host} failed sanity check. It is not a dagit server.'.format(host=host)
        )

    response = requests.post(
        urljoin(host, '/graphql'), params={'query': query, 'variables': variables}
    )
    response.raise_for_status()
    str_res = response.json()
    return str_res 
Example #2
Source File: utils.py    From dagster with Apache License 2.0 6 votes vote down vote up
def execute_dagster_graphql(context, query, variables=None):
    result = graphql(
        create_schema(),
        query,
        context=context,
        variables=variables,
        allow_subscriptions=True,
        return_promise=False,
    )

    # has to check attr because in subscription case it returns AnonymousObservable
    if hasattr(result, 'errors') and result.errors:
        first_error = result.errors[0]
        if hasattr(first_error, 'original_error') and first_error.original_error:
            raise result.errors[0].original_error

        raise result.errors[0]

    return result 
Example #3
Source File: test_star_wars_object_identification.py    From graphql-relay-py with MIT License 6 votes vote down vote up
def test_correctly_refetches_rebels():
    query = """
      query RebelsRefetchQuery {
        node(id: "RmFjdGlvbjox") {
          id
          ... on Faction {
            name
          }
        }
      }
    """
    expected = {
        "node": {"id": "RmFjdGlvbjox", "name": "Alliance to Restore the Republic"}
    }
    result = await graphql(StarWarsSchema, query)
    assert result == (expected, None) 
Example #4
Source File: graphql_ws_consumer.py    From DjangoChannelsGraphqlWs with MIT License 5 votes vote down vote up
def _format_error(error: Exception) -> Dict[str, Any]:
        """Format given exception `error` to send over a network."""
        if isinstance(error, graphql.error.GraphQLError):
            return dict(graphql.error.format_error(error))

        return {"message": f"{type(error).__name__}: {str(error)}"} 
Example #5
Source File: test_star_wars_object_identification.py    From graphql-relay-py with MIT License 5 votes vote down vote up
def test_correctly_fetches_id_name_rebels():
    query = """
      query RebelsQuery {
        rebels {
          id
          name
        }
      }
    """
    expected = {
        "rebels": {"id": "RmFjdGlvbjox", "name": "Alliance to Restore the Republic"}
    }
    result = await graphql(StarWarsSchema, query)
    assert result == (expected, None) 
Example #6
Source File: test_star_wars_object_identification.py    From graphql-relay-py with MIT License 5 votes vote down vote up
def test_correctly_fetches_id_name_empire():
    query = """
      query EmpireQuery {
        empire {
          id
          name
        }
      }
    """
    expected = {"empire": {"id": "RmFjdGlvbjoy", "name": "Galactic Empire"}}
    result = await graphql(StarWarsSchema, query)
    assert result == (expected, None) 
Example #7
Source File: test_star_wars_object_identification.py    From graphql-relay-py with MIT License 5 votes vote down vote up
def test_correctly_refetches_empire():
    query = """
      query EmpireRefetchQuery {
        node(id: "RmFjdGlvbjoy") {
          id
          ... on Faction {
            name
          }
        }
      }
    """
    expected = {"node": {"id": "RmFjdGlvbjoy", "name": "Galactic Empire"}}
    result = await graphql(StarWarsSchema, query)
    assert result == (expected, None) 
Example #8
Source File: test_star_wars_object_identification.py    From graphql-relay-py with MIT License 5 votes vote down vote up
def test_correctly_refetches_xwing():
    query = """
      query XWingRefetchQuery {
        node(id: "U2hpcDox") {
          id
          ... on Ship {
            name
          }
        }
      }
    """
    expected = {"node": {"id": "U2hpcDox", "name": "X-Wing"}}
    result = await graphql(StarWarsSchema, query)
    assert result == (expected, None) 
Example #9
Source File: test_star_wars_mutations.py    From graphql-relay-py with MIT License 5 votes vote down vote up
def test_correctly_mutates_dataset():
    query = """
      mutation AddBWingQuery($input: IntroduceShipInput!) {
        introduceShip(input: $input) {
          ship {
            id
            name
          }
          faction {
            name
          }
          clientMutationId
        }
      }
    """
    params = {
        "input": {"shipName": "B-Wing", "factionId": "1", "clientMutationId": "abcde"}
    }
    expected = {
        "introduceShip": {
            "ship": {"id": "U2hpcDo5", "name": "B-Wing"},
            "faction": {"name": "Alliance to Restore the Republic"},
            "clientMutationId": "abcde",
        }
    }
    result = await graphql(StarWarsSchema, query, variable_values=params)
    assert result == (expected, None) 
Example #10
Source File: base.py    From graphql-ws with MIT License 5 votes vote down vote up
def execute(self, request_context, params):
        return graphql(
            self.schema, **dict(params, allow_subscriptions=True)) 
Example #11
Source File: graphql_ws_consumer.py    From DjangoChannelsGraphqlWs with MIT License 4 votes vote down vote up
def _send_gql_data(
        self, operation_id, data: dict, errors: Optional[Sequence[Exception]]
    ):
        """Send GraphQL `data` message to the client.

        Args:
            data: Dict with GraphQL query response.
            errors: List of exceptions occurred during processing the
                GraphQL query. (Errors happened in resolvers.)

        """
        self._assert_thread()
        # Log errors with tracebacks so we can understand what happened
        # in a failed resolver.
        for ex in errors or []:
            # Typical exception here is `GraphQLLocatedError` which has
            # reference to the original error raised from a resolver.
            tb = ex.__traceback__
            if (
                isinstance(ex, graphql.error.located_error.GraphQLLocatedError)
                and ex.original_error is not None
            ):
                tb = ex.stack
                ex = ex.original_error
            LOG.error(
                "GraphQL resolver failed on operation with id=%s:\n%s",
                operation_id,
                "".join(traceback.format_exception(type(ex), ex, tb)).strip(),
            )

        await self.send_json(
            {
                "type": "data",
                "id": operation_id,
                "payload": {
                    "data": data,
                    **(
                        {"errors": [self._format_error(e) for e in errors]}
                        if errors
                        else {}
                    ),
                },
            }
        ) 
Example #12
Source File: cli.py    From dagster with Apache License 2.0 4 votes vote down vote up
def execute_query(workspace, query, variables=None, use_sync_executor=False, instance=None):
    check.inst_param(workspace, 'workspace', Workspace)
    check.str_param(query, 'query')
    check.opt_dict_param(variables, 'variables')
    instance = (
        check.inst_param(instance, 'instance', DagsterInstance)
        if instance
        else DagsterInstance.get()
    )
    check.bool_param(use_sync_executor, 'use_sync_executor')

    query = query.strip('\'" \n\t')

    locations = [RepositoryLocation.from_handle(x) for x in workspace.repository_location_handles]

    context = DagsterGraphQLContext(locations=locations, instance=instance, version=__version__,)

    executor = SyncExecutor() if use_sync_executor else GeventExecutor()

    result = graphql(
        request_string=query,
        schema=create_schema(),
        context_value=context,
        variable_values=variables,
        executor=executor,
    )

    result_dict = result.to_dict()

    context.drain_outstanding_executions()

    # Here we detect if this is in fact an error response
    # If so, we iterate over the result_dict and the original result
    # which contains a GraphQLError. If that GraphQL error contains
    # an original_error property (which is the exception the resolver
    # has thrown, typically) we serialize the stack trace of that exception
    # in the 'stack_trace' property of each error to ease debugging

    if 'errors' in result_dict:
        check.invariant(len(result_dict['errors']) == len(result.errors))
        for python_error, error_dict in zip(result.errors, result_dict['errors']):
            if hasattr(python_error, 'original_error') and python_error.original_error:
                error_dict['stack_trace'] = get_stack_trace_array(python_error.original_error)

    return result_dict 
Example #13
Source File: test_graphql.py    From dagster with Apache License 2.0 4 votes vote down vote up
def test_execute_hammer_through_dagit():
    # TODO: remove dependency on legacy_examples
    # https://github.com/dagster-io/dagster/issues/2653
    recon_repo = ReconstructableRepository.for_file(
        file_relative_path(
            __file__, '../../../../examples/legacy_examples/dagster_examples/toys/hammer.py'
        ),
        'hammer_pipeline',
    )
    instance = DagsterInstance.local_temp()

    context = DagsterGraphQLContext(
        locations=[InProcessRepositoryLocation(recon_repo)], instance=instance,
    )

    selector = infer_pipeline_selector(context, 'hammer_pipeline')

    executor = SyncExecutor()

    variables = {
        'executionParams': {
            'runConfigData': {
                'storage': {'filesystem': {}},
                'execution': {'dask': {'config': {'cluster': {'local': {}}}}},
            },
            'selector': selector,
            'mode': 'default',
        }
    }

    start_pipeline_result = graphql(
        request_string=LAUNCH_PIPELINE_EXECUTION_MUTATION,
        schema=create_schema(),
        context=context,
        variables=variables,
        executor=executor,
    )

    if start_pipeline_result.errors:
        raise Exception('{}'.format(start_pipeline_result.errors))

    run_id = start_pipeline_result.data['launchPipelineExecution']['run']['runId']

    context.drain_outstanding_executions()

    subscription = execute_dagster_graphql(context, SUBSCRIPTION_QUERY, variables={'runId': run_id})

    subscribe_results = []
    subscription.subscribe(subscribe_results.append)

    messages = [x['__typename'] for x in subscribe_results[0].data['pipelineRunLogs']['messages']]

    assert 'PipelineStartEvent' in messages
    assert 'PipelineSuccessEvent' in messages