Python graphql.GraphQLError() Examples

The following are 30 code examples of graphql.GraphQLError(). 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: test_query.py    From gql with MIT License 6 votes vote down vote up
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'." 
Example #2
Source File: translator.py    From edgedb with Apache License 2.0 6 votes vote down vote up
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 
Example #3
Source File: decorators.py    From lutece-backend with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: mutation.py    From lutece-backend with GNU General Public License v3.0 6 votes vote down vote up
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()) 
Example #5
Source File: LoginUser.py    From Flask-GraphQL-Graphene-MySQL-Docker-StarterKit with MIT License 6 votes vote down vote up
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') 
Example #6
Source File: mutation.py    From lutece-backend with GNU General Public License v3.0 6 votes vote down vote up
def mutate(self, info: ResolveInfo, *args, **kwargs):
        form = ExitContestTeamForm(kwargs)
        if form.is_valid():
            values = form.cleaned_data
            team = ContestTeam.objects.get(pk=values.get('pk'))
            contest = team.contest
            current_time = datetime.now()
            if current_time > contest.settings.end_time:
                raise GraphQLError('Time denied')
            usr = info.context.user
            # If owner exit, delete the entire team
            if team.owner == usr:
                team.memeber.all().delete()
                team.delete()
            else:
                member = team.memeber.get(user=usr)
                member.confirmed = False
                member.save()
                team.approved = False
                team.save()
            return ExitContestTeam(state=True)
        else:
            raise RuntimeError(form.errors.as_json()) 
Example #7
Source File: schema_utils.py    From graphene-tornado with MIT License 6 votes vote down vote up
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() 
Example #8
Source File: mutations.py    From flask-unchained with MIT License 6 votes vote down vote up
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) 
Example #9
Source File: mutation.py    From lutece-backend with GNU General Public License v3.0 6 votes vote down vote up
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()) 
Example #10
Source File: test_subscription.py    From gql with MIT License 6 votes vote down vote up
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." 
Example #11
Source File: mutations.py    From flask-unchained with MIT License 5 votes vote down vote up
def mutate(self, info, children, **kwargs):
        if children:
            children = (session_manager
                            .query(types.Child._meta.model)
                            .filter(types.Child._meta.model.id.in_(children))
                            .all())
        try:
            parent = types.Parent._meta.model(children=children, **kwargs)
        except ValidationErrors as e:
            raise GraphQLError(str(e))

        session_manager.save(parent, commit=True)
        return CreateParent(parent=parent, success=True) 
Example #12
Source File: query.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_article_comment_list(self: None, info: ResolveInfo, pk: int, page: int) -> ArticleCommentListType:
        article = get_object_or_None(Article, pk=pk)
        if not article:
            raise GraphQLError('No such article')
        article_comment_list = ArticleComment.objects.filter(article=article)
        privilege = info.context.user.has_perm('article.view_articlecomment')
        if not privilege:
            article_comment_list = article_comment_list.filter(disable=False)
        article_comment_list = article_comment_list.order_by('-vote')
        paginator = Paginator(article_comment_list, COMMENT_PER_PAGE_COUNT)
        return ArticleCommentListType(max_page=paginator.num_pages, article_comment_list=paginator.get_page(page)) 
Example #13
Source File: models.py    From flask-graphql-neo4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __validate_timestamp(self):
        try:
            maya.parse(self.timestamp, day_first=True, year_first=False)
        except Exception:
            raise GraphQLError(
                'The timestamp you provided is not within the format: "dd/mm/yyyy hh:mm"'
            ) 
Example #14
Source File: models.py    From flask-graphql-neo4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def fetch(self):
        customer = self.match(graph, self.email).first()
        if customer is None:
            raise GraphQLError(f'"{self.email}" has not been found in our customers list.')

        return customer 
Example #15
Source File: pytest.py    From flask-unchained with MIT License 5 votes vote down vote up
def _raise_non_graphql_exceptions(error):
    if isinstance(error, graphql.GraphQLError):
        return graphql.format_error(error)

    raise error 
Example #16
Source File: models.py    From flask-graphql-neo4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __verify_products(self, products):
        _total_amount = 0
        for product in products:
            _product = Product(name=product.get('name')).fetch()
            if _product is None:
                raise GraphQLError(f'"{product.name}" has not been found in our products list.')

            _total_amount += product['price'] * product['amount']
            product['product'] = _product
        return products, _total_amount 
