Exemple #1
0
    def __init__(self,
                 schema=None,
                 introspection=None,
                 type_def=None,
                 transport=None,
                 fetch_schema_from_transport=False,
                 retries=0,
                 custom_types={}):
        """custom_types should be of type Dict[str, Any]
                    where str is the name of the custom scalar type, and
                          Any is a class which has a `parse_value()` function"""
        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(introspection_query)).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 = transport
        self.retries = retries
        self.type_adapter = TypeAdapter(schema,
                                        custom_types) if custom_types else None
Exemple #2
0
    def __init__(
        self,
        schema: Optional[Union[str, GraphQLSchema]] = None,
        introspection=None,
        type_def: Optional[str] = None,
        transport: Optional[Union[Transport, AsyncTransport]] = None,
        fetch_schema_from_transport: bool = False,
        execute_timeout: Optional[int] = 10,
    ):
        assert not (
            type_def and introspection
        ), "Cannot provide introspection and type definition at the same time."

        if type_def:
            assert (
                not schema
            ), "Cannot provide type definition and schema at the same time."
            warnings.warn(
                "type_def is deprecated; use schema instead",
                category=DeprecationWarning,
            )
            schema = type_def

        if introspection:
            assert (
                not schema
            ), "Cannot provide introspection and schema at the same time."
            schema = build_client_schema(introspection)

        if isinstance(schema, str):
            type_def_ast = parse(schema)
            schema = build_ast_schema(type_def_ast)

        if transport and fetch_schema_from_transport:
            assert (
                not schema
            ), "Cannot fetch the schema from transport if is already provided."

        if schema and not transport:
            transport = LocalSchemaTransport(schema)

        # GraphQL schema
        self.schema: Optional[GraphQLSchema] = schema

        # Answer of the introspection query
        self.introspection = introspection

        # GraphQL transport chosen
        self.transport: Optional[Union[Transport, AsyncTransport]] = transport

        # Flag to indicate that we need to fetch the schema from the transport
        # On async transports, we fetch the schema before executing the first query
        self.fetch_schema_from_transport: bool = fetch_schema_from_transport

        # Enforced timeout of the execute function
        self.execute_timeout = execute_timeout

        if isinstance(transport, Transport) and fetch_schema_from_transport:
            with self as session:
                session.fetch_schema()
    def __init__(
        self,
        schema=None,
        introspection=None,
        type_def=None,
        transport=None,
        fetch_schema_from_transport=False,
        retries=0,
    ):
        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(introspection_query)).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 = transport
        self.retries = retries
Exemple #4
0
def test_build_schema_from_introspection(
        benchmark,
        big_schema_introspection_result  # noqa: F811
):
    schema: GraphQLSchema = benchmark(lambda: build_client_schema(
        big_schema_introspection_result["data"], assume_valid=True))
    assert schema.query_type is not None
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
Exemple #6
0
    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
Exemple #7
0
 def get_case_strategy(
         self,
         endpoint: Endpoint,
         hooks: Optional[HookDispatcher] = None,
         feedback: Optional[Feedback] = None) -> SearchStrategy:
     constructor = partial(GraphQLCase, endpoint=endpoint)
     schema = graphql.build_client_schema(self.raw_schema)
     return st.builds(constructor, body=gql_st.query(schema))
Exemple #8
0
 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
Exemple #9
0
    async 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 = await self.transport.execute(
            parse(get_introspection_query()))
        self.client.introspection = execution_result.data
        self.client.schema = build_client_schema(self.client.introspection)
Exemple #10
0
 def get_case_strategy(
     self,
     operation: APIOperation,
     hooks: Optional[HookDispatcher] = None,
     data_generation_method: DataGenerationMethod = DataGenerationMethod.default(),
 ) -> SearchStrategy:
     constructor = partial(GraphQLCase, operation=operation)
     schema = graphql.build_client_schema(self.raw_schema)
     return st.builds(constructor, body=gql_st.query(schema))
Exemple #11
0
def _cache_v4_schema():
    global _V4_SCHEMA

    if _V4_SCHEMA:
        return

    with open('github_v4_schema.graphql') as source:
        introspection = json.loads(source.read())

    _V4_SCHEMA = build_client_schema(introspection)
