def create_series(series_name, series_subtitle, image_file, bucket, prefix, awscredsfile, graphcoolcredsfile, graphcoolserviceid): series = Series.fromBasic(series_name, series_subtitle) if image_file is None: print("You need to specify an image file or set the default-image flag") exit(1) s3_url = None if image_file != "__default__": s3_url = upload_to_s3(image_file, bucket, awscredsfile, prefix) series.image3x2url = s3_url graphcool_creds = yaml.load(open(graphcoolcredsfile)) client = GraphQLClient('https://api.graph.cool/simple/v1/{}'.format(graphcoolserviceid)) client.inject_token("Bearer " + graphcool_creds['graphcooltoken']) # Look up the series by it's name (which is unique in graphcool) result = client.execute(find_series_by_name(), {"name": series.name}) parsed_json = json.loads(result) if parsed_json['data']['Series'] is None: creation_result = client.execute(create_series_query(), series.asDict()) print(json.loads(creation_result)) else: print("Series by this name already exists.")
def all_historical_job_metric(graphql_host, graphql_port, graphql_auth): # graphql connection graphql_url = 'http://' + graphql_host + ':' + str( graphql_port) + '/graphql' url = os.environ.get('GRAPHQL_URL', graphql_url) client = GraphQLClient(url) client.inject_token(os.environ.get('GRAPHQL_AUTH', graphql_auth)) output = graphql_queries.query_AllHistoricaJobs(client) df = pd.DataFrame() allJobs = json.loads(output).get('data', {}).get('allHistoricalJobs', {}) jobs = allJobs.get('HistoricalJobs', []) for j in jobs: cols = [1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 44, 45, 58] #print(j['jobid']) df_temp = pd.DataFrame(json_normalize(j)) #df.drop(df.columns[cols],axis=1,inplace=True) df_temp['submission_time_ms'] = j['submission_time_ms'] df_temp['slots'] = j['slots'] df = df.append(df_temp, sort=True) #pd.to_datetime(df['time'].values, unit='ms', utc=True) df.set_index('submission_time_ms', append=False, inplace=True) #df.index = df.index.to_datetime() # Use the following for values like 3.5G. Will remove the 'G' at the end. # pd.to_numeric(df['m_mem_used'].str.replace('[^\d.]', ''), errors='coerce') return (df[[ 'job_number', 'owner', 'slots', 'qname', 'project', 'usage.ru_wallclock', 'usage.cpu', 'hostname' ]])
def lambda_handler(event, context): client = GraphQLClient("https://api.faros.ai/v0/graphql") client.inject_token("Bearer {}".format(event["farosToken"])) query = '''{ lambda_functionConfiguration { data { functionArn functionName vpcConfig { subnetIds } farosAccountId farosRegionId } } }''' response = client.execute(query) response_json = json.loads(response) functions = response_json["data"]["lambda_functionConfiguration"]["data"] return [ f for f in functions if not f["vpcConfig"] or not f["vpcConfig"]["subnetIds"] ]
class GithubClient: def __init__(self, api_token, api_server_url='https://api.github.com/graphql'): """Client to interact with github graphql API Parameters ---------- api_token : str Github API token of user api_server_url : str Github API server url (default is 'https://api.github.com/graphql') """ self._api_token = api_token self._client = GraphQLClient(api_server_url) if api_token: self._client.inject_token('bearer ' + api_token) def get(self, query): """Make graphql query to github API Parameters ---------- query : str graphql query Returns ------- response_data : dict or list json decoded reponse of api call """ result = self._client.execute(query) data = json.loads(result) return data
def lambda_handler(event, context): client = GraphQLClient("https://api.faros.ai/v0/graphql") client.inject_token("Bearer {}".format(event["farosToken"])) query = '''{ iam_userDetail { data { userId userName mfaDevices { data { serialNumber } } farosAccountId farosRegionId } } }''' response = client.execute(query) response_json = json.loads(response) users = response_json["data"]["iam_userDetail"]["data"] return [{ "name": u["userName"], "id": u["userId"], "farosAccountId": u["farosAccountId"], "farosRegionId": u["farosRegionId"] } for u in users if not u["mfaDevices"]["data"]]
def get_client(self): token = self.refresh_token() if token: client = GraphQLClient('{}/graphql/{}'.format(self._url, self._path)) client.inject_token(token) return client return None
def lambda_handler(event, context): client = GraphQLClient("https://api.faros.ai/v0/graphql") client.inject_token("Bearer {}".format(event["farosToken"])) query = '''{ ec2_instance { data { instanceId tags { key } farosAccountId farosRegionId } } }''' response = client.execute(query) response_json = json.loads(response) instances = response_json["data"]["ec2_instance"]["data"] required_keys = frozenset(event["params"]["keys"].split(",")) tagless_instances = [{ "instance": i, "missingKeys": missing_tags(required_keys, frozenset([t["key"] for t in i["tags"]])) } for i in instances] tagless_instances = [i for i in tagless_instances if i["missingKeys"]] return tagless_instances
def run_simulation(config): session_id = config[SESSION_ID] app_state = get_app_state(session_id) app_state[CONFIG] = config set_status(session_id, STARTING) env = try_make_env(config[ENVIRONMENT_ID]) if (env == None): set_status(ERROR, ["Can't load environment: " + config[ENVIRONMENT_ID]]) return app_state[STATUS] app_state[ENVIRONMENT] = env agents = config[AGENTS] uri = agents[0][URI] token = agents[0][TOKEN] client = GraphQLClient(uri) client.inject_token("Bearer " + token) app_state[CLIENT] = client thread = threading.Thread(target=run_episodes, args=( session_id, 99, )) print("thread: " + repr(thread)) app_state[THREAD] = thread thread.start() return app_state[STATUS]
def get_github_client(version): """ Create a Github client for the given Github API version using credentials provided as environment variables """ if version == 3: token = os.getenv('GITHUB_TOKEN') client_id = os.getenv('GITHUB_CLIENT_ID') client_secret = os.getenv('GITHUB_CLIENT_SECRET') if token is None or token == '': raise Exception('You need to set GITHUB_TOKEN using environment variables') if client_id is None or client_id == '': raise Exception('You need to set GITHUB_CLIENT_ID using environment variables') if client_secret is None or client_secret == '': raise Exception('You need to set GITHUB_CLIENT_SECRET using environment variables') gh = Github(login_or_token=token, client_id=client_id, client_secret=client_secret, per_page=100) #gh._Github__requester = CachingRequester(gh._Github__requester) return gh elif version == 4: github_token = os.getenv('GITHUB_TOKEN') if github_token is None or github_token == '': raise Exception('You need to set GITHUB_TOKEN using environment variables') graph = GraphQLClient('https://api.github.com/graphql') graph.inject_token(github_token) return graph else: raise ValueError('Invalid API version {}, choose between 3 and 4'.format(version))
def delete_series(series_id, graphcoolcredsfile, graphcoolserviceid): graphcool_creds = yaml.load(open(graphcoolcredsfile)) client = GraphQLClient( 'https://api.graph.cool/simple/v1/{}'.format(graphcoolserviceid)) client.inject_token("Bearer " + graphcool_creds['graphcooltoken']) search_result = json.loads( client.execute(find_series_by_id(), {"id": series_id})) if search_result['data']['Series'] is None: print("No series found with the id: {}".format(series_id)) exit(1) series = search_result['data']['Series'] sermon_count = len(series['sermons']) if sermon_count > 0: print( "Series \"{}\" contains {} sermons - cascading deleting has not been implemented. Sorry." .format(series['name'], sermon_count)) exit(1) deletion_result = json.loads( client.execute(delete_series_by_id(), {"id": series_id})) if deletion_result['data']['deleteSeries']: print("Deleted series \"{}\"".format( deletion_result['data']['deleteSeries']['name']))
def open(): access_token = "7e0118b3603a7c3a54435db7" bearer_token = 'Bearer ' + access_token client = GraphQLClient("https://wip.chat/graphql") client.inject_token(bearer_token) result = client.execute(''' query{ user(id: "73") { username products { name id } } } ''') products = json.loads(result) return render_template('open.html', data=products)
def send_to_graphql(logger, studentID, roomID, token, score, classification): ENDPOINT = "http://learnlab-server.herokuapp.com/" #logger.info("sending via graphql") try: auth = "Bearer " + token client = GraphQLClient(ENDPOINT) client.inject_token(auth) query = '''mutation addEngagement($room_id:ID!, $student_id:ID!, $score:Int!, $classification:String!, $created_at:Date!) { upsertEngagementCurrent(room_id: $room_id, student_id: $student_id, score: $score, classification: $classification, created_at: $created_at) { success, message } }''' variables = { "room_id": roomID, "student_id": studentID, "score": score, "classification": classification, "created_at": datetime.today().strftime('%m/%d/%Y %H:%M:%S') } # logger.info("Executing room_id: {}, student_id: {}, score: {}, classification: {}".format(roomID, studentID, score, classification)) # logger.info("Query: ".format(query)) data = client.execute(query=query, variables=variables) # logger.info(data) except Exception as e: logger.info("ERROR: {}".format(e))
def lambda_handler(event, context): client = GraphQLClient("https://api.faros.ai/v0/graphql") client.inject_token("Bearer {}".format(event["farosToken"])) query = '''{ ec2_instance { data { instanceId state { name } launchTime farosAccountId farosRegionId } } }''' response = client.execute(query) response_json = json.loads(response) instances = response_json["data"]["ec2_instance"]["data"] cutoff = int(event["params"]["num_days"]) return [ i for i in instances if i["state"]["name"] == "running" and days_diff(i["launchTime"]) > cutoff ]
def test_prisma_python_graphql_client(live_server, get_user_from_admin): """ Know more at: https://github.com/prisma/python-graphql-client """ some_user = get_user_from_admin created_token = Token.objects.create( key="6c5d69c150b32dcb9c746672c0185d6d8454ca21", user=some_user) client = GraphQLClient(f"{live_server.url}/api/graphql/") query = """ query { allCategories{ id name ingredients { id name notes } } } """ try: client.execute(query) except Exception as e: assert type(e) == HTTPError assert e.code == 401 client.inject_token(f"Token {created_token}") result = client.execute(query) assert result == '{"data":{"allCategories":[]}}'
class HasuraClient: def __init__(self): self.HASURA_GRAPHQL_URL = os.environ['HASURA_GRAPHQL_URL'] self.HASURA_GRAPHQL_ADMIN_SECRET = os.environ['HASURA_GRAPHQL_ADMIN_SECRET'] self.graphql_client = GraphQLClient(self.HASURA_GRAPHQL_URL) self.graphql_client.inject_token( self.HASURA_GRAPHQL_ADMIN_SECRET, 'x-hasura-admin-secret' )
def get_client(client_url=None,api_key=None,cfig=None): if not (client_url and api_key): if not cfig: cfig=config() client_url=cfig['client'] api_key=cfig['api_key'] client=GraphQLClient(client_url) client.inject_token(f'Bearer {api_key}') return client
class GqlApi(object): def __init__(self, url, token=None): self.url = url self.token = token self.client = GraphQLClient(self.url) if token: self.client.inject_token(token) def query(self, query, variables=None): try: # supress print on HTTP error # https://github.com/prisma-labs/python-graphql-client # /blob/master/graphqlclient/client.py#L32-L33 with open(os.devnull, 'w') as f, contextlib.redirect_stdout(f): result_json = self.client.execute(query, variables) except Exception as e: raise GqlApiError( 'Could not connect to GraphQL server ({})'.format(e)) result = json.loads(result_json) if 'errors' in result: raise GqlApiError(result['errors']) if 'data' not in result: raise GqlApiError(( "`data` field missing from GraphQL" "server response.")) return result['data'] def get_resource(self, path): query = """ query Resource($path: String) { resources: resources_v1 (path: $path) { path content sha256sum } } """ try: resources = self.query(query, {'path': path})['resources'] except GqlApiError: raise GqlGetResourceError( path, 'Resource not found.') if len(resources) != 1: raise GqlGetResourceError( path, 'Expecting one and only one resource.') return resources[0]
class GithubClient: def __init__(self, api_token): self.api_token = api_token self.client = GraphQLClient('https://api.github.com/graphql') self.client.inject_token('bearer ' + api_token) def get(self, query): result = self.client.execute(query) data = json.loads(result) return data
def upload_to_graphcool(sermon, graphcoolcredsfile, graphcoolServiceID, s3_url): print("Uploading to Graphcool") graphcool_creds = yaml.load(open(graphcoolcredsfile)) client = GraphQLClient('https://api.graph.cool/simple/v1/{}'.format(graphcoolServiceID)) client.inject_token("Bearer " + graphcool_creds['graphcooltoken']) # Look up the sermon by it's URL (which is unique in graphcool) result = client.execute(find_sermon_by_url(), {"url": sermon.public_url}) parsed_json = json.loads(result) print(parsed_json) if parsed_json['data'] == None: print("There was a problem talking to graphcool") print(parsed_json['errors']) exit(1) if parsed_json['data']['Sermon'] == None: print("Need to upload the data to graphcool") pp = pprint.PrettyPrinter(indent=4) pp.pprint(sermon.as_dict()) series_search_result = json.loads(client.execute(find_series_by_name(), {"name": sermon.series_name})) pp.pprint(series_search_result) print(type(series_search_result)) sermon.series_id = series_search_result['data']['Series']['id'] speaker_search_result = json.loads(client.execute(find_speaker_by_name(), {"name": sermon.speaker_name})) pp.pprint(speaker_search_result) sermon.speaker_ids = [speaker_search_result['data']['Speaker']['id']] event_search_result = json.loads(client.execute(find_event_by_name(), {"name": sermon.event})) pp.pprint(event_search_result) sermon.event_id = event_search_result['data']['Event']['id'] create_sermon_result = json.loads(client.execute(create_sermon(), sermon.as_dict())) pp.pprint(create_sermon_result) return "newid" else: print("It's already in graphcool") print(parsed_json['data']['Sermon']) return parsed_json['data']['Sermon']['id']
class HmrcReleaseSearch: def __init__(self): self.client = GraphQLClient('https://api.github.com/graphql') oauth_token = os.environ.get('GITOAUTH') # type: Optional[str] if not oauth_token: print("environment variable $GITOAUTH is not defined") exit(1) if not oauth_token.startswith("Bearer"): print( "environment variable $GITOAUTH does not start with 'Bearer'") exit(1) self.client.inject_token(oauth_token) # OauthToken 'bearer {token}' def graph_ql_search(self, lib_name): return self.client.execute(''' query { repository(owner:"hmrc", name:"''' + lib_name + '''") { releases(first: 100, orderBy: {direction: DESC, field: CREATED_AT}) { nodes { name } } } } ''') def fetch_release(self, sbt_version, lib): domain = lib.group(1) library_name = lib.group(2) current_version = lib.group(3) if domain == "uk.gov.hmrc": version_number = current_version.replace("-play-25", "").replace( "-play-26", "") for release in json.loads(self.graph_ql_search( library_name))["data"]["repository"]["releases"]["nodes"]: release_name = str(release["name"]) test = version_number release_number = str( release_name.replace("-play-25", "").replace( "-play-26", "").replace(",", "").split(" ")[0]) if test.split(".")[0] == release_number.split(".")[0]: if "-play-25" in release_name: if "2.5" in sbt_version: return str(release_number + "-play-25") else: return str(release_number + "-play-26") else: return str(release_number)
def buildClient(client=graphqlClient): # Cached in regular use cases. if (client is None): print('Building graphql client...') token = getAuthToken() if (token is None): # Short-circuit for 'no-auth' scenario. print('Failed to get access token. Abandoning client setup...') return None url = os.getenv('MAANA_ENDPOINT_URL') client = GraphQLClient(url) client.inject_token('Bearer '+token) return client
async def fetch_homeworks(self, since: str, to: str) -> list[Homework]: """ :param since: The start date of wanted fetched homeworks: 2020-12-30 :param to: The end date of wanted fetched homeworks: 2021-01-28 :return: a list of homework """ client = GraphQLClient("http://127.0.0.1:21727/graphql") client.inject_token(self.__token, "Token") data = json.loads(client.execute(Q.homework % (since, to))) homework = [] for work in data["data"]["homeworks"]: homework.append(Homework(work)) return homework
class SlushieClient: def __init__(self): self.client = GraphQLClient( 'https://rxmmnanjazc63nzfsn6q57nytu.appsync-api.us-east-2.amazonaws.com/graphql' ) self.client.inject_token(config.SLUSHIE_API_KEY, 'x-api-key') def put_weather_data(self, device_id, temperature, humidity): now = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S+00:00') query = ''' mutation updateWeatherData {{ updateSlushieWeatherModel(input: {{deviceId: \"{device_id}\", temperature: \"{temperature}\", humidity: \"{humidity}\", datetime: \"{now}\"}}) {{ deviceId temperature humidity datetime }} }} '''.format(device_id=device_id, temperature=temperature, humidity=humidity, now=now) print(query) result = self.client.execute(query) print(result) if 'errors' in result: result = self.create_weather_data(device_id, humidity, temperature) return result def create_weather_data(self, device_id, humidity, temperature): now = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S+00:00') query = ''' mutation createWeatherData {{ createSlushieWeatherModel(input: {{deviceId: \"{device_id}\", temperature: \"{temperature}\", humidity: \"{humidity}\", datetime: \"{now}\"}}) {{ deviceId temperature humidity datetime }} }} '''.format(device_id=device_id, temperature=temperature, humidity=humidity, now=now) print(query) result = self.client.execute(query) print(result) return result
def lambda_handler(event, context): client = GraphQLClient("https://api.faros.ai/v0/graphql") client.inject_token("Bearer {}".format(event["farosToken"])) query = """{ iam_userDetail { data { userId userName attachedManagedPolicies { policyName policyArn } groups { data { groupId groupName attachedManagedPolicies { policyName policyArn } } } farosAccountId farosRegionId } } }""" response = client.execute(query) response_json = json.loads(response) users = response_json["data"]["iam_userDetail"]["data"] users_without_policies = [] required_policy_arns = event["params"]["required_policy_arns"].split(",") for user in users: policies = get_policy_arns(user) missing_policies = get_missing_policies(required_policy_arns, policies) if missing_policies: users_without_policies.append({ "userId": user["userId"], "userName": user["userName"], "farosAccountId": user["farosAccountId"], "farosRegionId": user["farosRegionId"], "missing_policies": missing_policies} ) return users_without_policies
def download_organization(url): """Return aggregated organization data (see `common.py`) or `None` if no such org.""" logging.debug("Starting downloading the organization %s" % url) result = deepcopy(zero_data) # still zero repos processed org = url.replace('https://github.com/', '', 1) client = GraphQLClient('https://api.github.com/graphql') client.inject_token('Bearer ' + settings.GITHUB_API_TOKEN) # authentication repositories = get_repositories_for_org(client, org) for repo in repositories: if isinstance(repo, OrganizationNotFound): return None pocessed_repo_data = process_repository(repo) result = sum_profiles(result, pocessed_repo_data) return result
def search_charities(q, limit=20, skip=0): if not q: return { "count": 0, "results": [], } client = GraphQLClient(current_app.config.get("CHARITYBASE_API_URL")) client.inject_token("Apikey " + current_app.config.get("CHARITYBASE_API_KEY")) query = """ query fetchCharities($q:String, $limit:PageLimit, $skip:Int){ CHC { getCharities(filters: {search:$q}) { count list(limit:$limit, skip:$skip) { id names(all:false) { value primary } finances(all:true) { financialYear { begin } } } } } } """ result = client.execute( query, { "q": q, "limit": limit, "skip": skip, }, ) result = json.loads(result) return { "count": result.get("data", {}).get("CHC", {}).get("getCharities", {}).get("count", 0), "results": result.get("data", {}).get("CHC", {}).get("getCharities", {}).get("list", []), }
def all_jobs_metric(graphql_host, graphql_port, graphql_auth): # graphql connection graphql_url = 'http://' + graphql_host + ':' + str( graphql_port) + '/graphql' url = os.environ.get('GRAPHQL_URL', graphql_url) client = GraphQLClient(url) client.inject_token(os.environ.get('GRAPHQL_AUTH', graphql_auth)) output_allJobsRunning = graphql_queries.query_AllJobs_Running(client) df = pd.DataFrame() # We triger a query got all Historical Jobs allJobs = json.loads(output_allJobsRunning).get('data', {}).get('allJobs', {}) jobs = allJobs.get('Jobs', []) # Walk the result and append to dataframe for j in jobs: #print(j['jobid']) df_temp = pd.DataFrame(json_normalize(j)) df_temp['submitEpoch'] = j['timeStamp']['submitEpoch'] df_temp['time'] = j['timeStamp']['submitEpoch'] df_temp['submission_time'] = j['timeStamp']['submit'] df_temp['hosts'] = j['queue'].split('@')[1] df = df.append(df_temp, sort=True) pd.to_datetime(df['time'].values, unit='ms', utc=True) COLS = [ 'submission_time', 'jobid', 'taskid', 'slots', 'priority', 'department', 'project', 'shares', 'queue_name', 'hosts', 'usage.iow', 'usage.mem', 'usage.ioops', 'usage.cpu', 'usage.vmem', 'usage.wallclock', 'usage.maxvmem' ] # Handle case where no jobs were found by creating an empty data frame # with the expected columns if len(df) == 0: df = pd.DataFrame(columns=COLS + ['submitEpoch']) df.set_index('submitEpoch', append=False, inplace=True) return df[COLS]
async def login(username: str = None, password: str = None, url: str = None, ent: str = None, query: list[Q] or Q = None) -> User: """ Start a connexion with Pronote, and grab the token. :type query: object Q :param username: : Pronote/ENT username :param password: : Pronote/ENT password :param url: : Pronote link :param ent: : (optional) ENT Name (could be found here: https://github.com/Litarvan/pronote-api#comptes-région-supportés) """ if query is None: query = Q.full # subprocess.Popen(["pronote-api-server"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) body = {"url": url, "username": username, "password": password} if ent: body |= {"cas": ent} async with aiohttp.ClientSession() as client: async with client.post( "http://127.0.0.1:21727/auth/login", headers={'Content-Type': 'application/json'}, json=body) as resp: # noinspection PyTypeChecker token = json.loads(await resp.text()) if "token" not in token.keys(): raise errors.ConnexionError( "Could not log in with given credentials ") del body client = GraphQLClient("http://127.0.0.1:21727/graphql") client.inject_token(token["token"], "Token") data = json.loads(client.execute(query)) data = data["data"] data = merge(Q.base, data) return User(data, token["token"])
def lambda_handler(event, context): client = GraphQLClient("https://api.faros.ai/v0/graphql") client.inject_token("Bearer {}".format(event["farosToken"])) query = '''{ ec2_volume { data { volumeId encrypted farosAccountId farosRegionId } } }''' response = client.execute(query) response_json = json.loads(response) volumes = response_json["data"]["ec2_volume"]["data"] return [v for v in volumes if not v["encrypted"]]
def lambda_handler(event, context): client = GraphQLClient("https://api.faros.ai/v0/graphql") client.inject_token("Bearer {}".format(event["farosToken"])) query = '''{ ec2_instance { data { instanceId publicIpAddress farosAccountId farosRegionId } } }''' response = client.execute(query) response_json = json.loads(response) instances = response_json["data"]["ec2_instance"]["data"] return [i for i in instances if i["publicIpAddress"] is not None]