本文整理汇总了Python中graphql.graphql方法的典型用法代码示例。如果您正苦于以下问题:Python graphql.graphql方法的具体用法?Python graphql.graphql怎么用?Python graphql.graphql使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类graphql
的用法示例。
在下文中一共展示了graphql.graphql方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute_query_against_remote
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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
示例2: execute_dagster_graphql
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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
示例3: test_correctly_refetches_rebels
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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)
示例4: _format_error
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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)}"}
示例5: test_correctly_fetches_id_name_rebels
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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)
示例6: test_correctly_fetches_id_name_empire
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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)
示例7: test_correctly_refetches_empire
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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)
示例8: test_correctly_refetches_xwing
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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)
示例9: test_correctly_mutates_dataset
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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)
示例10: execute
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
def execute(self, request_context, params):
return graphql(
self.schema, **dict(params, allow_subscriptions=True))
示例11: _send_gql_data
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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 {}
),
},
}
)
示例12: execute_query
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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
示例13: test_execute_hammer_through_dagit
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import graphql [as 别名]
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