Пример #1
0
def test_reports_custom_validation_errors():
    class CustomValidationRule(ValidationRule):
        def enter_field(self, node, *_args):
            self.report_error(GraphQLError("Custom validation error.", node))

    results, params = run_http_query(
        schema,
        "get",
        {},
        query_data=dict(query="{ test }"),
        validation_rules=[CustomValidationRule],
    )

    assert as_dicts(results) == [{
        "data":
        None,
        "errors": [{
            "message": "Custom validation error.",
            "locations": [{
                "line": 1,
                "column": 3
            }],
        }],
    }]

    response = encode_execution_results(results)
    assert response.status_code == 400
Пример #2
0
def test_allows_get_with_operation_name():
    results, params = run_http_query(
        schema,
        "get",
        {},
        query_data=dict(
            query="""
        query helloYou { test(who: "You"), ...shared }
        query helloWorld { test(who: "World"), ...shared }
        query helloDolly { test(who: "Dolly"), ...shared }
        fragment shared on QueryRoot {
          shared: test(who: "Everyone")
        }
        """,
            operationName="helloWorld",
        ),
    )

    assert as_dicts(results) == [{
        "data": {
            "test": "Hello World",
            "shared": "Hello Everyone"
        },
        "errors": None
    }]

    response = encode_execution_results(results)
    assert response.status_code == 200
Пример #3
0
def test_reports_max_num_of_validation_errors():
    results, params = run_http_query(
        schema,
        "get",
        {},
        query_data=dict(query="{ test, unknownOne, unknownTwo }"),
        max_errors=1,
    )

    assert as_dicts(results) == [{
        "data":
        None,
        "errors": [
            {
                "message":
                "Cannot query field 'unknownOne' on type 'QueryRoot'.",
                "locations": [{
                    "line": 1,
                    "column": 9
                }],
            },
            {
                "message":
                "Too many validation errors, error limit reached."
                " Validation aborted.",
            },
        ],
    }]

    response = encode_execution_results(results)
    assert response.status_code == 400
Пример #4
0
def test_encode_execution_results_with_pretty():
    execution_results = [ExecutionResult({"test": "Hello World"}, None)]

    output = encode_execution_results(execution_results,
                                      encode=json_encode_pretty)
    body = output.body
    assert body == "{\n" '  "data": {\n' '    "test": "Hello World"\n' "  }\n" "}"
Пример #5
0
def test_encode_execution_results_with_batch_and_empty_result():
    execution_results = [
        ExecutionResult({"result": 1}, None),
        None,
        ExecutionResult({"result": 3}, None),
    ]

    output = encode_execution_results(execution_results, is_batch=True)
    assert isinstance(output, ServerResponse)
    assert isinstance(output.body, str)
    assert isinstance(output.status_code, int)
    assert json.loads(output.body) == [
        {
            "data": {
                "result": 1
            }
        },
        None,
        {
            "data": {
                "result": 3
            }
        },
    ]
    assert output.status_code == 200
