Python graphql.Source() Examples

The following are 10 code examples of graphql.Source(). 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: __init__.py    From gql with MIT License 5 votes vote down vote up
def check_gql(self):
        if not self.tree or not self.lines:
            self.load_file()

        visitor = self.visitor_class(self.filename, self.options)
        visitor.visit(self.tree)

        for node in visitor.calls:
            # Lines with the noqa flag are ignored entirely
            if pycodestyle.noqa(self.lines[node.lineno - 1]):
                continue

            query = visitor.node_query(node)
            if not query:
                continue

            try:
                source = Source(query, 'gql query')
                ast = parse(source)
            except Exception as e:
                message = str(e)
                yield self.error(node, GQL_SYNTAX_ERROR, message)
                continue

            validation_errors = self.validation_errors(ast)
            if validation_errors:
                for error in validation_errors:
                    message = str(error)
                    yield self.error(node, GQL_VALIDATION_ERROR, message) 
Example #2
Source File: gql.py    From gql with MIT License 5 votes vote down vote up
def gql(request_string: str) -> DocumentNode:
    source = Source(request_string, "GraphQL request")
    return parse(source) 
Example #3
Source File: test_helpers.py    From graphql-server-core with MIT License 5 votes vote down vote up
def test_encode_execution_results_with_error():
    execution_results = [
        ExecutionResult(
            None,
            [
                GraphQLError(
                    "Some error",
                    source=Source(body="Some error"),
                    positions=[1],
                    path=["somePath"],
                )
            ],
        ),
        ExecutionResult({"result": 42}, None),
    ]

    output = encode_execution_results(execution_results)
    assert isinstance(output, ServerResponse)
    assert isinstance(output.body, str)
    assert isinstance(output.status_code, int)
    assert json.loads(output.body) == {
        "errors": [
            {
                "message": "Some error",
                "locations": [{"line": 1, "column": 2}],
                "path": ["somePath"],
            }
        ],
        "data": None,
    }
    assert output.status_code == 200 
Example #4
Source File: test_helpers.py    From graphql-server-core with MIT License 5 votes vote down vote up
def test_encode_execution_results_with_format_error():
    execution_results = [
        ExecutionResult(
            None,
            [
                GraphQLError(
                    "Some msg",
                    source=Source("Some msg"),
                    positions=[1],
                    path=["some", "path"],
                )
            ],
        )
    ]

    def format_error(error):
        return {
            "msg": error.message,
            "loc": "{}:{}".format(error.locations[0].line, error.locations[0].column),
            "pth": "/".join(error.path),
        }

    output = encode_execution_results(execution_results, format_error=format_error)
    assert isinstance(output, ServerResponse)
    assert isinstance(output.body, str)
    assert isinstance(output.status_code, int)
    assert json.loads(output.body) == {
        "errors": [{"msg": "Some msg", "loc": "1:2", "pth": "some/path"}],
        "data": None,
    }
    assert output.status_code == 200 
Example #5
Source File: translator.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def parse_tokens(
    text: str,
    tokens: List[Tuple[gql_lexer.TokenKind, int, int, int, int, str]]
) -> graphql.Document:
    try:
        src = graphql.Source(text)
        parser = graphql.language.parser.Parser(src)
        parser._lexer = TokenLexer(src, tokens, len(text))
        return parser.parse_document()
    except graphql.GraphQLError as err:
        err_loc = (err.locations[0].line,
                   err.locations[0].column)
        raise g_errors.GraphQLCoreError(err.message, loc=err_loc) from None 
Example #6
Source File: views.py    From graphene-django-extras with MIT License 5 votes vote down vote up
def get_operation_ast(self, request):
        data = self.parse_body(request)
        query = request.GET.get("query") or data.get("query")

        if not query:
            return None

        source = Source(query, name="GraphQL request")

        document_ast = parse(source)
        operation_ast = get_operation_ast(document_ast, None)

        return operation_ast 
Example #7
Source File: __init__.py    From graphql-django-view with MIT License 5 votes vote down vote up
def execute_graphql_request(self, request):
        query, variables, operation_name = self.get_graphql_params(request, self.parse_body(request))

        if not query:
            raise HttpError(HttpResponseBadRequest('Must provide query string.'))

        source = Source(query, name='GraphQL request')

        try:
            document_ast = parse(source)
            validation_errors = validate(self.schema, document_ast)
            if validation_errors:
                return ExecutionResult(
                    errors=validation_errors,
                    invalid=True,
                )
        except Exception as e:
            return ExecutionResult(errors=[e], invalid=True)

        if request.method.lower() == 'get':
            operation_ast = get_operation_ast(document_ast, operation_name)
            if operation_ast and operation_ast.operation != 'query':
                raise HttpError(HttpResponseNotAllowed(
                    ['POST'], 'Can only perform a {} operation from a POST request.'.format(operation_ast.operation)
                ))

        try:
            return self.execute(
                document_ast,
                root_value=self.get_root_value(request),
                variable_values=variables,
                operation_name=operation_name,
                context_value=self.get_context(request),
                executor=self.executor,
            )
        except Exception as e:
            return ExecutionResult(errors=[e], invalid=True) 
Example #8
Source File: test_concat_ast.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def test_it_concatenates_two_acts_together():
    source_a = Source("{ a, b, ... Frag }")
    source_b = Source(
        """
        fragment Frag on T {
            c
        }
    """
    )

    ast_a = parse(source_a)
    ast_b = parse(source_b)
    ast_c = concat_ast([ast_a, ast_b])

    assert (
        print_ast(ast_c)
        == """{
  a
  b
  ...Frag
}

fragment Frag on T {
  c
}
"""
    ) 
Example #9
Source File: test_ast_to_code.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def test_ast_to_code_using_kitchen_sink():
    doc = parse(fixtures.KITCHEN_SINK)
    code_ast = ast_to_code(doc)
    source = Source(fixtures.KITCHEN_SINK)

    def loc(start, end):
        return Loc(start, end, source)

    parsed_code_ast = eval(code_ast, {}, {"ast": ast, "loc": loc})
    assert doc == parsed_code_ast 
Example #10
Source File: test_schema_parser.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def create_loc_fn(body):
    # type: (str) -> Callable
    source = Source(body)
    return lambda start, end: Loc(start, end, source)