コード例 #1
0
ファイル: utils_schema.py プロジェクト: ekampf/gql
def load_introspection_from_server(url):
    query = get_introspection_query()
    request = requests.post(url, json={'query': query})
    if request.status_code == 200:
        return request.json()['data']

    raise Exception(f'Query failed to run by returning code of {request.status_code}. {query}')
コード例 #2
0
ファイル: app.py プロジェクト: Ambro17/pyconar-graphql
def create_app():
    app = Flask(__name__, static_folder='static')

    # Serve Graphiql IDE at /
    graphiql = GraphQLAPI.as_view("graphiql",
                                  schema=schema,
                                  use_playground=False)
    app.add_url_rule("/", view_func=graphiql)

    # Serve Graphiql IDE at /dark
    graphiql = GraphQLAPI.as_view("playground",
                                  schema=schema,
                                  use_playground=True)
    app.add_url_rule("/dark", view_func=graphiql)

    # Serve Explorer at /explorer
    introspection = schema.execute_sync(get_introspection_query())
    explorer = APIExplorer.as_view("voyager",
                                   introspection=json.dumps(
                                       {'data': introspection.data}))
    app.add_url_rule("/explorer", view_func=explorer)

    # Handle database connections per request
    @app.before_request
    def before_request():
        db.connect()

    @app.after_request
    def after_request(response):
        db.close()
        return response

    return app
コード例 #3
0
def make_remote_executable_schema(url: str) -> graphql.GraphQLSchema:
    """
    Creates an executable GraphQL schema from a remote endpoint.
    """
    client = GraphQLClient(url=url)

    introspection_result = client.execute(graphql.get_introspection_query())
    schema = graphql.build_client_schema(introspection_result.data)

    def root_resolver(obj, info, **inputs):
        query = graphql.print_ast(info.operation)
        # TODO: add graphql context
        delegated_result = client.execute(query=query,
                                          variables=info.variable_values)
        return delegated_result.data[info.field_name]

    # apply root resolver to any field on query or mutation roots
    resolvers = {
        schema.query_type.name:
        {q: root_resolver
         for q in schema.query_type.fields},
        schema.mutation_type.name:
        {q: root_resolver
         for q in schema.mutation_type.fields},
    }

    ariadne.resolvers.add_resolve_functions_to_schema(schema, resolvers)

    return schema
コード例 #4
0
ファイル: client.py プロジェクト: stjordanis/magma-1
    def __init__(
        self,
        schema: Optional[GraphQLSchema] = None,
        introspection: Optional[Dict[str, Any]] = None,
        type_def: Optional[str] = None,
        transport: Optional[Transport] = None,
        fetch_schema_from_transport: bool = False,
        retries: int = 0,
    ) -> None:
        assert not (
            type_def and introspection
        ), "Cant provide introspection type definition at the same time"
        if transport and fetch_schema_from_transport:
            assert (
                not schema
            ), "Cant fetch the schema from transport if is already provided"
            introspection = transport.execute(
                parse(get_introspection_query(descriptions=True))).data
        if introspection:
            assert not schema, "Cant provide introspection and schema at the same time"
            schema = build_client_schema(introspection)
        elif type_def:
            assert (
                not schema
            ), "Cant provide Type definition and schema at the same time"
            type_def_ast = parse(type_def)
            schema = build_ast_schema(type_def_ast)
        elif schema and not transport:
            transport = LocalSchemaTransport(schema)

        self.schema = schema
        self.introspection = introspection
        self.transport = cast(Transport, transport)
        self.retries = retries
コード例 #5
0
ファイル: utils_schema.py プロジェクト: snwfdhmp/magma
def load_introspection_from_server(url):
    query = get_introspection_query()
    request = requests.post(url, json={'query': query})
    if request.status_code == 200:
        return request.json()['data']

    raise Exception('Query failed to run by returning code of '
        f'{request.status_code}. {query}')
コード例 #6
0
 async def schema(self):
     return await fetch(
         self.url,
         headers={
             'Accept': 'application/json',
             'Content-Type': 'application/json',
         },
         params={'query': get_introspection_query(descriptions=False)})
