Beispiel #1
0
    def test_code():
        sample_transport = RequestsHTTPTransport(url=url)

        query = gql(query1_str)

        with pytest.raises(TransportClosed):
            sample_transport.execute(query)
Beispiel #2
0
def create_gql_client(token):
    transport = RequestsHTTPTransport(url='https://api.github.com/graphql',
                                      use_json=True)
    transport.headers = {"Authorization": "Bearer {}".format(token)}
    client = Client(transport=transport)

    return client
Beispiel #3
0
    def __init__(self, account_id, api_key, region="us"):
        try:
            self.account_id = int(account_id)
        except ValueError:
            raise ValueError("Account ID must be an integer")

        self.api_key = api_key

        if region == "us":
            self.url = "https://api.newrelic.com/graphql"
        elif region == "eu":
            self.url = "https://api.eu.newrelic.com/graphql"
        elif region == "staging":
            self.url = "https://staging-api.newrelic.com/graphql"
        else:
            raise ValueError("Region must be one of 'us' or 'eu'")

        transport = RequestsHTTPTransport(url=self.url, use_json=True)
        transport.headers = {"api-key": self.api_key}

        try:
            self.client = Client(transport=transport,
                                 fetch_schema_from_transport=True)
        except Exception:
            self.client = Client(transport=transport,
                                 fetch_schema_from_transport=False)
Beispiel #4
0
 def client(self):
     if self._client is None:
         transport = \
             RequestsHTTPTransport(self.url, use_json=True, timeout=300)
         transport.headers = {
             'User-Agent': 'sierra-client (python)/{}'.format(VERSION)
         }
         self._client = Client(
             transport=transport,
             fetch_schema_from_transport=True)
     return self._client
Beispiel #5
0
    def __init__(self,
                 key,
                 secret,
                 access_token,
                 access_secret,
                 etherscan_api_key,
                 trade_value_threshold=250000,
                 short_position_value_threshold=100000,
                 eye_catcher_threshold=1000000,
                 debug=False):
        auth = OAuthHandler(key, secret)
        auth.set_access_token(access_token, access_secret)
        self.api = API(auth)

        self.etherscan_api_key = etherscan_api_key

        # Trades
        transport = RequestsHTTPTransport(
            url=EXCHANGE_SUBGRAPH_API_ENDPOINT,
            verify=True,
            retries=3,
        )
        self.gql_client_synthetix_exchanges = Client(
            transport=transport, fetch_schema_from_transport=True)

        # Cross-asset Swaps
        transport = RequestsHTTPTransport(
            url=CURVE_SUBGRAPH_API_ENDPOINT,
            verify=True,
            retries=3,
        )
        self.gql_client_curve = Client(transport=transport,
                                       fetch_schema_from_transport=True)

        # Short positions
        transport = RequestsHTTPTransport(
            url=SHORTS_SUBGRAPH_API_ENDPOINT,
            verify=True,
            retries=3,
        )
        self.gql_client_synthetix_shorts = Client(
            transport=transport, fetch_schema_from_transport=True)

        # CoinGecko
        self.cg = CoinGeckoAPI()

        self.trade_value_threshold = trade_value_threshold
        self.short_position_value_threshold = short_position_value_threshold
        self.eye_catcher_threshold = eye_catcher_threshold

        self.timestamp_last_fetch = int(time.time())
        self.debug = debug
Beispiel #6
0
 def __init__(self, username, password, year):
     self.username = username
     self.password = password
     self.year = year
     self.gql_unauthenticated_client = Client(
         transport=RequestsHTTPTransport(_graphql_url()),
         fetch_schema_from_transport=True,
     )
     self.gql_client = Client(
         transport=RequestsHTTPTransport(
             _graphql_url(), headers={"authorization": self._token()}),
         fetch_schema_from_transport=True,
     )
