Esempio n. 1
0
def _create_transport(url, auth_token, language):
    """Create and return a gql transport object.

    :param str url: the Tracker GraphQL endpoint url.
    :param str auth_token: JWT auth token, omit when initially obtaining the token (default is none).
    :param str lang: value to set the http "accept-language" header to.
    :return: A gql transport for given url.
    :rtype: AIOHTTPTransport
    :raises ValueError: if auth_token is not a valid JWT or language is not "en" or "fr".
    :raises TypeError: if auth_token is not a string.
    """
    if auth_token is None:
        transport = AIOHTTPTransport(url=url)

    else:
        # Resulting stack trace is very unhelpful when passing an invalid token
        # We validate the given auth_token and raise an exception if it's invalid
        # to make debugging easier
        if not isinstance(auth_token, str):
            raise TypeError("auth_token must be a string")

        if not re.match(_JWT_RE, auth_token):
            raise ValueError("auth_token is not a valid JWT")

        if language.lower() != "en" and language.lower() != "fr":
            raise ValueError("Language must be 'en' or 'fr'")

        transport = AIOHTTPTransport(
            url=url,
            headers=generate_headers(auth_token, language),
        )

    return transport
Esempio n. 2
0
 def getClient(self):
     transport = AIOHTTPTransport(url=GRAPHQL_URL)
     if self.token != None:
         transport = AIOHTTPTransport(
             url=GRAPHQL_URL, headers={'Authorization': str(self.token)})
     client = Client(transport=transport, fetch_schema_from_transport=True)
     return client
Esempio n. 3
0
async def graphql_connection(places, food_preferences, activity_preferences):
    results = []
    api_key = getAPIKey()
    # define our authentication process.
    header = {
        'Authorization': 'bearer {}'.format(api_key),
        'Content-Type': "application/json"
    }
    transport = AIOHTTPTransport(url="https://api.yelp.com/v3/graphql",
                                 headers=header)

    client = Client(transport=transport, fetch_schema_from_transport=True)
    async with client as session:
        for i in range(0, len(places), 2):
            spot = places[i]
            task1 = asyncio.create_task(
                execute_query(session, interests[0], spot,
                              food_preferences[i]))
            task2 = asyncio.create_task(
                execute_query(session, interests[1], spot,
                              activity_preferences[i]))
            if i + 1 < len(places):
                spot2 = places[i + 1]
                task3 = asyncio.create_task(
                    execute_query(session, interests[0], spot2,
                                  food_preferences[i + 1]))
                task4 = asyncio.create_task(
                    execute_query(session, interests[1], spot2,
                                  activity_preferences[i + 1]))
                ans = await asyncio.gather(task1, task2, task3, task4)
                results.append(ans[:2])
                results.append(ans[2:])
            else:
                results.append(await asyncio.gather(task1, task2))
        return results
Esempio n. 4
0
 def __init__(self, token):
     transport = AIOHTTPTransport(
         url='https://classic.warcraftlogs.com/api/v2/client',
         headers={'Authorization': 'Bearer ' + token},
         timeout=120)
     self.client = Client(transport=transport,
                          fetch_schema_from_transport=True)
Esempio n. 5
0
def get_orders(
    num_items: int,
    num_pages: int,
    orders_per_page: int,
    request_backoff_seconds: int,
) -> None:
    """Get orders from Shopify"""

    shopify_key = os.environ["SHOPIFY_KEY"]
    shopify_pass = os.environ["SHOPIFY_PASS"]
    transport = AIOHTTPTransport(
        url=
        f"https://{shopify_key}:{shopify_pass}@tstvhq.myshopify.com/admin/api/2021-04/graphql.json"
    )
    shopify_client = Client(transport=transport,
                            fetch_schema_from_transport=True)

    orders = get_shopify_orders(
        shopify_client,
        num_items,
        num_pages,
        orders_per_page,
        request_backoff_seconds,
    )
    for order in orders:
        print(order)
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     headers = {"Authorization": f'token {self.get_api_token("github")}'}
     transport = AIOHTTPTransport(url=self.GITHUB_API_ENDPOINT,
                                  headers=headers)
     self.client = Client(transport=transport,
                          fetch_schema_from_transport=True)