コード例 #7
0
ファイル: client.py プロジェクト: cipriantarta/typegql
 async def introspection(self):
     status, result = await self.execute(get_introspection_query())
     if status != 200:
         raise ValueError(
             f"Error in schema introspection. {status} - {result}")
     schema = build_client_schema(result.data)
     self.dsl = DSLSchema(schema, camelcase=self.camelcase)
     return schema
コード例 #8
0
    def fetch_schema(self) -> None:
        """Fetch the GraphQL schema explicitely using introspection.

        Don't use this function and instead set the fetch_schema_from_transport
        attribute to True"""
        execution_result = self.transport.execute(parse(get_introspection_query()))

        self.client._build_schema_from_introspection(execution_result)
コード例 #9
0
def load_introspection_from_server(url):
    query = get_introspection_query()
    request = requests.post(url, json={"query": query})
    if request.status_code == 200:
        return request.json()["data"]

    raise Exception(
        f"Request failure with {request.status_code} status code for query {query}"
    )
コード例 #10
0
def main():
    pp = PrettyPrinter(indent=4)
    client = GraphQLClient('http://swapi.graph.cool/')
    query_intros = get_introspection_query(descriptions=True)
    intros_result = client.execute(query_intros,
                                   variables=None,
                                   operationName=None)
    client_schema = build_client_schema(intros_result.get('data', None))
    sdl = print_schema(client_schema)
    print(sdl)
    pp.pprint(sdl)
コード例 #11
0
    def introspect(self) -> Dict[str, Any]:
        """Return the introspection query result for the current schema

        Raises:
            ValueError: If the introspection query fails due to an invalid schema
        """
        introspection = self.execute_sync(get_introspection_query())
        if introspection.errors or not introspection.data:
            raise ValueError(f"Invalid Schema. Errors {introspection.errors!r}")

        return introspection.data
コード例 #12
0
    def handle(self, *args, **options):
        query = get_introspection_query(descriptions=False)
        result = graphql_sync(schema, query)

        output = {"data": result.data}

        with open("schema.json", "w") as f:
            json.dump(output, f, indent=4, sort_keys=True)

        self.stdout.write(
            self.style.SUCCESS(
                "Successfully dumped GraphQL schema to schema.json"))
コード例 #13
0
def test_executable_schema_can_be_introspected():
    schema = make_executable_schema(type_defs)
    introspection_query = get_introspection_query(descriptions=True)
    result = graphql_sync(schema, introspection_query)
    assert result.errors is None
    assert result.data is not None
    assert "__schema" in result.data
    type_names = [
        schema_type["name"] for schema_type in result.data["__schema"]["types"]
    ]
    assert "User" in type_names
    assert "Query" in type_names
    assert "Date" in type_names
コード例 #14
0
def query_for_schema(provider):
    """
    Asks the given provider for its schema
    """
    prov = get_provider(provider)
    if hasattr(prov, 'get_schema_str'):
        data = prov.get_schema_str()
        schema = graphql.build_schema(data)
    else:
        query = graphql.get_introspection_query(descriptions=True)

        data = exec_query_sync(provider, query)
        schema = graphql.build_client_schema(data)
    schema = insert_builtins(schema)
    return schema
コード例 #15
0
ファイル: schemas.py プロジェクト: danpalmer/graphql-validate
def _resolve_url(ctx, url: str) -> Optional[GraphQLSchema]:
    query = get_introspection_query(descriptions=True)

    try:
        response = requests.post(url,
                                 data={"query": query},
                                 headers={"Accept": "application/json"})
        response.raise_for_status()
    except requests.RequestException:
        raise ValueError("Could not download schema")

    try:
        data = response.json()
    except json.decoder.JSONDecodeError:
        raise ValueError("Received invalid JSON from GraphQL endpoint")

    try:
        return build_client_schema(data["data"])
    except Exception:
        raise ValueError("Could not decode schema")