Example #17
Source File: models.py    From flask-graphql-neo4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __verify_receipt(self, receipt):
        customer_properties = f":Customer {{email: '{self.email}'}}"
        receipt_properties = f":Receipt {{timestamp: '{receipt.timestamp}', total_amount:{receipt.total_amount}}}"
        existing_receipts = graph.run(
            f"MATCH ({customer_properties})-[relation:HAS]-({receipt_properties}) RETURN relation").data()

        if existing_receipts:
            raise GraphQLError("The receipt you're trying to submit already exists.") 
Example #18
Source File: models.py    From flask-graphql-neo4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __verify_store(self, store):
        _store = Store(**store).fetch_by_name_and_address()
        if _store is None:
            raise GraphQLError(f"The store \"{store['name']}\" does not exist in our stores list.")

        return _store 
Example #19
Source File: mutation.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def mutate(self: None, info: ResolveInfo, **kwargs):
        update_article_comment = UpdateBaseReplyForm(kwargs)
        if update_article_comment.is_valid():
            values = update_article_comment.cleaned_data
            usr = info.context.user
            comment = BaseReply.objects.get(pk=values.get('pk'))
            if not usr.has_perm('reply.change_basereply') and usr != comment.author:
                raise PermissionError('Permission Denied.')
            comment.content = values.get('content')
            comment.save()
            return UpdateBaseReply(state=True)
        else:
            raise GraphQLError(update_article_comment.errors.as_json()) 
Example #20
Source File: mutation.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def mutate(self: None, info: ResolveInfo, **kwargs):
        create_comment_reply = CreateCommentReplyForm(kwargs)
        if create_comment_reply.is_valid():
            values = create_comment_reply.cleaned_data
            usr = info.context.user
            parent = BaseReply.objects.get(pk=values.get('parent'))
            BaseReply.objects.create(
                content=values.get('content'),
                reply=parent,
                ancestor=parent.ancestor if parent.ancestor else parent,
                author=usr
            )
            return CreateCommentReply(state=True)
        else:
            raise GraphQLError(create_comment_reply.errors.as_json()) 
Example #21
Source File: mutation.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def mutate(self: None, info: ResolveInfo, **kwargs):
        toggle_reply_vote = ToggleReplyVoteForm(kwargs)
        if toggle_reply_vote.is_valid():
            values = toggle_reply_vote.cleaned_data
            reply = BaseReply.objects.get(pk=values.get('pk'))
            vote, state = ReplyVote.objects.get_or_create(reply=reply, record_user=info.context.user)
            vote.attitude = False if vote.attitude else True
            vote.save()
            reply.vote = ReplyVote.objects.filter(reply=reply, attitude=True).count()
            reply.save()
            return ToggleReplyVote(state=True)
        else:
            raise GraphQLError(toggle_reply_vote.errors.as_json()) 
Example #22
Source File: mutation.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def mutate(self, info: ResolveInfo, *args, **kwargs):
        form = CreateContestTeamForm(kwargs)
        if form.is_valid():
            values = form.cleaned_data
            contest = Contest.objects.get(pk=values.get('pk'))
            current_time = datetime.now()
            usr = info.context.user
            if current_time > contest.settings.end_time:
                raise GraphQLError('Time denied')
            if get_object_or_None(ContestTeam, contest=contest, owner=usr):
                raise GraphQLError('Only one team can be created in one contest')
            if get_object_or_None(ContestTeamMember, contest_team__contest=contest, user=usr, confirmed=True):
                raise GraphQLError('To create a team, must exit the previous one')
            members = json.loads(values.get('members'))
            usr = info.context.user
            if usr.username not in members:
                raise GraphQLError('No owner')
            team = ContestTeam.objects.create(
                contest=contest,
                name=values.get('name'),
                owner=info.context.user,
                additional_info=values.get('additional_info')
            )
            for each in members:
                ContestTeamMember.objects.create(
                    contest_team=team,
                    user=User.objects.get(username=each),
                    confirmed=True if each == usr.username else False
                )
            return CreateContestTeam(state=True)
        else:
            raise RuntimeError(form.errors.as_json())