Пример #6
0
def test_encode_execution_results_with_error():
    execution_results = [
        ExecutionResult(
            None,
            [
                GraphQLError("Some error",
                             locations=[SourceLocation(1, 2)],
                             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) == {
        "data":
        None,
        "errors": [{
            "message": "Some error",
            "locations": [{
                "line": 1,
                "column": 2
            }],
            "path": ["somePath"],
        }],
    }
    assert output.status_code == 200
Пример #7
0
def test_reports_validation_errors():
    results, params = run_http_query(
        schema,
        "get", {},
        query_data=dict(query="{ test, unknownOne, unknownTwo }"))

    assert as_dicts(results) == [{
        "data":
        None,
        "errors": [
            {
                "message":
                "Cannot query field 'unknownOne' on type 'QueryRoot'.",
                "locations": [{
                    "line": 1,
                    "column": 9
                }],
                "path": None,
            },
            {
                "message":
                "Cannot query field 'unknownTwo' on type 'QueryRoot'.",
                "locations": [{
                    "line": 1,
                    "column": 21
                }],
                "path": None,
            },
        ],
    }]

    response = encode_execution_results(results)
    assert response.status_code == 400
Пример #8
0
    def dispatch_request(self):
        try:
            request_method = request.method.lower()
            data = self.parse_body()

            show_graphiql = request_method == 'get' and self.should_display_graphiql()
            catch = show_graphiql

            pretty = self.pretty or show_graphiql or request.args.get('pretty')

            extra_options = {}
            executor = self.get_executor()
            if executor:
                # We only include it optionally since
                # executor is not a valid argument in all backends
                extra_options['executor'] = executor

            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.args,
                batch_enabled=self.batch,
                catch=catch,
                backend=self.get_backend(),

                # Execute options
                root=self.get_root_value(),
                context=self.get_context(),
                middleware=self.get_middleware(),
                **extra_options
            )
            result, status_code = encode_execution_results(
                execution_results,
                is_batch=isinstance(data, list),
                format_error=self.format_error,
                encode=partial(self.encode, pretty=pretty)
            )

            if show_graphiql:
                return self.render_graphiql(
                    params=all_params[0],
                    result=result
                )

            return Response(
                result,
                status=status_code,
                content_type='application/json'
            )

        except HttpQueryError as e:
            return Response(
                self.encode({
                    'errors': [self.format_error(e)]
                }),
                status=e.status_code,
                headers=e.headers,
                content_type='application/json'
            )
Пример #9
0
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
Пример #10
0
    def dispatch_request(self):
        try:
            request_method = request.method.lower()
            data = self.parse_body()

            show_graphiql = request_method == "get" and self.should_display_graphiql()
            catch = show_graphiql

            pretty = self.pretty or show_graphiql or request.args.get("pretty")

            all_params: List[GraphQLParams]
            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.args,
                batch_enabled=self.batch,
                catch=catch,
                # Execute options
                root_value=self.get_root_value(),
                context_value=self.get_context_value(),
                middleware=self.get_middleware(),
            )
            result, status_code = encode_execution_results(
                execution_results,
                is_batch=isinstance(data, list),
                format_error=self.format_error,
                encode=partial(self.encode, pretty=pretty),  # noqa
            )

            if show_graphiql:
                graphiql_data = GraphiQLData(
                    result=result,
                    query=getattr(all_params[0], "query"),
                    variables=getattr(all_params[0], "variables"),
                    operation_name=getattr(all_params[0], "operation_name"),
                    subscription_url=self.subscriptions,
                    headers=self.headers,
                )
                graphiql_config = GraphiQLConfig(
                    graphiql_version=self.graphiql_version,
                    graphiql_template=self.graphiql_template,
                    graphiql_html_title=self.graphiql_html_title,
                    jinja_env=None,
                )
                source = render_graphiql_sync(
                    data=graphiql_data, config=graphiql_config
                )
                return render_template_string(source)

            return Response(result, status=status_code, content_type="application/json")

        except HttpQueryError as e:
            parsed_error = GraphQLError(e.message)
            return Response(
                self.encode(dict(errors=[self.format_error(parsed_error)])),
                status=e.status_code,
                headers=e.headers,
                content_type="application/json",
            )
Пример #11
0
def graphql(event, context):
    """
    Handles the graphql event.
    """
    logger.debug('Event Received: graphql: {}'.format(json.dumps(event)))

    body = json.loads(event['body'])

    # Execute the GraphQL query.
    execution_results, _ = run_http_query(schema.root(), 'post', body)

    # Get the results and status code for the response.
    result, status_code = encode_execution_results(execution_results,
                                                   default_format_error, False,
                                                   lambda o: o)

    # Build the response with the status code and GraphQL results.
    response = {
        'statusCode': status_code,
        'headers': {
            'Access-Control-Allow-Origin': "*",
            'Access-Control-Allow-Credentials': 'true'
        },
        'body': json.dumps(result)
    }

    logger.debug('Event Response: graphql: {}'.format(json.dumps(response)))

    return response
Пример #12
0
    async def __call__(self, request):
        try:
            data = await self.parse_body(request)
            request_method = request.method.lower()
            is_graphiql = self.is_graphiql(request)
            is_pretty = self.is_pretty(request)

            if request_method == 'options':
                return self.process_preflight(request)

            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.query,
                batch_enabled=self.batch,
                catch=is_graphiql,
                # Execute options
                return_promise=self.enable_async,
                root_value=self.root_value,
                context_value=self.get_context(request),
                middleware=self.middleware,
                executor=self.executor,
                backend=self.backend,
            )

            awaited_execution_results = await Promise.all(execution_results)
            result, status_code = encode_execution_results(
                awaited_execution_results,
                is_batch=isinstance(data, list),
                format_error=self.error_formatter,
                encode=partial(self.encoder, pretty=is_pretty),
            )

            if is_graphiql:
                return await self.render_graphiql(
                    params=all_params[0],
                    result=result,
                )

            return web.Response(
                text=result,
                status=status_code,
                content_type='application/json',
            )

        except HttpQueryError as err:
            if err.headers and 'Allow' in err.headers:
                # bug in graphql_server.execute_graphql_request
                # https://github.com/graphql-python/graphql-server-core/pull/4
                if isinstance(err.headers['Allow'], list):
                    err.headers['Allow'] = ', '.join(err.headers['Allow'])

            return web.Response(
                text=self.encoder({'errors': [self.error_formatter(err)]}),
                status=err.status_code,
                headers=err.headers,
                content_type='application/json',
            )