Esempio n. 7
0
def get_transport(args: Namespace) -> AsyncTransport:
    """Instanciate a transport from the parsed command line arguments

    :param args: parsed command line arguments
    """

    # Get the url scheme from server parameter
    url = URL(args.server)
    scheme = url.scheme

    # Get extra transport parameters from command line arguments
    # (headers)
    transport_args = get_transport_args(args)

    # Instanciate transport depending on url scheme
    transport: AsyncTransport
    if scheme in ["ws", "wss"]:
        transport = WebsocketsTransport(url=args.server,
                                        ssl=(scheme == "wss"),
                                        **transport_args)
    elif scheme in ["http", "https"]:
        transport = AIOHTTPTransport(url=args.server, **transport_args)
    else:
        raise ValueError("URL protocol should be one of: http, https, ws, wss")

    return transport
Esempio n. 8
0
async def removeOldestQuotes():
    today = datetime.now(timezone('CET'))
    delta = ""
    if today.weekday() == 0:
        delta = timedelta(days=4)
    elif today.weekday() == 1:
        delta = timedelta(days=4)
    else:
        delta = timedelta(days=2)
    date = today - delta
    transport = AIOHTTPTransport(url=gql_url, headers={ 'x-hasura-admin-secret': hasura_secret })
    async with Client(transport=transport, fetch_schema_from_transport=True) as session:
        query = gql(
            """
            mutation deleteStockQuotes($time: String!) {
                delete_quotes(where: {time: { _lt: $time }}) {
                    returning {
                        id
                    }
                }
            }
        """
        )
        params = {
            "time": date.isoformat()
        }
        await session.execute(query, variable_values=params)
Esempio n. 9
0
async def test_aiohttp_error_code_401(event_loop, aiohttp_server):
    from aiohttp import web
    from gql.transport.aiohttp import AIOHTTPTransport

    async def handler(request):
        # Will generate http error code 401
        return web.Response(
            text=
            '{"error":"Unauthorized","message":"401 Client Error: Unauthorized"}',
            content_type="application/json",
            status=401,
        )

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    transport = AIOHTTPTransport(url=url)

    async with Client(transport=transport) as session:

        query = gql(query1_str)

        with pytest.raises(TransportServerError) as exc_info:
            await session.execute(query)

        assert "401, message='Unauthorized'" in str(exc_info.value)
Esempio n. 10
0
def graph_ql():
    date = datetime.now()
    logs = open('calls.log', 'a')
    log_value =  ''+str(date)+ '-' + request.path +'\n'
    logs.write(log_value)

    # Select your transport with a defined url endpoint
    transport = AIOHTTPTransport(url="http://localhost:4000/graphql")
    
    # Create a GraphQL client using the defined transport
    client = Client(transport=transport, fetch_schema_from_transport=True)

    stId = request.args.get('studentID')

    # Provide a GraphQL query
    query = gql(
        """
       query findStudent($studentid: String)
       { studentQueryById(studentid: $studentid) {
          studentid
          studentname
          studentdob
        }

    }
    """
    )

    variables = {"studentid": stId}
    
    # Execute the query on the transport
    result = client.execute(query, variables)
    return (result)
Esempio n. 11
0
async def main():

    # Should look like:
    # https://XXXXXXXXXXXXXXXXXXXXXXXXXX.appsync-api.REGION.amazonaws.com/graphql
    url = os.environ.get("AWS_GRAPHQL_API_ENDPOINT")

    if url is None:
        print("Missing environment variables")
        sys.exit()

    # Extract host from url
    host = str(urlparse(url).netloc)

    auth = AppSyncIAMAuthentication(host=host)

    transport = AIOHTTPTransport(url=url, auth=auth)

    async with Client(
            transport=transport,
            fetch_schema_from_transport=False,
    ) as session:

        query = gql("""
mutation createMessage($message: String!) {
  createMessage(input: {message: $message}) {
    id
    message
    createdAt
  }
}""")

        variable_values = {"message": "Hello world!"}

        result = await session.execute(query, variable_values=variable_values)
        print(result)