# If team member call this function, would exit team, if owner or user with delete permission, delete the entire team. 
Example #23
Source File: mutation.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def mutate(self, info: ResolveInfo, *args, **kwargs):
        form = JoinContestTeamForm(kwargs)
        if form.is_valid():
            values = form.cleaned_data
            usr = info.context.user
            team = ContestTeam.objects.get(pk=values.get('pk'))
            if get_object_or_None(ContestTeamMember, contest_team__contest=team.contest, user=usr, confirmed=True):
                raise GraphQLError('To join other team, must exit the previous one.')
            member = team.memeber.get(user=usr)
            member.confirmed = True
            member.save()
            return JoinContestTeam(state=True)
        else:
            raise RuntimeError(form.errors.as_json()) 
Example #24
Source File: mutation.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def mutate(self, info: ResolveInfo, *args, **kwargs):
        form = UpdateContestTeamForm(kwargs)
        if form.is_valid():
            values = form.cleaned_data
            team = ContestTeam.objects.get(pk=values.get('pk'))
            current_time = datetime.now()
            if current_time > team.contest.settings.end_time:
                raise GraphQLError('Time denied')
            members = json.loads(values.get('members'))
            usr = info.context.user
            contain_owner = usr.username in members
            if (not contain_owner or team.owner != usr) and not usr.has_perm('contest.change_contestteam'):
                raise GraphQLError('No owner or permission denied')
            name = values.get('name')
            additional_info = values.get('additional_info')
            if name != team.name or additional_info != team.additional_info or set(
                    map(lambda each: each.user.username, team.memeber.all())) != set(members):
                team.approved = False
            team.name = name
            team.additional_info = additional_info
            team.save()
            for each in team.memeber.all():
                if each.user.username not in members:
                    each.delete()
            for each in members:
                ContestTeamMember.objects.get_or_create(
                    contest_team=team,
                    user=User.objects.get(username=each)
                )
            return UpdateContestTeam(state=True)
        else:
            raise RuntimeError(form.errors.as_json()) 
Example #25
Source File: query.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def resolve_contest_clarification_list(self: None, info: ResolveInfo, pk: graphene.ID(), page: graphene.Int()):
        contest = get_object_or_None(Contest, pk=pk)
        privilege = info.context.user.has_perm('contest.view_contest')
        if datetime.now() < contest.settings.start_time and not privilege:
            return ContestClarificationListType(max_page=1, contest_clarification_list=[])
        if not contest:
            raise GraphQLError('No such contest')
        clarification_list = ContestClarification.objects.filter(contest=contest)
        privilege = info.context.user.has_perm('contest.view_contestclarification')
        if not privilege:
            clarification_list = clarification_list.filter(disable=False)
        clarification_list = clarification_list.order_by('-vote')
        paginator = Paginator(clarification_list, CLARIFICATION_PER_PAGE_COUNT)
        return ContestClarificationListType(max_page=paginator.num_pages,
                                            contest_clarification_list=paginator.get_page(page)) 
Example #26
Source File: mutation.py    From lutece-backend with GNU General Public License v3.0 5 votes vote down vote up
def mutate(self: None, info: ResolveInfo, **kwargs):
        toggle_article_star = ToggleArticleStarForm(kwargs)
        if toggle_article_star.is_valid():
            values = toggle_article_star.cleaned_data
            article = Article.objects.get(pk=values.get('pk'))
            vote, state = ArticleVote.objects.get_or_create(article=article, record_user=info.context.user)
            vote.attitude = False if vote.attitude else True
            vote.save()
            return ToggleArticleVote(state=True)
        else:
            raise GraphQLError(toggle_article_star.errors.as_json()) 
Example #27
Source File: test_datetime.py    From graphene with MIT License 5 votes vote down vote up
def test_bad_time_query():
    not_a_date = "Some string that's not a time"

    result = schema.execute("""{ time(at: "%s") }""" % not_a_date)

    error = result.errors[0]
    assert isinstance(error, GraphQLError)
    assert (
        error.message == "Time cannot represent value:"
        ' "Some string that\'s not a time"'
    )
    assert result.data is None 
Example #28
Source File: __init__.py    From graphql-server-core with MIT License 5 votes vote down vote up
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) 
Example #29
Source File: __init__.py    From graphql-server-core with MIT License 5 votes vote down vote up
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) 
Example #30
Source File: Me.py    From Flask-GraphQL-Graphene-MySQL-Docker-StarterKit with MIT License 5 votes vote down vote up
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.")