Exemple #12
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)
Exemple #13
0
def load_schema(schema_path):
    """Load the Intuit Schema. Apparently it differs a bit from what
    Graphene wants, specifically Graphene doesn't recognize the
    top-level "errors" and "data" fields
    """

    with open(os.path.abspath(schema_path)) as ifile:
        ischema = json.load(ifile)
    if "data" in ischema:
        ischema = ischema["data"]
    return graphql.build_client_schema(ischema)
Exemple #14
0
    def get_schema(self):
        gql_introspection_schema = self.options.get('gql_introspection_schema')
        if gql_introspection_schema:
            try:
                with open(gql_introspection_schema) as data_file:
                    introspection_schema = json.load(data_file)
                    return build_client_schema(introspection_schema)
            except IOError as e:
                raise Exception("Cannot find the provided introspection schema. {}".format(str(e)))

        schema = self.options.get('schema')
        assert schema, 'Need to provide schema'
Exemple #15
0
    def get_schema(self):
        pygql_introspection_schema = self.options.get('pygql_introspection_schema')
        if gql_introspection_schema:
            try:
                with open(pygql_introspection_schema) as data_file:
                    introspection_schema = json.load(data_file)
                    return build_client_schema(introspection_schema)
            except IOError as e:
                raise Exception("Cannot find the provided introspection schema. {}".format(str(e)))

        schema = self.options.get('schema')
        assert schema, 'Need to provide schema'
Exemple #16
0
    def convert_from_file(self, value, param, ctx):
        f = click.File('r').convert(value, param, ctx)

        try:
            introspection = json.load(f)['data']
            schema = graphql.build_client_schema(introspection)
        except (ValueError, KeyError) as e:
            self.fail('File content is not valid a graphql schema %s.' % e,
                      param=param,
                      ctx=ctx)

        return schema
Exemple #17
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")
Exemple #18
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
Exemple #19
0
def IntrospectionQuery(endpoint, filename):

    url = endpoint
    #  for headers request
    headers = {
        "User-Agent":
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:67.0) Gecko/20100101 Firefox/67.0",
        "Accept": "*/*",
        "Accept-Language": "id,en-US;q=0.7,en;q=0.3",
        "Accept-Encoding": "gzip, deflate",
        "content-type": "application/json"
    }

    # Post Request Query for grab schema IntrospectionQuery
    body = {
        "query":
        "query IntrospectionQuery {__schema {queryType { name },mutationType { name },subscriptionType { name },types {...FullType},directives {name,description,args {...InputValue},onOperation,onFragment,onField,locations}}}\nfragment FullType on __Type {kind,name,description,fields(includeDeprecated: true) {name,description,args {...InputValue},type {...TypeRef},isDeprecated,deprecationReason},inputFields {...InputValue},interfaces {...TypeRef},enumValues(includeDeprecated: true) {name,description,isDeprecated,deprecationReason},possibleTypes {...TypeRef}}\nfragment InputValue on __InputValue {name,description,type { ...TypeRef },defaultValue}\nfragment TypeRef on __Type {kind,name,ofType {kind,name,ofType {kind,name,ofType {kind,name}}}}"
    }
    data = requests.post(url, headers=headers, json=body)
    status = data.status_code

    print("\n[+] Checking endpoint ", endpoint, " .. ")
    if (status == 400):
        print("[+] IntrospectionQuery Now Allowed")

    if (status == 200):
        print("[+] IntrospectionQuery Allowed ")

        print("[+] Saving  IntrospectionQuery to folder output .. ")
        save = (json.loads(data.text))
        filename_saved = 'output/' + filename + ".json"
        with open(filename_saved, 'w') as outfile:
            json.dump(save, outfile)
        print("[+] __schema saved in ", filename_saved)

        # Convert to client schema
        instropection = json.loads(data.text)
        client_schema = build_client_schema(instropection['data'])
        _schema = print_schema(client_schema)

        print(_schema)
        print("[+] Saving  client_schema to folder output ..")

        client_schema_saved = 'output/' + filename + ".schema"
        with open(client_schema_saved, 'w') as file:
            file.write(_schema)
        print("[+] client_schema  saved in ", client_schema_saved)
