當前位置: 首頁>>代碼示例>>Python>>正文


Python graphql.GraphQLError方法代碼示例

本文整理匯總了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." 
開發者ID:graphql-python,項目名稱:gql,代碼行數:27,代碼來源:test_subscription.py

示例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') 
開發者ID:MaxGoh,項目名稱:Flask-GraphQL-Graphene-MySQL-Docker-StarterKit,代碼行數:22,代碼來源:LoginUser.py

示例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 
開發者ID:edgedb,項目名稱:edgedb,代碼行數:26,代碼來源:translator.py

示例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) 
開發者ID:briancappello,項目名稱:flask-unchained,代碼行數:18,代碼來源:mutations.py

示例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() 
開發者ID:graphql-python,項目名稱:graphene-tornado,代碼行數:18,代碼來源:schema_utils.py

示例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 
開發者ID:lutece-awesome,項目名稱:lutece-backend,代碼行數:22,代碼來源:decorators.py

示例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()) 
開發者ID:lutece-awesome,項目名稱:lutece-backend,代碼行數:22,代碼來源:mutation.py

示例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()) 
開發者ID:lutece-awesome,項目名稱:lutece-backend,代碼行數:19,代碼來源:mutation.py

示例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'." 
開發者ID:graphql-python,項目名稱:gql,代碼行數:14,代碼來源:test_query.py

示例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) 
開發者ID:graphql-python,項目名稱:graphql-server-core,代碼行數:31,代碼來源:__init__.py

示例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) 
開發者ID:graphql-python,項目名稱:graphql-server-core,代碼行數:29,代碼來源:__init__.py

示例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.") 
開發者ID:MaxGoh,項目名稱:Flask-GraphQL-Graphene-MySQL-Docker-StarterKit,代碼行數:9,代碼來源:Me.py

示例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) 
開發者ID:MaxGoh,項目名稱:Flask-GraphQL-Graphene-MySQL-Docker-StarterKit,代碼行數:13,代碼來源:RegisterUser.py

示例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")) 
開發者ID:mirumee,項目名稱:ariadne,代碼行數:6,代碼來源:test_graphql.py

示例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) 
開發者ID:mirumee,項目名稱:ariadne,代碼行數:9,代碼來源:wsgi.py


注:本文中的graphql.GraphQLError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。