コード例 #16
0
    def initialize(self):
        loop = tornado.ioloop.IOLoop.current()

        generate_schema()
        api_schema = get_api_schema()
        module_schema = get_module_schema()

        if options.generate_schema_and_exit:
            query = get_introspection_query(descriptions=False)
            introspection_query_result = graphql_sync(api_schema, query)
            client_schema = build_client_schema(introspection_query_result.data)
            sdl = print_schema(client_schema)

            with open(
                Path(options.basedir).joinpath("..", "schema.graphql").resolve(), "w+"
            ) as fid:
                fid.write(sdl)
            sys.exit(0)

        start_all_modules()
        self.database = None  # MavDatabase()

        application = TornadoQL()

        # Start Non-SSL server
        server = tornado.httpserver.HTTPServer(application)
        server.listen(port=options.server_port_nonssl, address=options.server_interface)
        application_log.info(
            f"Starting Maverick API server: {options.server_interface}:{options.server_port_nonssl}/{options.app_prefix}"
        )

        # Start SSL server, unless disabled
        if not options.disable_ssl:
            ssl_options = self.get_ssl_options()
            server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options)
            server.listen(
                port=options.server_port_ssl, address=options.server_interface
            )
            application_log.info(
                f"Starting Maverick API server - SSL: {options.server_interface}:{options.server_port_ssl}/{options.app_prefix}"
            )
コード例 #17
0
    async def introspect(
        self, headers: Optional[Dict[str, str]] = None
    ) -> graphql.GraphQLSchema:
        """
        Introspect the GraphQL endpoint specified for this client and return a `graphql.GraphQLSchema` object
        specifying the schema associated with this endpoint.

        :return: GraphQL schema for the configured endpoint
        """
        request = GraphQLRequest(
            query=graphql.get_introspection_query(descriptions=False),
            validate=False,
            headers=headers,
        )
        introspection = await self.query(request)
        try:
            return graphql.build_client_schema(introspection=introspection.data)
        except TypeError:
            raise GraphQLIntrospectionException(
                f"Failed to build schema from introspection data: {introspection.errors}"
            )
コード例 #18
0
def main():
    pp = PrettyPrinter(indent=4)

    # query over the network
    query_intros = get_introspection_query(descriptions=True)
    #introspection_query_result = graphql_sync(schema, query)
    intros_result = client.execute(query_intros,
                                   variables=None,
                                   operationName=None)
    client_schema = build_client_schema(intros_result.get('data', None))
    sdl = print_schema(client_schema)
    print(sdl)
    pp.pprint(sdl)
    print("\n")

    # query again using the graphql_sync()
    from graphql import graphql_sync
    introspection_query_result = graphql_sync(client_schema, query_intros)
    client_schema = build_client_schema(introspection_query_result.data)
    sdl = print_schema(client_schema)
    print(sdl)
    pp.pprint(sdl)
    print("\n")
コード例 #19
0
def introspection_query():
    return get_introspection_query()
コード例 #20
0
ファイル: schema.py プロジェクト: zsiciarz/graphene
    GrapheneScalarType,
    GrapheneUnionType,
)
from .dynamic import Dynamic
from .enum import Enum
from .field import Field
from .inputobjecttype import InputObjectType
from .interface import Interface
from .objecttype import ObjectType
from .resolver import get_default_resolver
from .scalars import ID, Boolean, Float, Int, Scalar, String
from .structures import List, NonNull
from .union import Union
from .utils import get_field_as

introspection_query = get_introspection_query()
IntrospectionSchema = introspection_types["__Schema"]


def assert_valid_root_type(type_):
    if type_ is None:
        return
    is_graphene_objecttype = inspect.isclass(type_) and issubclass(
        type_, ObjectType)
    is_graphql_objecttype = isinstance(type_, GraphQLObjectType)
    assert is_graphene_objecttype or is_graphql_objecttype, (
        "Type {} is not a valid ObjectType.").format(type_)


def is_graphene_type(type_):
    if isinstance(type_, (List, NonNull)):
コード例 #21
0
def test_should_ignore_the_introspection_query():
    errors, result = run_query(get_introspection_query(), 10)
    assert not errors
    assert result == {"IntrospectionQuery": 0}
コード例 #22
0
def test_opentracing_extension_doesnt_break_introspection(schema):
    introspection_query = get_introspection_query(descriptions=True)
    _, result = graphql(schema, {"query": introspection_query},
                        extensions=[OpenTracingExtension])
    assert "errors" not in result