Пример #13
0
    async def __call__(self, request):
        try:
            data = await self.parse_body(request)
            request_method = request.method.lower()
            is_graphiql = self.is_graphiql(request)
            is_pretty = self.is_pretty(request)

            if request_method == "options":
                return self.process_preflight(request)

            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.query,
                batch_enabled=self.batch,
                catch=is_graphiql,
                # Execute options
                return_promise=self.enable_async,
                root_value=self.root_value,
                context_value=self.get_context(request),
                middleware=self.middleware,
                executor=self.executor,
                **self.execution_options,
            )

            if is_graphiql and self.enable_async:
                # catch errors like run_http_query does when async
                execution_results = [
                    result.catch(lambda value: None)
                    for result in execution_results
                ]
            awaited_execution_results = await Promise.all(execution_results)
            result, status_code = encode_execution_results(
                awaited_execution_results,
                is_batch=isinstance(data, list),
                format_error=self.error_formatter,
                encode=partial(self.encoder, pretty=is_pretty),
            )

            if is_graphiql:
                return await self.render_graphiql(
                    params=all_params[0],
                    result=result,
                )

            return web.Response(
                text=result,
                status=status_code,
                content_type="application/json",
            )

        except HttpQueryError as err:
            return web.Response(
                text=self.encoder({"errors": [self.error_formatter(err)]}),
                status=err.status_code,
                headers=err.headers,
                content_type="application/json",
            )
Пример #14
0
    async def __call__(self, request):
        try:
            data = await self.parse_body(request)
            request_method = request.method.lower()
            is_graphiql = self.is_graphiql(request)

            if request_method == 'options':
                return self.process_preflight(request)

            is_pretty = self.is_pretty(request)

            if request_method == 'options':
                return self.process_preflight(request)

            try:
                out = await request.json()
            except:
                out = {}
            results, params = await run_query(self.schema, data, request.query,
                                              out.get("operationName"))

            result, status_code = encode_execution_results(
                results,
                is_batch=isinstance(data, list),
                format_error=self.error_formatter,
                encode=partial(json_encode, pretty=is_pretty),
            )

            if is_graphiql and params[0].query is not None:
                return await self.render_graphiql(
                    params=params[0],
                    result=result,
                )
            elif is_graphiql and params[0].query is None:
                return await self.render_graphiql(
                    params=params[0],
                    result=None,
                )

            return web.Response(
                text=result,
                status=status_code,
                content_type='application/json',
            )

        except HttpQueryError as err:
            if err.headers and 'Allow' in err.headers:
                # bug in graphql_server.execute_graphql_request
                # https://github.com/graphql-python/graphql-server-core/pull/4
                if isinstance(err.headers['Allow'], list):
                    err.headers['Allow'] = ', '.join(err.headers['Allow'])

            return web.Response(
                text=json_encode({'errors': [self.error_formatter(err)]}),
                status=err.status_code,
                headers=err.headers,
                content_type='application/json',
            )