Beispiel #7
0
def main(remote,
         remote_authorization,
         host,
         port,
         debug=False,
         debug_sql=False,
         setup_db=False):

    if debug:
        logging.basicConfig(level=logging.DEBUG)
    if debug_sql:
        logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    if setup_db:
        from datasub.monitoring.database import engine
        from datasub.monitoring.models import Base
        Base.metadata.create_all(bind=engine)

    headers = {}
    if remote_authorization is not None:
        headers['Authorization'] = remote_authorization

    client = datasub.monitoring.gql.Client(
        transport=RequestsHTTPTransport(
            url=remote,
            headers=headers,
            use_json=True,
        ),
        fetch_schema_from_transport=True,
    )

    schema = make_remote_executable_schema(client.schema, client)

    app = datasub.app.create(schema)
    app.run(host=host, port=port, debug=debug)
Beispiel #8
0
 def __init__(self, overrides={}):
     self.settings = {
         'entity': None,
         'project': None,
         'run': "latest",
         'base_url': env.get_base_url("https://api.wandb.ai")
     }
     self.settings.update(overrides)
     if 'username' in overrides and 'entity' not in overrides:
         wandb.termwarn(
             'Passing "username" to Api is deprecated. please use "entity" instead.'
         )
         self.settings['entity'] = overrides['username']
     self._projects = {}
     self._runs = {}
     self._sweeps = {}
     self._base_client = Client(transport=RequestsHTTPTransport(
         headers={
             'User-Agent': self.user_agent,
             'Use-Admin-Privileges': "true"
         },
         use_json=True,
         # this timeout won't apply when the DNS lookup fails. in that case, it will be 60s
         # https://bugs.python.org/issue22889
         timeout=self._HTTP_TIMEOUT,
         auth=("api", self.api_key),
         url='%s/graphql' % self.settings['base_url']))
     self._client = RetryingClient(self._base_client)
Beispiel #9
0
    def do_GET(self):

        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

        client = Client(
            transport=RequestsHTTPTransport(
                url='https://graphql.fauna.com/graphql',
                headers={
                    'Authorization': 'Bearer ' + getenv("FAUNADB_SECRET")
                },
                use_json=True,
            ),
            fetch_schema_from_transport=True,
        )

        query = gql("""
    {
      findClientByID(id: "258719855966945812") {
        email
      }
    }
    """)

        self.wfile.write(json.dumps(client.execute(query)).encode('utf-8'))

        return
Beispiel #10
0
def ConvertTimeStampsToBlocks(timestamps):

    blocks = [None] * (len(timestamps))

    # eth block api
    sample_transport_ETH = RequestsHTTPTransport(
        url=
        'https://api.thegraph.com/subgraphs/name/blocklytics/ethereum-blocks',
        verify=True,
        retries=5,
    )
    client_ETH = Client(transport=sample_transport_ETH)

    for i in range(0, len(timestamps)):
        params_name = {"timestamp_gt": timestamps[i]}

        block = gql("""
        query($timestamp_gt: BigInt! )
        {
            blocks(first: 1, orderBy: timestamp, orderDirection: asc,
            where: {timestamp_gt: $timestamp_gt})
        {
            id
        number
        timestamp
        }
        }""")

        block_data = client_ETH.execute(block, variable_values=params_name)
        blocks[i] = int(block_data['blocks'][0]['number'])

    return blocks
Beispiel #11
0
    def update_intended_process_states(self, name, running=False):
        try:
            access_token = create_access_token(identity=current_user)
            transport = RequestsHTTPTransport(
                url=GRAPHQL_URI,
                use_json=True,
                headers={
                    "Content-Type": "application/json; charset=utf-8",
                    "Authorization": "Bearer {}".format(access_token),
                },
                verify=False,
            )

            client = Client(retries=3,
                            transport=transport,
                            fetch_schema_from_transport=True)

            query = gql(intended_process_states_mutation)

            params = {"name": name, "running": running}

            client.execute(query, variable_values=params)

        except Exception:
            log.exception("exception")
Beispiel #12
0
def signal_loading(module, status=False):
    if GUI_ENABLED != "true":
        return
    try:

        transport = RequestsHTTPTransport(
            url=GRAPHQL_URI,
            use_json=True,
            headers={
                "Content-type": "application/json; charset=utf-8",
                "x-hasura-admin-secret": HASURA_GRAPHQL_ACCESS_KEY,
            },
            verify=False,
        )

        client = Client(retries=3,
                        transport=transport,
                        fetch_schema_from_transport=True)

        query = gql(PROCESS_STATES_LOADING_MUTATION)

        params = {"name": "{}%".format(module), "loading": status}

        client.execute(query, variable_values=params)

    except Exception:
        log.exception("exception")