コード例 #23
0
ファイル: loaders.py プロジェクト: schemathesis/schemathesis
import graphql
import requests
from graphql import ExecutionResult
from starlette.applications import Starlette
from starlette.testclient import TestClient as ASGIClient
from werkzeug import Client
from yarl import URL

from ...constants import DEFAULT_DATA_GENERATION_METHODS, CodeSampleStyle
from ...exceptions import HTTPError
from ...hooks import HookContext, dispatch
from ...types import DataGenerationMethodInput, PathLike
from ...utils import WSGIResponse, prepare_data_generation_methods, require_relative_url, setup_headers
from .schemas import GraphQLSchema

INTROSPECTION_QUERY = graphql.get_introspection_query()
INTROSPECTION_QUERY_AST = graphql.parse(INTROSPECTION_QUERY)


def from_path(
    path: PathLike,
    *,
    app: Any = None,
    base_url: Optional[str] = None,
    data_generation_methods: DataGenerationMethodInput = DEFAULT_DATA_GENERATION_METHODS,
    code_sample_style: str = CodeSampleStyle.default().name,
    encoding: str = "utf8",
) -> GraphQLSchema:
    """Load GraphQL schema via a file from an OS path.

    :param path: A path to the schema file.
コード例 #24
0
ファイル: test_introspection.py プロジェクト: zhutony/ariadne
def test_executable_schema_can_be_introspected(snapshot):
    schema = make_executable_schema(type_defs)
    introspection_query = get_introspection_query(descriptions=True)
    result = graphql_sync(schema, introspection_query)
    assert result.errors is None
    snapshot.assert_match(result.data)
コード例 #25
0
ファイル: client.py プロジェクト: acatinon/gql
 async def fetch_schema(self) -> None:
     execution_result = await self.transport.execute(
         parse(get_introspection_query())
     )
     self.client.introspection = execution_result.data
     self.client.schema = build_client_schema(self.client.introspection)
コード例 #26
0
subscription_type = GraphQLObjectType(
    "Subscription",
    lambda: {
        "reviewAdded": GraphQLField(
            review_type,
            args={
                "episode": GraphQLArgument(
                    episode_enum,
                    description="Episode to review",
                )
            },
            subscribe=subscribe_reviews,
            resolve=resolve_review,
        )
    },
)


StarWarsSchema = GraphQLSchema(
    query=query_type,
    mutation=mutation_type,
    subscription=subscription_type,
    types=[human_type, droid_type, review_type, review_input_type],
)


StarWarsIntrospection = graphql_sync(StarWarsSchema, get_introspection_query()).data

StarWarsTypeDef = print_schema(StarWarsSchema)
コード例 #27
0
ファイル: schema.py プロジェクト: vikramarunBT/gql
subscriptionType = GraphQLObjectType(
    "Subscription",
    fields=lambda: {
        "reviewAdded":
        GraphQLField(
            reviewType,
            args={
                "episode":
                GraphQLArgument(
                    description="Episode to review",
                    type_=episodeEnum,
                )
            },
            subscribe=subscribe_reviews,
            resolve=resolve_review,
        )
    },
)

StarWarsSchema = GraphQLSchema(
    query=queryType,
    mutation=mutationType,
    subscription=subscriptionType,
    types=[humanType, droidType, reviewType, reviewInputType],
)

StarWarsIntrospection = graphql_sync(StarWarsSchema,
                                     get_introspection_query()).data

StarWarsTypeDef = print_schema(StarWarsSchema)
コード例 #28
0
async def test_apollotracing_extension_doesnt_break_introspection(schema):
    introspection_query = get_introspection_query(descriptions=True)
    _, result = await graphql(schema, {"query": introspection_query},
                              extensions=[ApolloTracingExtension])
    assert "errors" not in result
コード例 #29
0
 async def get(self):
     query = get_introspection_query(descriptions=True)
     introspection_query_result = await graphql(api_schema, query)
     introspection_dict = introspection_query_result.data
     self.write(json.dumps(introspection_dict, indent=4, sort_keys=True))
     self.finish()