Пример #15
0
def test_encode_execution_results_with_empty_result():
    execution_results = [None]

    output = encode_execution_results(execution_results)
    assert isinstance(output, ServerResponse)
    assert isinstance(output.body, str)
    assert isinstance(output.status_code, int)
    assert output.body == "null"
    assert output.status_code == 200
Пример #16
0
def test_encode_execution_results_batch():
    data = {"answer": 42}
    errors = [GraphQLError("bad")]
    results = [ExecutionResult(data, None), ExecutionResult(None, errors)]
    result = encode_execution_results(results, is_batch=True)
    assert result == (
        '[{"data":{"answer":42}},{"errors":[{"message":"bad"}]}]',
        400,
    )
Пример #17
0
 def query(self, request):
     data = self.parse_body(request)
     execution_results, params = run_http_query(schema, 'post', data)
     result, status_code = encode_execution_results(
         execution_results,
         format_error=default_format_error,
         is_batch=False,
         encode=json_encode)
     return result
Пример #18
0
    async def dispatch_request(self, request, *args, **kwargs):
        try:
            request_method = request.method.lower()
            data = self.parse_body(request)

            show_graphiql = request_method == 'get' and self.should_display_graphiql(
                request)
            catch = show_graphiql

            pretty = self.pretty or show_graphiql or request.args.get('pretty')

            if request_method != 'options':
                execution_results, all_params = run_http_query(
                    self.schema,
                    request_method,
                    data,
                    query_data=request.args,
                    batch_enabled=self.batch,
                    catch=catch,

                    # Execute options
                    return_promise=self._enable_async,
                    root_value=self.get_root_value(request),
                    context_value=self.get_context(request),
                    middleware=self.get_middleware(request),
                    executor=self.get_executor(request),
                )
                awaited_execution_results = await Promise.all(execution_results
                                                              )
                result, status_code = encode_execution_results(
                    awaited_execution_results,
                    is_batch=isinstance(data, list),
                    format_error=partial(self._format_error, request),
                    encode=partial(self.encode, pretty=pretty))

                if show_graphiql:
                    return await self.render_graphiql(params=all_params[0],
                                                      result=result)

                return HTTPResponse(result,
                                    status=status_code,
                                    content_type='application/json')

            else:
                return self.process_preflight(request)

        except HttpQueryError as e:
            _log.exception(GraphQLView.dispatch_request.__name__)

            return HTTPResponse(self.encode(
                {'errors': [self._format_error(request, e)]}),
                                status=e.status_code,
                                headers=e.headers,
                                content_type='application/json')
Пример #19
0
 def graphql_response(self, req, resp, schema):
     query = self._resolve_graphql_query(req)
     result = schema.execute(query)
     result, status_code = encode_execution_results(
         [result],
         is_batch=False,
         format_error=default_format_error,
         encode=partial(json_encode, pretty=False),
     )
     resp.media = json.loads(result)
     return (query, result, status_code)
Пример #20
0
def test_encode_execution_results_with_encode():
    execution_results = [ExecutionResult({"result": None}, None)]

    def encode(result):
        return repr(dict(result))

    output = encode_execution_results(execution_results, encode=encode)
    assert isinstance(output, ServerResponse)
    assert isinstance(output.body, str)
    assert isinstance(output.status_code, int)
    assert output.body == "{'data': {'result': None}}"
    assert output.status_code == 200
Пример #21
0
    def dispatch_request(self):
        try:
            request_method = request.method.lower()
            data = self.parse_body()

            show_graphiql = request_method == 'get' and self.should_display_graphiql()
            catch = show_graphiql

            pretty = self.pretty or show_graphiql or request.args.get('pretty')

            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.args,
                batch_enabled=self.batch,
                catch=catch,

                # Execute options
                root_value=self.get_root_value(),
                context_value=self.get_context(),
                middleware=self.get_middleware(),
                executor=self.get_executor(),
            )
            result, status_code = encode_execution_results(
                execution_results,
                is_batch=isinstance(data, list),
                format_error=self.format_error,
                encode=partial(self.encode, pretty=pretty)
            )

            if show_graphiql:
                return self.render_graphiql(
                    params=all_params[0],
                    result=result
                )

            return Response(
                result,
                status=status_code,
                content_type='application/json'
            )

        except HttpQueryError as e:
            return Response(
                self.encode({
                    'errors': [self.format_error(e)]
                }),
                status=e.status_code,
                headers=e.headers,
                content_type='application/json'
            )