Beispiel #13
0
async def test_async_client_sync_transport(event_loop, fetch_schema_from_transport):

    url = "http://countries.trevorblades.com/graphql"

    # Get sync transport
    sample_transport = RequestsHTTPTransport(url=url, use_json=True)

    # Impossible to use a sync transport asynchronously
    with pytest.raises(AssertionError):
        async with Client(
            transport=sample_transport,
            fetch_schema_from_transport=fetch_schema_from_transport,
        ):
            pass

    sample_transport.close()
def get_data():
    _transport = RequestsHTTPTransport(
        url='http://localhost:5000/graphql',
        use_json=True,
    )

    client = Client(
        transport=_transport,
        fetch_schema_from_transport=True,
    )
    query = gql("""

    query{
    findLocationData(location: "Juja"){
        uuid
        location
        region
        localtime
        tempC
        windKph
        windDegree
        windDir
        pressureMb
        precipMm
        humidity
        cloud
    }
    }
    """)

    return client.execute(query)
def _get_rbc_eth_ratio(token_address) -> float:
    """
    Parse exchange rate rbc to eth from UniSwap.
    Return exchange rate: float.
    """
    transport = RequestsHTTPTransport(url=UNISWAP_API_URL)
    client = Client(transport=transport, fetch_schema_from_transport=True)
    query = gql("""
        {
            token(id: "%s"){
               name
               symbol
               decimals
               derivedETH
               tradeVolumeUSD
               totalLiquidity
            }
        }
        """ % token_address.lower())

    while 1:
        # Execute the query on the transport
        result = client.execute(query)

        if result:
            logging.info('UNISWAP GQL response: {}'.format(
                float(result.get("token").get("derivedETH"))))

            break

    return float(result.get("token").get("derivedETH"))
def test_max_characters():
    transport = RequestsHTTPTransport(
        url=urljoin(base, "gql"),
        verify=False,
        retries=3,
    )

    client = Client(
        transport=transport,
        fetch_schema_from_transport=True,
    )

    long_str = "then the more there are the better in order that they neutralize each other. When in the later part of the book he comes to consider government... these three should form a crescendo but usually perform a diminuendo."
    q = query_str.replace("How do you do?", long_str)
    with pytest.raises(Exception) as e:
        _ = client.execute(gql(q))

    assert str(e.value) == str({
        "message":
        "1 validation error for TranslationRequest\nsource_text\n  ensure this value has at most 200 characters (type=value_error.any_str.max_length; limit_value=200)",
        "locations": [{
            "line": 2,
            "column": 3
        }],
        "path": ["translation"],
    })
Beispiel #17
0
 def __init__(self, url):
     self.url = url
     self.client = gql.Client(
         transport=RequestsHTTPTransport(url=add_url_path(url,
                                                          'graphql'), ),
         fetch_schema_from_transport=True,
     )
def test_graphql_works():
    transport = RequestsHTTPTransport(
        url=urljoin(base, "gql"),
        verify=False,
        retries=3,
    )

    client = Client(
        transport=transport,
        fetch_schema_from_transport=True,
    )

    result = client.execute(query)

    assert result == {
        "translation": {
            "translatedText":
            "¿Cómo estás?",
            "fromLanguage":
            "en",
            "alignment": [{
                "src": {
                    "start": "0",
                    "end": "13",
                    "text": "How do you do?"
                },
                "dest": {
                    "start": "0",
                    "end": "11",
                    "text": "¿Cómo estás?"
                },
            }],
        }
    }
    def play(self, agent: Agent, game_id, player_id, player_token):
        http_transport = RequestsHTTPTransport(
            url=self.url,
            headers={'Authorization': player_token},
            verify=False,
            retries=3)

        with Client(transport=http_transport,
                    fetch_schema_from_transport=True) as session:
            winner = None
            result = session.execute(gql(START_GAME(game_id)))
            result = result['startGame']
            state = result['state']
            while True:
                result = session.execute(
                    gql(
                        DO_ACTION(
                            game_id,
                            agent.compute_action(
                                0 if result['playerOneId'] == player_id else 1,
                                state))))
                result = result['doAction']
                state = result['state']

                if result['status'] == GameStatus.ENDED:
                    winner = None if result['winner'] is None else 0 if result[
                        'winner']['id'] == result['playerOneId'] else 1
                    break
                if result['status'] == GameStatus.CLOSED:
                    break

            agent.on_game_ended(player_id, state, winner)
