本文整理汇总了Python中graphql.GraphQLError方法的典型用法代码示例。如果您正苦于以下问题:Python graphql.GraphQLError方法的具体用法?Python graphql.GraphQLError怎么用?Python graphql.GraphQLError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类graphql
的用法示例。
在下文中一共展示了graphql.GraphQLError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_subscription_support_using_client_invalid_field
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def test_subscription_support_using_client_invalid_field():
subs = gql(subscription_invalid_str)
params = {"ep": "JEDI"}
async with Client(schema=StarWarsSchema) as session:
# We subscribe directly from the transport to avoid local validation
results = [
result
async for result in session.transport.subscribe(
subs, variable_values=params
)
]
assert len(results) == 1
result = results[0]
assert isinstance(result, ExecutionResult)
assert result.data is None
assert isinstance(result.errors, list)
assert len(result.errors) == 1
error = result.errors[0]
assert isinstance(error, GraphQLError)
assert error.message == "The subscription field 'qsdfqsdfqsdf' is not defined."
示例2: mutate
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def mutate(self, info, email, password):
user = UserModel.query.filter_by(email=email).scalar()
if user and user._verify_password(password):
user.last_logged_in = datetime.datetime.now()
try:
user.save()
except Exception as e:
raise GraphQLError('Unable to update user', e)
else:
ok = True
message = "User has successfully logged in"
return LoginUser(
access_token=user.generate_access_token(),
refresh_token=user.generate_refresh_token(),
ok=ok,
message=message,
user=user
)
else:
raise Exception('Invalid Login Credentials')
示例3: convert_errors
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def convert_errors(
errs: List[gql_error.GraphQLError], *,
substitutions: Optional[Dict[str, Tuple[str, int, int]]],
) -> List[gql_error.GraphQLErrors]:
result = []
for err in errs:
m = REWRITE_TYPE_ERROR.match(err.message)
if not m:
# we allow conversion from Int to Float, and that is allowed by
# graphql spec. It's unclear why graphql-core chokes on this
if INT_FLOAT_ERROR.match(err.message):
continue
result.append(err)
continue
if (m.group("used"), m.group("expected")) in _IMPLICIT_CONVERSIONS:
# skip the error, we avoid it in the execution code
continue
value, line, col = substitutions[m.group("var_name")]
err = gql_error.GraphQLError(
f"Expected type {m.group('expected')}, found {value}.")
err.locations = [gql_lang.SourceLocation(line, col)]
result.append(err)
return result
示例4: mutate
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def mutate(self, info, id, children, **kwargs):
parent = session_manager.query(types.Parent._meta.model).get(id)
try:
parent.update(**{k: v for k, v in kwargs.items() if v})
except ValidationErrors as e:
raise GraphQLError(str(e))
if children:
parent.children = (session_manager
.query(types.Child._meta.model)
.filter(types.Child._meta.model.id.in_(children))
.all())
session_manager.save(parent, commit=True)
return EditParent(parent=parent, success=True)
示例5: generate_schema_hash
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def generate_schema_hash(schema: GraphQLSchema) -> str:
"""
Generates a stable hash of the current schema using an introspection query.
"""
ast = parse(introspection_query)
result = cast(ExecutionResult, execute(schema, ast))
if result and not result.data:
raise GraphQLError("Unable to generate server introspection document")
schema = result.data["__schema"]
# It's important that we perform a deterministic stringification here
# since, depending on changes in the underlying `graphql-core` execution
# layer, varying orders of the properties in the introspection
stringified_schema = stringify(schema).encode("utf-8")
return hashlib.sha512(stringified_schema).hexdigest()
示例6: check_contest_permission
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def check_contest_permission(func):
def wrapper(*args, **kwargs):
info = args[func.__code__.co_varnames.index('info')]
pk = info.variable_values.get('pk')
contest = get_object_or_None(Contest, pk=pk)
usr = info.context.user
if not contest:
raise GraphQLError('No such contest')
else:
privilege = usr.has_perm('contest.view_contest')
member = None
if usr.is_authenticated:
member = get_object_or_None(ContestTeamMember, user=usr, contest_team__contest=contest, confirmed=True)
if privilege or contest.is_public() or (
usr.is_authenticated and member and member.contest_team.approved):
return func(*args, **kwargs)
else:
return None
return wrapper
示例7: mutate
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def mutate(self: None, info: ResolveInfo, **kwargs):
form = CreateContestClarificationForm(kwargs)
if form.is_valid():
values = form.cleaned_data
contest = Contest.objects.get(pk=values.get('pk'))
reply = values.get('reply')
privilege = info.context.user.has_perm('contest.view_contest')
if datetime.now() < contest.settings.start_time and not privilege:
raise GraphQLError('Time denied')
if reply:
reply = ContestClarification.objects.get(pk=reply)
comment = ContestClarification.objects.create(
contest=contest,
content=values.get('content'),
reply=reply,
author=info.context.user
)
return CreateContestClarification(pk=comment.pk)
else:
raise GraphQLError(form.errors.as_json())
示例8: mutate
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def mutate(self: None, info: ResolveInfo, **kwargs):
create_article_comment = CreateArticleCommentForm(kwargs)
if create_article_comment.is_valid():
values = create_article_comment.cleaned_data
article = Article.objects.get(pk=values.get('pk'))
reply = values.get('reply')
if reply:
reply = ArticleComment.objects.get(pk=reply)
comment = ArticleComment.objects.create(
article=article,
content=values.get('content'),
reply=reply,
author=info.context.user
)
return CreateArticleComment(pk=comment.pk)
else:
raise GraphQLError(create_article_comment.errors.as_json())
示例9: test_parse_error
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def test_parse_error(client):
with pytest.raises(Exception) as exc_info:
gql(
"""
qeury
"""
)
error = exc_info.value
assert isinstance(error, GraphQLError)
formatted_error = format_error(error)
assert formatted_error["locations"] == [{"column": 13, "line": 2}]
assert formatted_error["message"] == "Syntax Error: Unexpected Name 'qeury'."
示例10: encode_execution_results
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def encode_execution_results(
execution_results: List[Optional[ExecutionResult]],
format_error: Callable[[GraphQLError], Dict] = format_error_default,
is_batch: bool = False,
encode: Callable[[Dict], Any] = json_encode,
) -> ServerResponse:
"""Serialize the ExecutionResults.
This function takes the ExecutionResults that are returned by run_http_query()
and serializes them using JSON to produce an HTTP response.
If you set is_batch=True, then all ExecutionResults will be returned, otherwise only
the first one will be used. You can also pass a custom function that formats the
errors in the ExecutionResults, expecting a dictionary as result and another custom
function that is used to serialize the output.
Returns a ServerResponse tuple with the serialized response as the first item and
a status code of 200 or 400 in case any result was invalid as the second item.
"""
results = [
format_execution_result(execution_result, format_error)
for execution_result in execution_results
]
result, status_codes = zip(*results)
status_code = max(status_codes)
if not is_batch:
result = result[0]
return ServerResponse(encode(result), status_code)
示例11: format_execution_result
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def format_execution_result(
execution_result: Optional[ExecutionResult],
format_error: Optional[Callable[[GraphQLError], Dict]] = format_error_default,
) -> FormattedResult:
"""Format an execution result into a GraphQLResponse.
This converts the given execution result into a FormattedResult that contains
the ExecutionResult converted to a dictionary and an appropriate status code.
"""
status_code = 200
response: Optional[Dict[str, Any]] = None
if execution_result:
if execution_result.errors:
fe = [format_error(e) for e in execution_result.errors] # type: ignore
response = {"errors": fe}
if execution_result.errors and any(
not getattr(e, "path", None) for e in execution_result.errors
):
status_code = 400
else:
response["data"] = execution_result.data
else:
response = {"data": execution_result.data}
return FormattedResult(response, status_code)
示例12: resolve_me
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def resolve_me(self, info):
id = get_jwt_identity()
user = UserModel.query.filter_by(id=id).scalar()
if user:
return user
else:
raise GraphQLError("User is not found.")
示例13: mutate
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def mutate(self, info, **kwargs):
user = UserModel(**kwargs)
try:
user.save()
except Exception as e:
raise GraphQLError("Error creating User object.", e)
else:
ok = True
message = "User have been created successfully"
return RegisterUser(ok=ok, message=message)
示例14: leave_operation_definition
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def leave_operation_definition( # pylint: disable=unused-argument
self, *args, **kwargs
):
self.context.report_error(GraphQLError("Invalid"))
示例15: __call__
# 需要导入模块: import graphql [as 别名]
# 或者: from graphql import GraphQLError [as 别名]
def __call__(self, environ: dict, start_response: Callable) -> List[bytes]:
try:
return self.handle_request(environ, start_response)
except GraphQLError as error:
return self.handle_graphql_error(error, start_response)
except HttpError as error:
return self.handle_http_error(error, start_response)