Пример #22
0
 def query(self, request):
     logger.info("begin-query")
     data = self.parse_body(request)
     logger.info("query", request=request)
     execution_results, params = run_http_query(schema, 'post', data)
     result, status_code = encode_execution_results(
         execution_results,
         format_error=default_format_error,
         is_batch=False,
         encode=json_encode)
     logger.info("query", result=result, status_code=status_code)
     logger.info("end-query")
     return result
Пример #23
0
def test_handles_field_errors_caught_by_graphql():
    results, params = run_http_query(schema,
                                     "get",
                                     data=dict(query="{thrower}"))

    assert results == [(None, [{
        "message": "Throws!",
        "locations": [(1, 2)],
        "path": ["thrower"]
    }])]

    response = encode_execution_results(results)
    assert response.status_code == 200
Пример #24
0
def test_encode_execution_results_without_error():
    execution_results = [
        ExecutionResult({"result": 1}, None),
        ExecutionResult({"result": 2}, None),
        ExecutionResult({"result": 3}, 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) == {"data": {"result": 1}}
    assert output.status_code == 200
Пример #25
0
    async def dispatch_request(self):
        try:
            request_method = request.method.lower()
            data = await self.parse_body()

            show_graphiql = request_method == "get" and self.should_display_graphiql(
            )
            catch = show_graphiql

            pretty = self.pretty or show_graphiql or request.args.get("pretty")

            extra_options = {}
            executor = self.get_executor()
            if executor:
                extra_options["executor"] = executor

            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.args,
                batch_enabled=self.batch,
                catch=catch,
                backend=self.get_backend(),
                # Execute options
                root=self.get_root_value(),
                context=self.get_context(),
                middleware=self.get_middleware(),
                **extra_options)
            result, status_code = encode_execution_results(
                execution_results,
                is_batch=isinstance(data, list),
                format_error=self.format_error,
                encode=partial(self.encode, pretty=pretty),
            )

            if show_graphiql:
                return await self.render_graphiql(params=all_params[0],
                                                  result=result)

            return Response(result,
                            status=status_code,
                            content_type="application/json")

        except HttpQueryError as e:
            return Response(
                self.encode({"errors": [self.format_error(e)]}),
                status=e.status_code,
                headers=e.headers,
                content_type="application/json",
            )
Пример #26
0
    async def graphql_response(self, req, resp, schema):
        show_graphiql = req.method == "get" and req.accepts("text/html")

        if show_graphiql:
            resp.content = self.template_string(GRAPHIQL, endpoint=req.url.path)
            return

        query, variables, operation_name = await self._resolve_graphql_query(req)
        result = schema.execute(query, variables=variables, operation_name=operation_name)
        result, status_code = encode_execution_results(
            [result],
            is_batch=False,
            format_error=default_format_error,
            encode=partial(json_encode, pretty=False),
        )
        resp.media = json.loads(result)
        return (query, result, status_code)
Пример #27
0
    async def graphql_response(self, req, resp, schema):
        show_graphiql = req.method.lower() == 'get' and req.accepts('text/html')

        if show_graphiql:
            resp.content = self.template('graphiql.html', endpoint=req.url.path)
            return

        query = await self._resolve_graphql_query(req)
        result = schema.execute(query)
        result, status_code = encode_execution_results(
            [result],
            is_batch=False,
            format_error=default_format_error,
            encode=partial(json_encode, pretty=False),
        )
        resp.media = json.loads(result)
        return (query, result, status_code)