Beispiel #20
0
def fetch_from_caida():
    # we don't really care about traffic security here
    urllib3.disable_warnings()

    caida_transport = RequestsHTTPTransport(
        url="https://api.asrank.caida.org/v2/graphql",
        headers={"Content-type": "application/json"},
        use_json=True,
        verify=False,
    )

    client = gql.Client(retries=3, transport=caida_transport)

    offset = 0
    has_next_page = True
    while has_next_page:
        response = client.execute(QUERY, {
            "first": BATCH_SIZE,
            "offset": offset
        })
        has_next_page = response["asns"]["pageInfo"]["hasNextPage"]
        total_count = response["asns"]["totalCount"]
        offset += BATCH_SIZE

        for edge in response["asns"]["edges"]:
            node = edge["node"]
            asn, rank = node["asn"], node["rank"]
            yield int(asn), rank
 def client_session(self):
     transport = RequestsHTTPTransport(
         url=GH_GQL_URL, headers={"Authorization": f"bearer {GH_TOKEN}"})
     client = gql_client(transport=transport,
                         fetch_schema_from_transport=True)
     with client as session:
         yield session
    def __init__(self):
        self._config = Config()

        self._raw = None
        self._subpath_keys = None
        self._sublist_keys = None
        self._id_key = None

        self._translated = None

        self._arguments = utils.load_yaml((utils.build_yaml_path("arguments")))
        self._fields = utils.load_yaml((utils.build_yaml_path("fields")))

        ua = UserAgent()
        headers = {
            "User-Agent": ua.random,
            "Content-Type": "application/json",
            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
            "Connection": "keep-alive",
            "Host": "www.sportsbookreview.com",
            "Referer": "https://www.sportsbookreview.com/betting-odds/",
        }
        transport = RequestsHTTPTransport(
            url="https://www.sportsbookreview.com/ms-odds-v2/odds-v2-service",
            headers=headers,
        )
        self.client = Client(transport=transport,
                             fetch_schema_from_transport=False)
Beispiel #23
0
def _get_client() -> Client:
    if not (GITHUB_API_TOKEN and GITHUB_GRAPHQL_ENDPOINT):
        raise GithubGraphqlApiNotProperlyConfiguredException("Token and endpoint properties are required")
    # TODO I know it will create the same stuff all the time. Working in progress :)
    headers = {"Authorization": f"bearer {GITHUB_API_TOKEN}"}
    _transport = RequestsHTTPTransport(url=GITHUB_GRAPHQL_ENDPOINT, use_json=True, timeout=(5, 25), headers=headers)
    return Client(retries=3, transport=_transport, fetch_schema_from_transport=True)
Beispiel #24
0
def test_execute_result_error():
    expected_retries = 3

    client = Client(
        retries=expected_retries,
        transport=RequestsHTTPTransport(
            url="https://countries.trevorblades.com/",
            use_json=True,
            headers={"Content-type": "application/json"},
        ),
    )

    failing_query = gql("""
    query getContinents {
      continents {
        code
        name
        id
      }
    }
    """)

    with pytest.raises(Exception) as exc_info:
        client.execute(failing_query)
    client.close()
    assert 'Cannot query field "id" on type "Continent".' in str(
        exc_info.value)
Beispiel #25
0
def query(name, **kwargs):
    url = "https://api.github.com/graphql"

    api_token = config.get_value("token")

    transport = RequestsHTTPTransport(
        url=url,
        use_json=True,
        headers={
            "Authorization": "Bearer %s" % api_token,
            "Accept": "application/vnd.github.vixen-preview+json",
        },
    )

    log.debug(
        f"Calling query {name}.graphql with token starting {api_token[0:4]}")
    client = Client(transport=transport, fetch_schema_from_transport=False)
    queries = {}
    for filename in os.listdir("query"):
        with open(f"query/{filename}") as query_file:
            queries[filename.split(".")[0]] = query_file.read()
    query_template = Template(queries[name])
    full_query = query_template.render(**kwargs)
    query = gql(full_query)
    return Dict(client.execute(query))