Esempio n. 12
0
    def __init__(self, key):
        self.GITHUB_SECRET_KEY = key
        self.gql = GitHubGQL

        self.__headers = {"Authorization": "bearer " + self.GITHUB_SECRET_KEY}
        self.__transport = AIOHTTPTransport(
            url="https://api.github.com/graphql", headers=self.__headers)
Esempio n. 13
0
async def test_aiohttp_query_variable_values(event_loop, aiohttp_server):
    async def handler(request):
        return web.Response(text=query2_server_answer, content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    sample_transport = AIOHTTPTransport(url=url, timeout=10)

    async with Client(transport=sample_transport,) as session:

        params = {"code": "EU"}

        query = gql(query2_str)

        # Execute query asynchronously
        result = await session.execute(
            query, variable_values=params, operation_name="getEurope"
        )

        continent = result["continent"]

        assert continent["name"] == "Europe"
Esempio n. 14
0
async def test_aiohttp_binary_file_upload(event_loop, aiohttp_server):
    app = web.Application()
    app.router.add_route("POST", "/", binary_upload_handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    sample_transport = AIOHTTPTransport(url=url, timeout=10)

    with TemporaryFile(binary_file_content) as test_file:

        async with Client(transport=sample_transport, ) as session:

            query = gql(file_upload_mutation_1)

            file_path = test_file.filename

            with open(file_path, "rb") as f:

                params = {"file": f, "other_var": 42}

                # Execute query asynchronously
                result = await session.execute(query,
                                               variable_values=params,
                                               upload_files=True)

            success = result["success"]

            assert success
Esempio n. 15
0
async def test_aiohttp_extra_args(event_loop, aiohttp_server):
    async def handler(request):
        return web.Response(text=query1_server_answer, content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    # passing extra arguments to aiohttp.ClientSession
    jar = DummyCookieJar()
    sample_transport = AIOHTTPTransport(
        url=url, timeout=10, client_session_args={"version": "1.1", "cookie_jar": jar}
    )

    async with Client(transport=sample_transport,) as session:

        query = gql(query1_str)

        # Passing extra arguments to the post method of aiohttp
        result = await session.execute(query, extra_args={"allow_redirects": False})

        continents = result["continents"]

        africa = continents[0]

        assert africa["code"] == "AF"
Esempio n. 16
0
async def test_aiohttp_cookies(event_loop, aiohttp_server):
    from aiohttp import web
    from gql.transport.aiohttp import AIOHTTPTransport

    async def handler(request):
        assert "COOKIE" in request.headers
        assert "cookie1=val1" == request.headers["COOKIE"]

        return web.Response(text=query1_server_answer,
                            content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    transport = AIOHTTPTransport(url=url, cookies={"cookie1": "val1"})

    async with Client(transport=transport) as session:

        query = gql(query1_str)

        # Execute query asynchronously
        result = await session.execute(query)

        continents = result["continents"]

        africa = continents[0]

        assert africa["code"] == "AF"
Esempio n. 17
0
async def test_aiohttp_query(event_loop, aiohttp_server):
    async def handler(request):
        return web.Response(text=query1_server_answer,
                            content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    sample_transport = AIOHTTPTransport(url=url, timeout=10)

    async with Client(transport=sample_transport, ) as session:

        query = gql(query1_str)

        # Execute query asynchronously
        result = await session.execute(query)

        continents = result["continents"]

        africa = continents[0]

        assert africa["code"] == "AF"
Esempio n. 18
0
 async def main(self, channel):
     headers = {
         "Authorization": f"Bearer {self.conf['Tokens']['Testmail']}"
     }
     transport = AIOHTTPTransport(
         url="https://api.testmail.app/api/graphql", headers=headers)
     async with Client(transport=transport,
                       fetch_schema_from_transport=True) as session:
         self.bot.log("Checking testmail")
         result = await session.execute(gql(self.req))
         for email in result["inbox"]["emails"]:
             if email not in self.emails:
                 embed = discord.Embed()
                 embed.set_author(
                     name=
                     f"From: {email['from']}\nTo: {email['to']}\nSubject: {email['subject']}"
                 )
                 embed.description = email['text'][:2047]
                 await channel.send(embed=embed)
                 self.emails.append(email)
                 # reee why cant i give a string and have discord.File do it for me
                 sio = io.StringIO(email["html"])
                 bio = io.BytesIO(sio.read().encode('utf8'))
                 htmlfile = discord.File(bio, filename="email.html")
                 await channel.send(file=htmlfile)
Esempio n. 19
0
async def test_aiohttp_ignore_backend_content_type(event_loop, aiohttp_server):
    from aiohttp import web
    from gql.transport.aiohttp import AIOHTTPTransport

    async def handler(request):
        return web.Response(text=query1_server_answer,
                            content_type="text/plain")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    transport = AIOHTTPTransport(url=url, timeout=10)

    async with Client(transport=transport) as session:

        query = gql(query1_str)

        result = await session.execute(query)

        continents = result["continents"]

        africa = continents[0]

        assert africa["code"] == "AF"
Esempio n. 20
0
    def __init__(self, api_token, *args, **kwargs):
        self.loop = kwargs.get('loop') or asyncio.get_event_loop()
        self.token_provided = api_token is not None
        self.__auth = 'Sdk ' + (api_token or os.getenv('DCLIST_TOKEN') or '')

        self._transporter = kwargs.get('transporter') or AIOHTTPTransport(
            url=self.BASE, headers={'Authorization': self.__auth})
Esempio n. 21
0
async def test_aiohttp_query_variable_values_fix_issue_292(
        event_loop, aiohttp_server):
    """Allow to specify variable_values without keyword.

    See https://github.com/graphql-python/gql/issues/292"""

    from aiohttp import web
    from gql.transport.aiohttp import AIOHTTPTransport

    async def handler(request):
        return web.Response(text=query2_server_answer,
                            content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    transport = AIOHTTPTransport(url=url, timeout=10)

    async with Client(transport=transport) as session:

        params = {"code": "EU"}

        query = gql(query2_str)

        # Execute query asynchronously
        result = await session.execute(query,
                                       params,
                                       operation_name="getEurope")

        continent = result["continent"]

        assert continent["name"] == "Europe"
Esempio n. 22
0
async def test_aiohttp_stream_reader_upload(event_loop, aiohttp_server):
    from aiohttp import web, ClientSession
    from gql.transport.aiohttp import AIOHTTPTransport

    async def binary_data_handler(request):
        return web.Response(body=binary_file_content,
                            content_type="binary/octet-stream")

    app = web.Application()
    app.router.add_route("POST", "/", binary_upload_handler)
    app.router.add_route("GET", "/binary_data", binary_data_handler)

    server = await aiohttp_server(app)

    url = server.make_url("/")
    binary_data_url = server.make_url("/binary_data")

    transport = AIOHTTPTransport(url=url, timeout=10)

    async with Client(transport=transport) as session:
        query = gql(file_upload_mutation_1)
        async with ClientSession() as client:
            async with client.get(binary_data_url) as resp:
                params = {"file": resp.content, "other_var": 42}

                # Execute query asynchronously
                result = await session.execute(query,
                                               variable_values=params,
                                               upload_files=True)

    success = result["success"]

    assert success
Esempio n. 23
0
async def test_aiohttp_invalid_protocol(event_loop, aiohttp_server, param):
    from aiohttp import web
    from gql.transport.aiohttp import AIOHTTPTransport

    response = param["response"]

    async def handler(request):
        return web.Response(text=response, content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await aiohttp_server(app)

    url = server.make_url("/")

    transport = AIOHTTPTransport(url=url)

    async with Client(transport=transport) as session:

        query = gql(query1_str)

        with pytest.raises(TransportProtocolError) as exc_info:
            await session.execute(query)

        assert param["expected_exception"] in str(exc_info.value)
Esempio n. 24
0
async def main():

    async with aiohttp.ClientSession() as session:
        # Select your transport with a defined url endpoint
        transport = AIOHTTPTransport(
            url="https://dbschool.alcyone.life/graphql")

        async with session.get(
                'http://51.15.17.205:9000/tick/Tony') as response:
            json = await response.json()

        # Create a GraphQL client using the defined transport
        async with Client(
                transport=transport,
                fetch_schema_from_transport=True,
        ) as client:
            data = json['data']
            for tick in data:

                query = gql("""
                        mutation {
                            createTicker(input: { data:{ symbol: "%s", price: %d } }) {
                                ticker {
                                    symbol
                                    price
                                }
                            }
                        }
                    """ % (str(tick['symbol']), float(tick['price'])))

                # Execute the query on the transport
                result = await client.execute(query)
                print(result)
Esempio n. 25
0
async def test_aiohttp_query_https(event_loop, ssl_aiohttp_server,
                                   ssl_close_timeout):
    from aiohttp import web
    from gql.transport.aiohttp import AIOHTTPTransport

    async def handler(request):
        return web.Response(text=query1_server_answer,
                            content_type="application/json")

    app = web.Application()
    app.router.add_route("POST", "/", handler)
    server = await ssl_aiohttp_server(app)

    url = server.make_url("/")

    assert str(url).startswith("https://")

    transport = AIOHTTPTransport(url=url,
                                 timeout=10,
                                 ssl_close_timeout=ssl_close_timeout)

    async with Client(transport=transport) as session:

        query = gql(query1_str)

        # Execute query asynchronously
        result = await session.execute(query)

        continents = result["continents"]

        africa = continents[0]

        assert africa["code"] == "AF"
Esempio n. 26
0
async def _tick_(request):
    async with aiohttp.ClientSession() as session:
        async with session.get('http://51.15.17.205:9000/tick/Julien') as resp:
            print(resp.status)
            print(await resp.text())
            info = await resp.json()
            response = await resp.json()

            transport = AIOHTTPTransport(
                url='https://dbschool.alcyone.life/graphql')

            async with Client(transport=transport,
                              fetch_schema_from_transport=True) as session:
                print(response)
                for value in response['data']:
                    # Execute single query
                    query = gql("""
                                mutation {
                                  createTicker(input: { data: { symbol: "%s", price: %.2f } }) {
                                    ticker {
                                      symbol
                                      price
                                    }
                                  }
                                }
                            """ % (value['symbol'], float(value['price'])))

                    result = await session.execute(query)
                    print(result)


#
                return aiohttp.web.json_response(dict(json=response))
Esempio n. 27
0
    def test_code():
        sample_transport = AIOHTTPTransport(url=url)

        client = Client(transport=sample_transport)

        query = gql(query1_str)

        client.execute(query)
Esempio n. 28
0
 async def query_http(query, variable_values=None, with_fragments=True):
     transport = AIOHTTPTransport(
         url="https://graph.codeday.org/",
         headers={"authorization": f"Bearer {GQLService.make_token()}"})
     client = Client(transport=transport, fetch_schema_from_transport=False)
     return await client.execute_async(GQLService.make_query(
         query, with_fragments=with_fragments),
                                       variable_values=variable_values)
Esempio n. 29
0
async def execute_ethereum_gql_query(network: str, query: DocumentNode,
                                     variables: Dict) -> Dict:
    """Executes GraphQL query."""
    subgraph_url = NETWORKS[network]["ETHEREUM_SUBGRAPH_URL"]
    transport = AIOHTTPTransport(url=subgraph_url)
    async with Client(transport=transport,
                      execute_timeout=EXECUTE_TIMEOUT) as session:
        return await session.execute(query, variable_values=variables)
Esempio n. 30
0
 def __init__(self):
     env = os.environ
     if not 'BACKEND_URL' in env:
         raise RuntimeError('Missing env values')
     self.__backend = env['BACKEND_URL']
     transport = AIOHTTPTransport(url=self.__backend)
     self.__api = Client(transport=transport, fetch_schema_from_transport=True)
     logger.info('Using {} as API Endpoint'.format(self.__backend))