Пример #28
0
    def dispatch_request(self):
        try:
            request_method = request.method.lower()
            data = self.parse_body()

            show_graphiql = request_method == 'get' and self.should_display_graphiql(
            )
            catch = HttpQueryError if show_graphiql else None

            pretty = self.pretty or show_graphiql or request.args.get('pretty')

            execution_results, all_params = run_http_query(
                self.schema,
                request_method,
                data,
                query_data=request.args,
                batch_enabled=self.batch,
                catch=catch,

                # Execute options
                root_value=self.get_root_value(),
                context_value=self.get_context(),
                middleware=self.get_middleware(),
                executor=self.get_executor(),
            )
            result, status_code = encode_execution_results(
                execution_results,
                is_batch=isinstance(data, list),
                format_error=self.format_error,
                encode=partial(self.encode, pretty=pretty))

            if show_graphiql:
                return self.render_graphiql(params=all_params[0],
                                            result=result)

            return Response(status=status_code,
                            response=result,
                            content_type='application/json')

        except HttpQueryError as e:
            return Response(self.encode({'errors': [self.format_error(e)]}),
                            status=e.status_code,
                            headers=e.headers,
                            content_type='application/json')
Пример #29
0
def test_encode_execution_results_with_batch_and_error():
    execution_results = [
        ExecutionResult({"result": 1}, None),
        ExecutionResult(
            None,
            [
                GraphQLError("No data here",
                             locations=[SourceLocation(1, 2)],
                             path=["somePath"])
            ],
        ),
        ExecutionResult({"result": 3}, None),
    ]

    output = encode_execution_results(execution_results, is_batch=True)
    assert isinstance(output, ServerResponse)
    assert isinstance(output.body, str)
    assert isinstance(output.status_code, int)
    assert json.loads(output.body) == [
        {
            "data": {
                "result": 1
            }
        },
        {
            "data":
            None,
            "errors": [{
                "message": "No data here",
                "locations": [{
                    "line": 1,
                    "column": 2
                }],
                "path": ["somePath"],
            }],
        },
        {
            "data": {
                "result": 3
            }
        },
    ]
    assert output.status_code == 200
Пример #30
0
        def view_func():
            variable_values = self.get_variable_values()

            field_selection_set = self._get_field_selection_set(
                field, include_node=True)

            if hasattr(field.type, 'graphene_type') and issubclass(
                    field.type.graphene_type, Node):
                _type_name, _id = Node.from_global_id(variable_values['id'])
                node_type = schema.get_type(_type_name)
                inline_selection = graphql_ast.InlineFragment(
                    type_condition=graphql_ast.NamedType(name=graphql_ast.Name(
                        value=_type_name)),
                    selection_set=self._get_field_selection_set(
                        GraphQLField(node_type), include_node=True))
                field_selection_set.selections.append(inline_selection)

            document_ast = graphql_ast.Document([
                graphql_ast.OperationDefinition(
                    operation=operation,
                    variable_definitions=variable_definitions,
                    selection_set=graphql_ast.SelectionSet(selections=[
                        graphql_ast.Field(name=graphql_ast.Name(
                            value=field_name),
                                          arguments=arguments,
                                          selection_set=field_selection_set)
                    ]))
            ])

            execution_results = schema.execute(document_ast,
                                               variable_values=variable_values)

            # TODO custom encoder that positions data[field_name] at data
            result, status_code = encode_execution_results(
                [execution_results],
                is_batch=False,
                format_error=default_format_error,
                encode=json_encode)

            return Response(result,
                            status=status_code,
                            content_type='application/json')
Пример #31
0
def graphql():
    request_method = request.method.lower()
    if request_method == 'get':
        return render_template(
            'graphiql.html',
            graphiql_version="0.11.11",
            graphiql_html_title="Cyber GraphiQL",
        )

    # token = requestHandler(request)
    token = {'permission': ['view:*']}

    data = load_json_body(request.data.decode())

    pretty = request.args.get('pretty')
    context = {'token': token}

    execution_results, _ = run_http_query(
        schema,
        request_method,
        data,
        query_data=request.args,
        batch_enabled=False,
        catch=False,
        backend=None,

        # Execute options
        root=None,
        context=context,
        middleware=None,
    )

    result, status_code = encode_execution_results(
        execution_results,
        is_batch=False,
        format_error=default_format_error,
        encode=partial(json_encode, pretty=pretty))

    return Response(result,
                    status=status_code,
                    content_type='application/json')