Beispiel #26
0
def test_retries_on_transport(execute_mock):
    """Testing retries on the transport level

    This forces us to override low-level APIs because the retry mechanism on the urllib3 (which
    uses requests) is pretty low-level itself.
    """
    expected_retries = 3
    execute_mock.side_effect = NewConnectionError("Should be HTTPConnection",
                                                  "Fake connection error")
    transport = RequestsHTTPTransport(
        url="http://localhost:9999",
        retries=expected_retries,
    )
    client = Client(transport=transport)

    query = gql("""
    {
      myFavoriteFilm: film(id:"RmlsbToz") {
        id
        title
        episodeId
      }
    }
    """)
    with client:  # We're using the client as context manager
        with pytest.raises(Exception):
            client.execute(query)

    # This might look strange compared to the previous test, but making 3 retries
    # means you're actually doing 4 calls.
    assert execute_mock.call_count == expected_retries + 1
Beispiel #27
0
def get_client(url, **kwargs):
    """
    Setup the gql transport settings for hitting the FlyBase GraphQL API
    endpoint and return the client.

    :param url: - The URL for the GraphQL endpoint.
    :param kwargs: - Any additional keyword params to pass to the
                     RequestsHTTPTransport class.
    :return: The gql.Client class object.
    """
    flybase_transport = RequestsHTTPTransport(
        url=url,
        use_json=True,
        headers={
            "Content-type": "application/json",
        },
        verify=False,
        retries=3,
        **kwargs
    )
    # Init and return GraphQL client.
    return Client(
        transport=flybase_transport,
        fetch_schema_from_transport=True,
    )
Beispiel #28
0
def test_execute_result_error():
    expected_retries = 3

    client = Client(retries=expected_retries,
                    transport=RequestsHTTPTransport(
                        url='https://countries.trevorblades.com/',
                        use_json=True,
                        headers={
                            "Content-type": "application/json",
                        }))

    failing_query = gql('''
    query getContinents {
      continents {
        code
        name
        id
      }
    }
    ''')

    with pytest.raises(Exception) as exc_info:
        client.execute(failing_query)
    assert "Cannot query field \"id\" on type \"Continent\"." in str(
        exc_info.value)
Beispiel #29
0
def get_graphql_client(login_response, session_cookies, graphql_token):
    """Create a client for GraphQL queries.

    Args:
        login_response (requests.Response): The HTTP response from the login
            page (required to retrieve the session cookies)
        session_cookies (requests.CookieJar): Session cookies, initialised
            at login
        graphql_token (int): The "UniqeID" value retrieve from the login page.
            Used by the "Authorization" header during GraphQL queries.
    """
    # We transform the CookieJar object into a cookies header string
    # The current RequestsHTTPTransport constructor does not support
    # a cookies paramater, so we create a cookie header string instead.
    cookie_header = requests.cookies.get_cookie_header(session_cookies,
                                                       login_response)

    headers = {
        'Host': 'www.britishgas.co.uk',
        'Accept': 'application/json, text/plain, */*',
        'Cookie': cookie_header,
        'Authorization': graphql_token,
    }

    return Client(transport=RequestsHTTPTransport(url=MYENERGY_GRAPHQL_URL,
                                                  headers=headers,
                                                  timeout=TIMEOUT_S),
                  fetch_schema_from_transport=True)
Beispiel #30
0
def test_retries(execute_mock):
    expected_retries = 3
    execute_mock.side_effect = Exception("fail")

    client = Client(
        retries=expected_retries,
        transport=RequestsHTTPTransport(url="http://swapi.graphene-python.org/graphql"),
    )

    query = gql(
        """
    {
      myFavoriteFilm: film(id:"RmlsbToz") {
        id
        title
        episodeId
      }
    }
    """
    )

    with pytest.raises(Exception):
        client.execute(query)

    assert execute_mock.call_count == expected_retries