def createtransport(access_token: str) -> AIOHTTPTransport: return AIOHTTPTransport(url='https://graphql.anilist.co', headers={ 'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json', 'Accept': 'application/json', })
def __init__(self, auth_token): transport = AIOHTTPTransport( url="https://api.github.com/graphql", headers={'Authorization': 'token {}'.format(auth_token)}) self.client = Client(transport=transport, fetch_schema_from_transport=True) self.gql_query = GQLQuery(config.DIR_PATH + "/queries/")
def get_course(subj: str, course_id: str) -> dict: # Select your transport with a defined url endpoint transport = AIOHTTPTransport(url="https://searchneu.com/graphql") # Create a GraphQL client using the defined transport client = Client(transport=transport, fetch_schema_from_transport=True) # Provide a GraphQL query query = gql(""" query getCourse ($subj: String!, $course_id: String!) { class(subject: $subj, classId: $course_id) { latestOccurrence { name desc } } } """) # Execute the query on the transport result = client.execute(query, variable_values={ "subj": subj, "course_id": str(course_id) }) return result
def __init__(self): self.__map = {} self.__users = {} self.__invitations = {} self.__teams = {} self.__client = Github(self.__token) self.__client = self.__client.get_organization(self.__organizaton) self.__transport = AIOHTTPTransport( url=self.__url, headers={"Authorization": f"token {self.__token}"}) self.__setup_complete = False
def __init__(self, etos): """Initialize the async io transport. :param etos: ETOS Library instance. :type etos: :obj:`etos_lib.ETOS` """ self.etos = etos self.transport = AIOHTTPTransport( url=self.etos.debug.graphql_server, timeout=self.etos.debug.default_http_timeout, )
def graphql(self, query: str, variables=None): transport = AIOHTTPTransport( url=f"{FAUNADB_DOMAIN}/graphql", headers=self._headers, ) graphql_client = Client(transport=transport) graphql_query = gql(query) graphql_variables = variables or {} result = graphql_client.execute(graphql_query, variable_values=graphql_variables) errors = result.get("errors", []) if any(errors): raise Exception(errors) return result
def fetch_safe_mods(self, graph_endpoint, from_block, to_block, page_size=1000): self.logger.info(f"Fetching safe modes from {graph_endpoint}") transport = AIOHTTPTransport(url=graph_endpoint) client = Client(transport=transport, fetch_schema_from_transport=True) def fetch_page(from_block, to_block, first, skip): query = gql(f""" query{{ modifySAFECollateralizations(first: {first}, skip: {skip}, where: {{createdAtBlock_gte: {from_block}, createdAtBlock_lte: {to_block}}}) {{ safeHandler, createdAtBlock, collateralType {{ id }} }} }} """) result = client.execute(query) return result['modifySAFECollateralizations'] page_num = 0 page = fetch_page(from_block, to_block, page_size, page_num * page_size) all_pages = [] while page: all_pages.extend(page) page_num += 1 page = fetch_page(from_block, to_block, page_size, page_num * page_size) return all_pages
async def main(): transport = AIOHTTPTransport(url='https://countries.trevorblades.com/graphql') # Using `async with` on the client will start a connection on the transport # and provide a `session` variable to execute queries on this connection async with Client( transport=transport, fetch_schema_from_transport=True, ) as session: # Execute single query query = gql(''' query getContinents { continents { code name } } ''') result = await session.execute(query) print(result)
async def main(): # Set up required api stuff via http transport = AIOHTTPTransport(url=API_URL) client = Client(transport=transport, fetch_schema_from_transport=False) async with client as session: logger.info("Checking for currenlty running session") result = await session.execute(get_sessions) logger.debug(f'<-- {pformat(result)}') prev_session_id = None if not result["sessions"] else result[ "sessions"][0]["sessionId"] if prev_session_id: logger.info( f'Found previous session with ID: {prev_session_id}, ending it' ) variables = {"sessionId": prev_session_id} result = await session.execute(end_session, variables) logger.debug(f"<-- {pformat(result)}") new_session_id = str(uuid.uuid4()) logger.info(f'Creating new session with ID: {new_session_id}') result = await session.execute( create_all_and_start_session, variable_values={"sessionId": new_session_id}) logger.debug(f'<-- {pformat(result)}') # Connect via websocket to handle real time mutations/subscriptions # NB API doesnt respond to messages sent via websocket. Maybe this is just normal? # Either way it's probably fine as errors should still be thrown transport = WebsocketsTransport(url=API_URL) client = Client(transport=transport, fetch_schema_from_transport=False) async with client as session: # await asyncio.gather( # handle_subscriptions(session), # handle_soldiers(session), # return_exceptions=False # ) asyncio.create_task(handle_entities(session)) await handle_subscriptions(session)
def parse(self, inventory, loader, path, cache=True): ''' parses the inventory file ''' super(InventoryModule, self).parse(inventory, loader, path, cache) self._options = self._read_config_data(path) # print(self._options) self.api_server = self.get_option('api_server') self.api_token = self.get_option('api_token') self.main_group = self.get_option('main_group') self.environment = self.get_option('environment') try: # Select your transport with a defined url endpoint transport = AIOHTTPTransport( url="https://{}/graphql".format(self.api_server)) # Create a GraphQL client using the defined transport client = Client(transport=transport, fetch_schema_from_transport=True) # Provide a GraphQL query query = gql(''' query inventory { inventory(groupName: "''' + self.main_group + '''", environment: "''' + self.environment + '''"){ groups { ansible_group_name variables parent { ansible_group_name } } servers { hostname variables group_names } } } ''') # Execute the query on the transport data = client.execute(query) # print(data["inventory'"]["servers"]) # print("hello") # self.inventory.add_group(data["group"]["name"]) # self.inventory.add_host("test") except Exception as e: raise AnsibleParserError(e) if not data: raise AnsibleParserError('Parsed empty Graphql requests') elif not isinstance(data, MutableMapping): raise AnsibleParserError( 'YAML inventory has invalid structure, it should be a dictionary, got: %s' % type(data)) elif data.get('plugin'): raise AnsibleParserError( 'Plugin configuration YAML file, not YAML inventory') # self._parse_group(data["groupByName"]["ansible_group_name"], data["groupByName"]) self._parse_servers(data["inventory"]["servers"], data["inventory"]["groups"])
def __init__(self): # TODO remove once PR 135 makes it into gql asyncio.set_event_loop(asyncio.new_event_loop()) transport = AIOHTTPTransport(url="https://sleeper.app/graphql") self.client = Client(transport=transport, fetch_schema_from_transport=False)
def get_vars(self, loader, path, entities, cache=True): ''' parses the inventory file ''' if not isinstance(entities, list): entities = [entities] super(VarsModule, self).get_vars(loader, path, entities) if 'api_server' not in OPTIONS.keys(): self.loader = loader config_file_path = path + "/graphql_plugin.yaml" self.display.v('Load vars plugin configuration file {}'.format( config_file_path)) if self.verify_file(config_file_path): self.parse_config_file(config_file_path) else: return {} self.api_server = OPTIONS['api_server'] self.api_token = OPTIONS['api_token'] data = {} for entity in entities: if isinstance(entity, Host): subdir = 'host_vars' elif isinstance(entity, Group): subdir = 'group_vars' else: raise AnsibleParserError( "Supplied entity must be Host or Group, got %s instead" % (type(entity))) if isinstance(entity, Group): key = "Group_%s" % entity.name if cache and key in FOUND: self.display.v('Load vars from cache') new_data = FOUND[key] else: self.display.v('Load vars from graphql api {}'.format( self.api_server)) try: # Select your transport with a defined url endpoint transport = AIOHTTPTransport( url="https://{}/graphql".format(self.api_server)) # Create a GraphQL client using the defined transport client = Client(transport=transport, fetch_schema_from_transport=True) # Provide a GraphQL query query = gql(''' query { groupByName(groupName: "''' + entity.name + '''") { ansible_group_name variables } } ''') # Execute the query on the transport new_data = client.execute(query) if new_data["groupByName"] != None: new_data = new_data["groupByName"]["variables"] else: new_data = {} FOUND[key] = new_data except Exception as e: raise AnsibleParserError(e) data = combine_vars(data, new_data) return data
from gql import gql, Client, AIOHTTPTransport import json graphql_url = "<placeholder>" transport = AIOHTTPTransport(url=graphql_url) client = Client(transport=transport, fetch_schema_from_transport=True) add_result_mutation = gql( """ mutation add_result_mutation( $communityName: String! $player1Name: String! $player2Name: String! $date: timestamptz! $player1Goals: Int! $player2Goals: Int! $extraTime: Boolean! ) { insert_results( objects: { community: { data: { name: $communityName } on_conflict: { constraint: communities_name_key update_columns: name } } date: $date player1: { data: { name: $player1Name
def sync_registry(): logger.info("Synchronizing with the contract registry") session: Session = sessionmaker(bind=engine)() repository = AnnotationsRepository(session) gql_client = Client(transport=AIOHTTPTransport(url=PAN_SUBGRAPH)) offset = 0 limit = 100 annotations = fetch_registry_annotations( client=gql_client, offset=offset, limit=limit ) while annotations: # TODO: This takes long - parallelize for annotation in annotations: # skip if annotation already in DB try: annotation_exists = ( session.query(Annotation) .filter_by(subject_id=annotation["cid"]) .scalar() ) except MultipleResultsFound: annotation_exists = True if annotation_exists is not None: continue # fetch new annotation from IPFS and create DB object try: content = repository.get_subgraph_annotation( annotation_id=annotation["cid"] )[0] except IndexError: continue # content = repository.get_by_cid(annotation_id=annotation["cid"], published=True)[0] annotation_obj = Annotation( context=content["@context"], credential_type=content["type"], issuer=content["issuer"].split(":")[2], issuance_date=dateutil.parser.parse(content["issuanceDate"]), original_content=content["credentialSubject"]["content"], annotation_content=content["credentialSubject"]["annotation"], proof_type=content["proof"]["type"], proof_date=dateutil.parser.parse(content["proof"]["created"]), proof_purpose=content["proof"]["proofPurpose"], verification_method=content["proof"]["verificationMethod"], proof_jws=content["proof"]["jws"], subject_id=annotation["cid"], published=True, ) try: session.add(annotation_obj) session.commit() except SQLAlchemyError as e: logger.error(f"Encountered error during database commit: {e}") session.rollback() offset += limit annotations = fetch_registry_annotations( client=gql_client, offset=offset, limit=limit )
def __init__(self, url=ENDPOINT) -> None: headers = {"Authorization": f"Bearer {ANNICT_TOKEN}"} self.transport = AIOHTTPTransport(url=url, headers=headers) self.client = Client(transport=self.transport, fetch_schema_from_transport=True)
def __init__(self, session: Session): self.session = session self.client = Client(transport=AIOHTTPTransport(url=PAN_SUBGRAPH))
# formatter = '%(asctime)s : %(levelname)s : %(message)s' # logging.basicConfig(format=formatter, level=logging.INFO) infura = "https://mainnet.infura.io/v3/4e3b160a19f845858bd42d301f00222e" web3 = Web3(Web3.HTTPProvider(infura)) print(web3.isConnected()) import warnings warnings.filterwarnings("ignore") ENDPOINT = "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2" transport = AIOHTTPTransport(url=ENDPOINT) client = Client(transport=transport, fetch_schema_from_transport=True) # # Globals dirname = os.path.dirname(__file__) if not os.path.isdir(os.path.join(dirname, "../", "data")): os.mkdir(os.path.join(dirname, "../", "data")) if not os.path.isdir(os.path.join(dirname, "../", "data", "uniswapv2")): os.mkdir(os.path.join(dirname, "../", "data", "uniswapv2")) datafolder = os.path.join(dirname, "../", "data", "uniswapv2") current_block = web3.eth.getBlock("latest")["number"]
def __init__(self): # Select your transport with a defined url endpoint transport = AIOHTTPTransport(url="http://localhost/graphql") # Create a GraphQL client using the defined transport self.client = Client(transport=transport, fetch_schema_from_transport=True)
async def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: if not tracker.latest_message['entities']: # no acronym was found in the latest user intent dispatcher.utter_message("I couldn't find a search term in '" + tracker.latest_message["text"] + "'. I'm am still a work in progress :)") # TODO: Log failed intent return [] # Get entity from latest message searchTerm = tracker.latest_message['entities'][0]['value'] query = re.sub(r'[^\w\s]', '', searchTerm) transport = AIOHTTPTransport( url="http://sfe-chatbot-gateway-api:1337/graphql") async with Client(transport=transport, fetch_schema_from_transport=True) as session: gqlQuery = gql(""" query getSearchResults($query: String, $locale: String) { gatewaySearch(query: $query, locale: $locale) { _id _score _source { name parent_page header_en description_en } } } """) params = {"query": query, "locale": "en"} results = await session.execute(gqlQuery, variable_values=params) # print( results ) # sys.stdout.flush() results = results["gatewaySearch"] resultsCount = len(results) response = None if resultsCount > 0: # TODO: Bilingual response = "I found " + str(resultsCount) + " result" + ( "s" if resultsCount > 1 else "") + " for \"" + searchTerm + "\". Were you looking for:" maxResults = 2 resultsCount = 0 for result in results: path = "/en/" + (result["_source"]["parent_page"] + "/" if result["_source"]["parent_page"] is not None else "") + result["_source"]["name"] response += "\n\n[" + result["_source"][ "header_en"] + "](" + path + ")" resultsCount += 1 if resultsCount >= maxResults: more = "/en/search/" + quote(searchTerm) response += "\n\n[More...](" + more + ")" break # print( response ) # sys.stdout.flush() dispatcher.utter_message(text=response) return [] else: response = "Hmm, I couldn't seem to find anything on the gateway related to \"" + query + "\"." dispatcher.utter_message(template="utter_search_results_none", gw_search_query=query, tracker=tracker) return []
from gql import gql, Client, AIOHTTPTransport from gql.transport.exceptions import TransportQueryError from schedule import Schedule, Event from os import getenv import json transport = AIOHTTPTransport( url=getenv('C3D_URL', 'https://data.c3voc.de/graphql'), headers={'Authorization': getenv('C3D_TOKEN', 'Basic|Bearer XXXX')}) #transport = AIOHTTPTransport(url="http://localhost:5001/graphql") # Create a GraphQL client using the defined transport client = Client(transport=transport, fetch_schema_from_transport=True) def create_conference(schedule: Schedule): conference = schedule.conference() input = { 'conference': { 'acronym': conference['acronym'], 'title': conference['title'], 'startDate': conference['start'], 'endDate': conference['end'], 'daysUsingId': { 'create': [{ 'index': day['index'], 'startDate': day['day_start'], 'endDate': day['day_end'] } for day in schedule.days()] },
import json import pathlib import re import os import asyncio from bs4 import BeautifulSoup from gql import gql, Client, AIOHTTPTransport import requests root = pathlib.Path(__file__).parent.resolve() TOKEN = "bearer " + os.getenv("GH_GQL_API_TOKEN", "") # Select your transport with a GitHub url endpoint transport = AIOHTTPTransport(url="https://api.github.com/graphql", headers={"Authorization": TOKEN}) client = Client( transport=transport, fetch_schema_from_transport=True, ) def replace_chunk(content, marker, chunk, inline=False): r = re.compile( r"<!\-\- {} starts \-\->.*<!\-\- {} ends \-\->".format(marker, marker), re.DOTALL, ) if not inline: chunk = "\n{}\n".format(chunk) chunk = "<!-- {} starts -->{}<!-- {} ends -->".format(
#!/usr/bin/env python3 from gql import gql, Client, AIOHTTPTransport from os import environ from sys import argv transport = AIOHTTPTransport( url="https://api.github.com/graphql", headers={"Authorization": "bearer " + environ["GITHUB_TOKEN"]}, ) client = Client(transport=transport, fetch_schema_from_transport=True) def make_request(after=None): if after is None: query = gql(""" query { user(login: \"""" + argv[1] + """\") { issues(first: 100) { edges { node { url } } pageInfo { endCursor hasNextPage hasPreviousPage startCursor } totalCount
from gql import gql, Client, AIOHTTPTransport import json import os GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN") # Select your transport with a defined url endpoint transport = AIOHTTPTransport( url="https://api.github.com/graphql", headers={"Authorization": "bearer {}".format(GITHUB_TOKEN)}, ) # Create a GraphQL client using the defined transport client = Client(transport=transport, fetch_schema_from_transport=True) edges = [] # Provide a GraphQL query query = gql(""" query getStarredRepos { user(login: "******") { starredRepositories(first: 100) { pageInfo { hasNextPage endCursor } edges { starredAt node {
from gql import gql, Client, AIOHTTPTransport # Select your transport with a defined url endpoint transport = AIOHTTPTransport(url="https://countries.trevorblades.com/") # Create a GraphQL client using the defined transport client = Client(transport=transport, fetch_schema_from_transport=True) # Provide a GraphQL query query = gql( """ query getContinents { continents { code name } } """ ) # Execute the query on the transport result = client.execute(query) print(result)