Exemple #20
0
    def __init__(self, schema=None, introspection=None, type_def=None, transport=None,
                 fetch_schema_from_transport=False, retries=0):
        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(introspection_query)).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 = transport
        self.retries = retries
Exemple #21
0
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")
Exemple #22
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}"
            )
Exemple #23
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}"
            )
Exemple #24
0
    def __init__(
        self,
        schema=None,
        introspection=None,
        type_def=None,
        transport=None,
        fetch_schema_from_transport=False,
        retries=0,  # We should remove this parameter and let the transport level handle it
    ):
        assert not (
            type_def and introspection
        ), "Cannot provide introspection type definition at the same time."
        if transport and fetch_schema_from_transport:
            assert (
                not schema
            ), "Cannot fetch the schema from transport if is already provided"
            introspection = transport.execute(parse(introspection_query)).data
        if introspection:
            assert (
                not schema
            ), "Cannot provide introspection and schema at the same time."
            schema = build_client_schema(introspection)
        elif type_def:
            assert (
                not schema
            ), "Cannot 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 = transport
        self.retries = retries

        if self.retries:
            log.warning(
                "The retries parameter on the Client class is deprecated."
                "You can pass it to the RequestsHTTPTransport.")
Exemple #25
0
 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)
Exemple #26
0
    def __init__(
        self,
        schema: Optional[Union[str, GraphQLSchema]] = None,
        introspection=None,
        type_def: Optional[str] = None,
        transport: Optional[Union[Transport, AsyncTransport]] = None,
        fetch_schema_from_transport: bool = False,
        execute_timeout: Optional[int] = 10,
    ):
        """Initialize the client with the given parameters.

        :param schema: an optional GraphQL Schema for local validation
                See :ref:`schema_validation`
        :param transport: The provided :ref:`transport <Transports>`.
        :param fetch_schema_from_transport: Boolean to indicate that if we want to fetch
                the schema from the transport using an introspection query
        :param execute_timeout: The maximum time in seconds for the execution of a
                request before a TimeoutError is raised. Only used for async transports.
        """
        assert not (
            type_def and introspection
        ), "Cannot provide introspection and type definition at the same time."

        if type_def:
            assert (
                not schema
            ), "Cannot provide type definition and schema at the same time."
            warnings.warn(
                "type_def is deprecated; use schema instead",
                category=DeprecationWarning,
            )
            schema = type_def

        if introspection:
            assert (
                not schema
            ), "Cannot provide introspection and schema at the same time."
            schema = build_client_schema(introspection)

        if isinstance(schema, str):
            type_def_ast = parse(schema)
            schema = build_ast_schema(type_def_ast)

        if transport and fetch_schema_from_transport:
            assert (
                not schema
            ), "Cannot fetch the schema from transport if is already provided."

        if schema and not transport:
            transport = LocalSchemaTransport(schema)

        # GraphQL schema
        self.schema: Optional[GraphQLSchema] = schema

        # Answer of the introspection query
        self.introspection = introspection

        # GraphQL transport chosen
        self.transport: Optional[Union[Transport, AsyncTransport]] = transport

        # Flag to indicate that we need to fetch the schema from the transport
        # On async transports, we fetch the schema before executing the first query
        self.fetch_schema_from_transport: bool = fetch_schema_from_transport

        # Enforced timeout of the execute function (only for async transports)
        self.execute_timeout = execute_timeout
Exemple #27
0
 def __attrs_post_init__(self) -> None:
     self.schema = graphql.build_client_schema(self.raw_schema)
Exemple #28
0
def load_schema(uri):
    introspection = load_introspection_from_file(uri) if os.path.isfile(uri) else load_introspection_from_server(uri)
    return build_client_schema(introspection)
def gql_schema(anon_user_gql_client):
    introspection = anon_user_gql_client.execute(introspection_query)
    return build_client_schema(introspection["data"])
Exemple #30
0
 def client_schema(self) -> graphql.GraphQLSchema:
     return graphql.build_client_schema(self.raw_schema)
Exemple #31
0
def load_schema(uri):
    introspection = load_introspection_from_file(uri) if os.path.isfile(
        uri) else load_introspection_from_server(uri)
    return build_client_schema(introspection)