def __init__(self, access_token: str, graphql_api_url: str, course_id: str) -> None: self.access_token = access_token self.course_id = course_id self.headers = {'Authorization': 'Bearer ' + self.access_token, "Content-Type": "application/json"} self.variables = {"courseId": self.course_id, "first": 500} self.query = """ query courseEnrollment($courseId: ID!, $first: Int) { course(id: $courseId) { name enrollmentsConnection(first: $first){ edges{ node{ lastActivityAt type } cursor } pageInfo { endCursor hasNextPage } } } } """ self.client = GraphqlClient(endpoint=graphql_api_url, headers=self.headers) self.web_session = requests.Session() self.web_session.headers.update({ "Authorization": f"Bearer {CANVAS_ACCESS_KEY}" })
def getTodayData(exchange="hose"): from python_graphql_client import GraphqlClient # Instantiate the client with an endpoint. client = GraphqlClient( endpoint="https://gateway-iboard.ssi.com.vn/graphql") # Create the query string and variables required for the request. query = """ query stockRealtimes($exchange: String) { stockRealtimes(exchange: $exchange) { stockSymbol refPrice ceiling floor openPrice matchedPrice priceChange priceChangePercent highest avgPrice lowest nmTotalTradedQty } } """ variables = {"exchange": exchange} # Asynchronous request import asyncio data = asyncio.run(client.execute_async(query=query, variables=variables)) return data['data']['stockRealtimes']
def crawl(self, count: int, source: str, keyword: str) -> None: title_list = [] headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36" } contents_list = [] page = count // 10 + 1 for i in range(page): url = 'https://weixin.sogou.com/weixin?query=' + str( keyword) + '&type=2&page=' + str(i) + '&ie=utf8' res = requests.get(url, headers=headers) res.encoding = "utf-8" soup = BeautifulSoup(res.text, 'html.parser') datas = soup.find('div', class_='news-box').find_all('li') for data in datas: title_list.append(data.find('div', class_='txt-box').h3.text) contents_list.append(data.find('div', class_='txt-box').p.text) client = GraphqlClient(endpoint="http://localhost:8080/v1/graphql") query = """ mutation MyMutation($content: String!, $imgurl: String!, $title: String!, $url: String!,$source: String!) { insert_spider(objects: {content: $content, imgurl: $imgurl, title: $title, url: $url, source: $source}) { affected_rows } } """ for j in range(len(title_list)): variables = { "content": contents_list[j], "title": title_list[j], "source": source } data = client.execute(query=query, variables=variables) print('finished')
def query_issues(github_token, owner=config.settings.github['owner'], repo=config.settings.github['repo'], iter=100): titles = [] client = GraphqlClient(endpoint=config.settings.github['graphql']) has_next_page = True next_cursor = None while has_next_page: data = client.execute( query=_to_graphql(next_cursor, owner, repo, iter), headers={"Authorization": "Bearer {}".format(github_token)}, ) # log.debug(json.dumps(data)) issues = data["data"]["repository"]["issues"] for issue in issues["edges"]: is_closed = issue["node"]["closed"] if not is_closed: title = issue["node"]["title"] titles.append(title) has_next_page = issues["pageInfo"]["hasNextPage"] next_cursor = issues["pageInfo"]["endCursor"] return titles
async def second_round(self, view): """ returns a dictionary, with episode_id as key, and as value have a pair of data, the first entry its how many diferent origins have all the characters involved in that episode, and the second entry its the list of origins_ids of all the characters involved in that episode (without repetition) """ client = GraphqlClient(endpoint=self.endpoint) query = RaMQuerys.forth_query(RaMQuerys, "1", view) page = await sync_to_async(client.execute)(query) Pages = page['data']['episodes']['info']['pages'] tasks = [] for i in range(1, Pages + 1): query_i = RaMQuerys.forth_query(RaMQuerys, i, view) tasks.append(client.execute_async(query_i)) aps = await asyncio.gather(*tasks) episode_origins_dict = {} for j in aps: for episode in j['data']['episodes']['results']: characters = episode['characters'] Id = episode['id'] name = episode['name'] origins = RaMStats.duplicate_elimination_by_origin_id( RaMStats, characters, view) if view: episode_origins_dict[name] = origins else: episode_origins_dict[Id] = origins return RaMStats.second_round_output(RaMStats, episode_origins_dict)
def collectionCreate(store, access_token): headers = { "X-Shopify-Access-Token": access_token, "Content-Type": "application/json" } client = GraphqlClient(endpoint="https://" + store + "/admin/api/2020-04/graphql.json") query = """ mutation collectionCreate($input: CollectionInput!) { collectionCreate(input: $input) { collection { id } userErrors { field message } } } """ variables = { 'input': 'gid://shopify/Product/{0}'.format(product_id), 'cursor': cursor } data = client.execute(query=query, headers=headers, variables=variables) return data
def removeProducts(store, access_token, collection_id, product_id): headers = { "X-Shopify-Access-Token": access_token, "Content-Type": "application/json" } client = GraphqlClient(endpoint="https://" + store + "/admin/api/2020-04/graphql.json") query = """ mutation collectionRemoveProducts($id: ID!, $productIds: [ID!]!) { collectionRemoveProducts(id: $id, productIds: $productIds) { job { id } userErrors { field message } } } """ if not 'gid://shopify/Collection/' in collection_id: collection_id = 'gid://shopify/Collection/{0}'.format(collection_id) variables = { 'id': collection_id, 'productIds': [product_id] } data = client.execute(query=query, headers=headers, variables=variables) return data
def test_execute_query_with_operation_name(self, post_mock): """Sends a graphql POST request with the operationName key set.""" client = GraphqlClient(endpoint="http://www.test-api.com/") query = """ query firstQuery { test { status } } query secondQuery { test { status } } """ operation_name = "firstQuery" client.execute(query, operation_name=operation_name) post_mock.assert_called_once_with( "http://www.test-api.com/", json={ "query": query, "operationName": operation_name }, headers={}, )
def __init__(self): headers = { "content-type": "application/json", "apollographql-client-name": "playground", "apollographql-client-version": "1.0", } self.gql_client = GraphqlClient(endpoint="https://www.prodigygame.net/graphql/", headers=headers)
def send_create_card_mutation(filename): from python_graphql_client import GraphqlClient import asyncio client = GraphqlClient(endpoint="http://localhost:8000/") mutation = """ mutation($filename: String) { createCard(card:{inside:98, mid:95, three:83, passing:99, steal:90, block: 70, accountID:1,filename:$filename}) { errors { field message } cards { accountID inside mid three passing steal block imgURL } } } """ variables = {"filename": filename} data = asyncio.run( client.execute_async(query=mutation, variables=variables)) return data
class TestAppQueriesSnapshot(TestCase): """Snapshot query test class""" def setUp(self): """setup test method""" self.host = AppConfig.conf_for_current_env()['host'] self.path = AppConfig.conf_for_current_env()['api_path'] self.client = GraphqlClient( endpoint="{}{}".format(self.host, self.path)) def test_levels_response_against_snapshot(self): """Test levels query response data""" query = GqlQuery().fields(['difficulty' ]).query('levels').operation().generate() levels_resp = self.client.execute(query=query) self.assertMatchSnapshot(levels_resp, 'levels_snapshot_resp') def test_equipment_against_snapshot(self): """Testing equipment response data""" query = GqlQuery().fields(['difficulty' ]).query('levels').operation().generate() equipment_resp = self.client.execute(query=query) self.assertMatchSnapshot(equipment_resp, 'equipment_snapshot_resp')
class GraphqlConnect: client = None query = '' token = '' def __init__(self): self.client = GraphqlClient(endpoint=hk_graphql['host']) def generate_token(self): if self.client: self.query = """ mutation { generateAccessToken(data: { email: "{}", password: "******" }) } """.format(hk_graphql['user_email'], hk_graphql['user_password']) print('run generateAccessToken mutation') res = asyncio.run(self.client.execute_async(query=self.query)) if 'data' in res and 'generateAcessToken' in res['data']: self.token = res['data']['generateAcessToken'] print("token: " + self.token) def run_query(self, query): res = None if self.client and query: res = asyncio.run(self.client.execute_async(query=query)) return res
def setUp(self): """Test setup method""" self.fake = Faker() self.fake.add_provider(profile) self.host = AppConfig.conf_for_current_env()['host'] self.path = AppConfig.conf_for_current_env()['api_path'] self.client = GraphqlClient( endpoint="{}{}".format(self.host, self.path))
def __init__(self, token, id): self.id = id self.token = token self.last_live_measurement = None self.last_live_measurement_update = None self.subscription_client = GraphqlClient(endpoint=SUBSCRIPTION_ENDPOINT) self.subscription_task = None self.subscription_start = None
def __init__(self): self.token = os.environ.get('TIBBER_TOKEN') self.checkconfig() headers = { 'Authorization': 'Bearer ' + self.token } self.query_client = GraphqlClient(endpoint=QUERY_ENDPOINT, headers=headers) self.homes = {}
def _initiate_client(self): self._split_auth_key() try: self.__auth = HTTPBasicAuth(self.__username, self.__password) self.__client = GraphqlClient(self.__endpoint, auth=self.__auth) except (HTTPError, ConnectionError) as e: return e else: return self.__client
def __init__(self, api_endpoint='https://smash.gg/api/-/gql', logger=None): self.api_endpoint = api_endpoint self.logger = logger self.gql_client = GraphqlClient(self.api_endpoint) self.algolia_file = 'algolia.json' self.user_agent = 'Mozilla/5.0' self.headers = { 'User-Agent': self.user_agent, 'client-version': '16', }
def test_raises_http_errors_as_exceptions(self, post_mock): """Raises an exception if an http error code is returned in the response.""" response_mock = MagicMock() response_mock.raise_for_status.side_effect = HTTPError() post_mock.return_value = response_mock client = GraphqlClient(endpoint="http://www.test-api.com/") with self.assertRaises(HTTPError): client.execute(query="")
def searchTwitter(siteObjects): client = GraphqlClient(endpoint='http://95.217.162.167:8080/v1/graphql') query = """ query MyQuery { projects { id url title description } } """ hasuraSiteEntries = client.execute(query) for hasuraSiteEntrie in hasuraSiteEntries["data"]["projects"]: siteObjectProperties = {} siteObjectProperties["siteUrl"] = hasuraSiteEntrie["url"] python_tweets = Twython(os.getenv('CONSUMER_KEY'), os.getenv('CONSUMER_SECRET')) query = { 'q': siteObjectProperties["siteUrl"], 'result_type': 'mixed', 'count': 10, 'lang': 'de', } results = python_tweets.search(**query) try: tweetId = results["statuses"][0]["id"] print(siteObjectProperties["siteUrl"]) tweetDetails = python_tweets.show_status(id=tweetId) print("RetweetCount: ", tweetDetails["retweet_count"]) print("Like Count: ", tweetDetails["favorite_count"]) tweetRankingCount = tweetDetails["retweet_count"] + \ tweetDetails["favorite_count"] print("Ranking Count: ", tweetRankingCount) except: print("not working") # try: # client = GraphqlClient( # endpoint='http://95.217.162.167:8080/v1/graphql') # variables = { # "url": siteObjectProperties["siteUrl"], "twitterActions": tweetRankingCount} # updateQuery = """ # mutation updateProject($url: String, $twitterActions: Int) { # update_projects(where: {url: {_eq: $url}}, _set: {twitterActions: $twitterActions}) { # affected_rows # } # } # """ # graphQlResult = client.execute(updateQuery, variables) # print(graphQlResult) # except: # print("GraphQL Import Error") # print("Parsing Error - Ignore URL: ", hasuraSiteEntrie["url"]) # siteObjects.append(siteObjectProperties) return siteObjects
class Ruter(hass.Hass): def initialize(self): # Create the GQL client ENDPOINT = self.args[ 'gql_server'] # One common stop for all public transport in Norway & Sweden self.client = GraphqlClient(endpoint=ENDPOINT) if self.args['logging'] is True: self.log('Initialized GQL client for {}'.format(ENDPOINT), ascii_encode=False) self.header = { "ET-Client-Name": self.args['ET-Client-Name'], "cache-control": "no-cache, no-store, max-age=0, must-revalidate", "content-type": "application/json;charset=utf-8", "expires": "0", "pragma": "no-cache" } now = self.get_now() interval = int(self.args["interval"]) #self.run_every(self.updateState, now, interval * 60) def query(self, query, header) -> dict: payload = self.client.execute(query=query, headers=header) return payload def updateState(self, kwargs=None): departures = self.queryNextDeparturesFromYourLocalStop() self.set_app_state(self.args['entity'], { "state": "", "attributes": departures }) def queryNextDeparturesFromYourLocalStop(self): stop_id = self.args['local_stop_id'] # Execute the query header = self.header query = GRAPHQL_NEXT_DEPARTURE.replace('$stop_place', stop_id) data = self.client.query(query=query, headers=header) d = data['data'] stop_name = d['stopPlace']['name'] table = defaultdict(list) for call in d['stopPlace']['estimatedCalls']: table[call['expectedDepartureTime']].append( {'destination': call['destinationDisplay']['frontText']}) table[call['expectedDepartureTime']].append({ 'transportMode': call['serviceJourney']['line']['transportMode'] }) table[call['expectedDepartureTime']].append( {'publicCode': call['serviceJourney']['line']['publicCode']}) if self.args['logging'] is True: for key in table: self.log(key + ': ' + str(table[key]), ascii_encode=False) return table
def test_execute_query_with_variables(self, requests_mock): """Sends a graphql POST request with variables.""" client = GraphqlClient(endpoint="http://www.test-api.com/") query = "" variables = {"id": 123} client.execute(query, variables) requests_mock.post.assert_called_once_with( "http://www.test-api.com/", json={"query": query, "variables": variables}, headers={}, )
def pairStats(pair_address: str): subgraph_url = subgraph_for(pair_address) if not subgraph_url: return {} client = GraphqlClient(endpoint=subgraph_url) response = client.execute(query=STATS_QUERY, variables={"pairAddress": pair_address}) if response['data'] and response['data']['pairDayDatas'] and len(response['data']['pairDayDatas']) > 0: return response['data']['pairDayDatas'][0] return None
def __init__(self, token, data): self.id = data['id'] self.token = token self.app_nickname = data.get('appNickname') self.features = data.get('features') self.realtime_consumption_enabled = False if self.features is not None: self.realtime_consumption_enabled = self.features.get('realTimeConsumptionEnabled') self.last_price = None self.last_price_update = None self.subscription_rt = None headers = { 'Authorization': 'Bearer ' + self.token } self.query_client = GraphqlClient(endpoint=QUERY_ENDPOINT, headers=headers, timeout=3.0)
def recent_releases(): query = """ query { viewer { repositories(first: 100, privacy: PUBLIC) { pageInfo { hasNextPage endCursor } nodes { name releases(last:1) { totalCount nodes { name publishedAt url } } } } } } """ client = GraphqlClient(endpoint="https://api.github.com/graphql") data = client.execute( query=query, headers={"Authorization": "Bearer {}".format(TOKEN)} ) releases = [] repos = set() for repo in data["data"]["viewer"]["repositories"]["nodes"]: if repo["releases"]["totalCount"] and repo["name"] not in repos: repos.add(repo["name"]) releases.append( { "repo": repo["name"], "release": repo["releases"]["nodes"][0]["name"], "url": repo["releases"]["nodes"][0]["url"], "published": repo["releases"]["nodes"][0]["publishedAt"].split("T")[ 0 ], } ) releases = sorted(releases, key=lambda r: r["published"], reverse=True,) return releases[:5]
def __init__(self, cfg_json_filename, auth_token_filename="auth_token.json"): self.access_token = None with open(cfg_json_filename, "r") as cfg_fp: cfg_json = json.load(cfg_fp) username = cfg_json["Username"] password = cfg_json["Password"] self.pool_id = cfg_json["CognitoPoolId"] self.pool_region = cfg_json["CognitoPoolRegion"] client_id = cfg_json["CognitoClientId"] sensordb_api_url = cfg_json["SensorDbApiUrl"] self.bucket = cfg_json["S3DownloadsBucket"] if "IdentityPoolId" in cfg_json: self.identity_pool_id = cfg_json["IdentityPoolId"] if "AccountId" in cfg_json: self.account_id = cfg_json["AccountId"] if "CognitoClientSecret" in cfg_json: client_secret = cfg_json["CognitoClientSecret"] else: client_secret = None if os.path.isfile(auth_token_filename): with open(auth_token_filename, "r") as token_fp: result = json.load(token_fp) expires_in = timedelta( seconds=int(result['AuthenticationResult']['ExpiresIn'])) header_date = datetime.strptime( result['ResponseMetadata']['HTTPHeaders']['date'], '%a, %d %b %Y %H:%M:%S GMT') print(header_date + expires_in, datetime.utcnow()) if header_date + expires_in > datetime.utcnow(): self.access_token = result['AuthenticationResult'][ 'AccessToken'] self.id_token = result['AuthenticationResult']['IdToken'] if self.access_token is None or self.id_token is None: cognito_client = boto3.client('cognito-idp', self.pool_region) self.awssrp = AWSSRP(username, password, self.pool_id, client_id, client=cognito_client, client_secret=client_secret) result = self.awssrp.authenticate_user(client=cognito_client) with open(auth_token_filename, "w") as token_fp: json.dump(result, token_fp, indent=2) self.access_token = result['AuthenticationResult']['AccessToken'] self.id_token = result['AuthenticationResult']['IdToken'] self.client = GraphqlClient( sensordb_api_url, headers={'authorization': self.access_token})
def __init__(self, queue, sync, signals_queue): self.queue = queue self.signals_queue = signals_queue self.sync = sync endpoint = 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2' self.client = GraphqlClient(endpoint=endpoint) self.loop = asyncio.new_event_loop() self.itter_time = 30 self.loginfo = logging.getLogger(' UniSwap ').warning self.coingecko = CoinGecko() self.exchange_name = 'Uniswap.com' self.gth_pair_id = '0xb38be7fd90669abcdfb314dbddf6143aa88d3110' self.last_trade_timestamp = dt.utcnow() - timedelta(minutes=5) self.swaps_check_time = 10 self.counted_swaps = collections.deque(maxlen=1000)
def test_execute_basic_query(self, requests_mock): """Sends a graphql POST request to an endpoint.""" client = GraphqlClient(endpoint="http://www.test-api.com/") query = """ { tests { status } } """ client.execute(query) requests_mock.post.assert_called_once_with( "http://www.test-api.com/", json={"query": query}, headers={} )
class ApiAccess(): #getRickAndMortyApiUrl() def __init__(self, url): # Instantiate the client with an endpoint obtained from configuration file. self.client = GraphqlClient(endpoint=url) def get_query_results(self): return self.client.execute(query=all_characters_query) def execute_search_all(self): """ Searches all the charactesr from GraphQL API. It gets name, image, status, gender and species """ # Synchronous request data = self.get_query_results() # check whether execution was successful if data.get('data').get('characters') is not None: results = data.get('data').get('characters').get('results') else: results = [] return results
async def test_subscribe(self, mock_connect): """Subsribe a GraphQL subscription.""" mock_websocket = mock_connect.return_value.__aenter__.return_value mock_websocket.send = AsyncMock() mock_websocket.__aiter__.return_value = [ '{"type": "data", "id": "1", "payload": {"data": {"messageAdded": "one"}}}', '{"type": "data", "id": "1", "payload": {"data": {"messageAdded": "two"}}}', ] client = GraphqlClient(endpoint="ws://www.test-api.com/graphql") query = """ subscription onMessageAdded { messageAdded } """ mock_handle = MagicMock() await client.subscribe(query=query, handle=mock_handle) mock_handle.assert_has_calls( [ call({"data": {"messageAdded": "one"}}), call({"data": {"messageAdded": "two"}}), ] )
class MembershipsRepository: def __init__(self): headers = { "content-type": "application/json", "apollographql-client-name": "playground", "apollographql-client-version": "1.0", } self.gql_client = GraphqlClient(endpoint="https://www.prodigygame.net/graphql/", headers=headers) def get_grades(): # Create the query string and variables required for the request. query = """ query FIND_GRADE ($id: ID!) { grade(id: $id) { name } } """ variables = { "id": 1 } # Synchronous request response = self.gql_client.execute(query=query, variables=variables) data = response.get("data") return data