Python oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name() Examples
The following are 30
code examples of oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
oauth2client.service_account.ServiceAccountCredentials
, or try the search function
.
Example #1
Source File: gsheet.py From avrae with GNU General Public License v3.0 | 7 votes |
def _init_gsheet_client(): with GoogleSheet._client_lock(): def _(): if config.GOOGLE_SERVICE_ACCOUNT is not None: credentials = ServiceAccountCredentials.from_json_keyfile_dict( json.loads(config.GOOGLE_SERVICE_ACCOUNT), scopes=SCOPES) else: credentials = ServiceAccountCredentials.from_json_keyfile_name( "avrae-google.json", scopes=SCOPES) return gspread.authorize(credentials) try: GoogleSheet.g_client = await asyncio.get_event_loop().run_in_executor(None, _) except: GoogleSheet._client_initializing = False raise GoogleSheet._token_expiry = datetime.datetime.now() + datetime.timedelta( seconds=ServiceAccountCredentials.MAX_TOKEN_LIFETIME_SECS) log.info("Logged in to google")
Example #2
Source File: mess_chore.py From instiapp-api with GNU Affero General Public License v3.0 | 7 votes |
def handle(self, *args, **options): """Fetch Mess Menus.""" # Use credentials to create a client to interact with the Google Drive API print("Authorizing - ", end="", flush=True) scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name('google_client_secret.json', scope) client = gspread.authorize(creds) print("OK") # Iterate over all hostels for hostel in Hostel.objects.all(): print("Updating " + hostel.name + " - ", end="", flush=True) if hostel.mess_gsheet: try: fetch_hostel(client, hostel) print("OK") except Exception: # pylint: disable=W0703 print("FAIL") else: print("SKIP")
Example #3
Source File: runTestSuites.py From nmos-testing with Apache License 2.0 | 6 votes |
def upload_test_results(results, name, sheet, credentials): """Upload the test results to the the google sheet""" if not sheet: return if not results: print('ERROR: No results specified') return credentials = ServiceAccountCredentials.from_json_keyfile_name(credentials, SCOPES) gcloud = gspread.authorize(credentials) spreadsheet = gcloud.open_by_url(sheet) try: worksheet = spreadsheet.worksheet(results["suite"]) except gspread.exceptions.WorksheetNotFound: print(" * ERROR: Worksheet {} not found".format(results["suite"])) return filename = "{}_{}_{}.json".format(name, results.get('suite'), results.get('timestamp')) gsheets_import(results, worksheet, filename)
Example #4
Source File: views.py From wagalytics with MIT License | 6 votes |
def get_access_token(ga_key_filepath): """Get the access token for Google Analytics. from https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/ Defines a method to get an access token from the credentials object. The access token is automatically refreshed if it has expired. """ # The scope for the OAuth2 request. SCOPE = 'https://www.googleapis.com/auth/analytics.readonly' # Construct a credentials objects from the key data and OAuth2 scope. _credentials = ServiceAccountCredentials.from_json_keyfile_name( ga_key_filepath, SCOPE) return _credentials.get_access_token().access_token
Example #5
Source File: fcmv1client.py From autopush with Mozilla Public License 2.0 | 6 votes |
def __init__(self, project_id, service_cred_path=None, logger=None, metrics=None, **options): self.project_id = project_id self.endpoint = ("https://fcm.googleapis.com/v1/" "projects/{}/messages:send".format(self.project_id)) self.token = None self.metrics = metrics self.logger = logger or Logger() self._options = options if service_cred_path: self.svc_cred = ServiceAccountCredentials.from_json_keyfile_name( service_cred_path, ["https://www.googleapis.com/auth/firebase.messaging"]) self._sender = treq.post
Example #6
Source File: google_analytics_hook.py From google_analytics_plugin with Apache License 2.0 | 6 votes |
def get_service_object(self, name): service = GoogleAnalyticsHook._services[name] if self.connection.password: credentials = AccessTokenCredentials(self.connection.password, 'Airflow/1.0') elif hasattr(self, 'client_secrets'): credentials = ServiceAccountCredentials.from_json_keyfile_dict(self.client_secrets, service.scopes) elif hasattr(self, 'file_location'): credentials = ServiceAccountCredentials.from_json_keyfile_name(self.file_location, service.scopes) else: raise ValueError('No valid credentials could be found') return build(service.name, service.version, credentials=credentials)
Example #7
Source File: gcp_agent.py From citest with Apache License 2.0 | 5 votes |
def make_service(cls, api=None, version=None, scopes=None, credentials_path=None, logger=None): """Instantiate a client service instance. Args: version: [string] The version of the API to use. scopes: [string] List of scopes to authorize, or None. credentials_path: [string] Path to json file with credentials, or None. logger: [Logger] The logger to inject into the agent if not the default. Returns: Service """ credentials_path = credentials_path or None logger = logger or logging.getLogger(__name__) if api is None: default_api, default_version = cls.default_discovery_name_and_version() api = default_api version = version or default_version if version is None: version = GcpAgent.determine_current_version(api) http = httplib2.Http() http = apiclient.http.set_user_agent( http, 'citest/{version}'.format(version=citest.__version__)) credentials = None if credentials_path is not None: logger.info('Authenticating %s %s', api, version) credentials = ServiceAccountCredentials.from_json_keyfile_name( credentials_path, scopes=scopes) else: credentials = GoogleCredentials.get_application_default() if scopes and credentials.create_scoped_required(): credentials = credentials.create_scoped(scopes) http = credentials.authorize(http) logger.info('Constructing %s service...', api) return apiclient.discovery.build(api, version, http=http)
Example #8
Source File: bot.py From pl-predictions-using-fifa with Mozilla Public License 2.0 | 5 votes |
def write_to_google_sheet(row): # use creds to create a client to interact with the Google Drive API scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('./client_secret.json', scope) client = gspread.authorize(credentials) sheet = client.open("2017-2018-PL-tips").sheet1 sheet.append_row(row)
Example #9
Source File: google.py From k8s-snapshots with BSD 2-Clause "Simplified" License | 5 votes |
def get_gcloud(ctx, version: str= 'v1'): """ Get a configured Google Compute API Client instance. Note that the Google API Client is not threadsafe. Cache the instance locally if you want to avoid OAuth overhead between calls. Parameters ---------- version Compute API version """ SCOPES = 'https://www.googleapis.com/auth/compute' credentials = None if ctx.config.get('gcloud_credentials_file'): credentials = ServiceAccountCredentials.from_json_keyfile_name( ctx.config.get('gcloud_credentials_file'), scopes=SCOPES) if ctx.config.get('google_application_credentials'): keyfile = json.loads(ctx.config.get('google_application_credentials')) credentials = ServiceAccountCredentials.from_json_keyfile_dict( keyfile, scopes=SCOPES) if not credentials: credentials = GoogleCredentials.get_application_default() if not credentials: raise RuntimeError("Auth for Google Cloud was not configured") compute = discovery.build( 'compute', version, credentials=credentials, # https://github.com/google/google-api-python-client/issues/299#issuecomment-268915510 cache_discovery=False ) return compute
Example #10
Source File: banned.py From SML-Cogs with MIT License | 5 votes |
def get_sheet(self, ctx) -> gspread.Worksheet: """Return values from spreadsheet.""" server = ctx.message.server credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_KEY_JSON, scopes=SCOPES) spreadsheetId = self.settings[server.id]["SHEET_ID"] gc = gspread.authorize(credentials) sh = gc.open_by_key(spreadsheetId) worksheet = sh.get_worksheet(0) return worksheet
Example #11
Source File: calendar.py From SML-Cogs with MIT License | 5 votes |
def calendar_list(self, ctx, max_results=5): """List events on a calendar.""" credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_KEY_JSON, scopes=SCOPES) http = credentials.authorize(httplib2.Http()) service = discovery.build('calendar', 'v3', http=http) now = dt.datetime.utcnow().isoformat() + 'Z' await self.bot.say( "Getting the upcoming {} events:".format(max_results)) eventsResult = service.events().list( calendarId=RACF_CALENDAR_ID, timeMin=now, maxResults=max_results, singleEvents=True, orderBy='startTime').execute() events = eventsResult.get('items', []) if not events: await self.bot.say("No upcoming events found.") out = [] for event in events: start = event['start'].get('dateTime', event['start'].get('date')) out.append(start) out.append(event['summary']) for page in pagify('\n'.join(out), shorten_by=24): await self.bot.say(page)
Example #12
Source File: folderclone.py From folderclone with GNU General Public License v3.0 | 5 votes |
def copy(source, dest): global drive global cred_num try: copied_file = drive.files().copy(fileId=source, body={"parents": [dest]}, supportsAllDrives=True).execute() except googleapiclient.errors.HttpError as e: cred_num += 1 if cred_num % 100 == 0: cred_num += 1 credentials = ServiceAccountCredentials.from_json_keyfile_name("accounts/" + str(cred_num) + ".json", scopes=[ "https://www.googleapis.com/auth/drive" ]) drive = googleapiclient.discovery.build("drive", "v3", credentials=credentials) logwrite("changed cred_num to " + str(cred_num)) copy(source, dest) except socket.timeout: logwrite("timeout") time.sleep(60) copy(source, dest) except Exception as e: logwrite("error: " + str(e)) try: copy(source, dest) except RecursionError as e: logwrite("max recursion reached") raise e
Example #13
Source File: wsstorage.py From ws-backend-community with GNU General Public License v3.0 | 5 votes |
def __create_signed_url_for_resource( self, verb="GET", bucket=None, file_key=None, duration=config.storage_signed_url_duration, creds_file_path=config.gcp_creds_file_path, ): """ Create and return a signed URL for retrieving the specified file from GCP. :param verb: The HTTP verb for the signed request. :param bucket: The bucket where the file resides. :param file_key: The key where the file resides within the bucket. :param duration: The amount of time in seconds that the URL should be valid for. :param creds_file_path: The local file path to where the GCP credentials to use to sign the URL reside. :return: A signed URL that can be used to retrieve the referenced file's contents. """ to_sign, expires_epoch = self.__get_signing_content_for_resource( verb=verb, bucket=bucket, file_key=file_key, duration=duration, ) creds = ServiceAccountCredentials.from_json_keyfile_name(creds_file_path) client_id = creds.service_account_email signed_blob = creds.sign_blob(to_sign)[1] encoded_sig = b64encode(signed_blob).replace("+", "%2B").replace("/", "%2F") resource_url = "%s%s/%s" % ( self.base_url, bucket, file_key, ) return "%s?GoogleAccessId=%s&Expires=%s&Signature=%s" % ( resource_url, client_id, expires_epoch, encoded_sig, )
Example #14
Source File: googlesheets.py From spice-hate_speech_detection with MIT License | 5 votes |
def create_google_sheet(sheetname): scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('confs/google_sheets.json', scope) gc = gspread.authorize(credentials) wks = gc.create(sheetname).sheet1 return wks
Example #15
Source File: googlesheets.py From spice-hate_speech_detection with MIT License | 5 votes |
def get_access(): scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('confs/google_sheets.json', scope) gc = gspread.authorize(credentials) return gc
Example #16
Source File: gdrive_service.py From rasa-demo with GNU General Public License v3.0 | 5 votes |
def __init__(self, gdrive_credentials_json: Text = config.gdrive_credentials): scopes = [ "https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive", ] # authenticate the service with a json key with tempfile.NamedTemporaryFile(suffix="_credentials.json", mode="w") as f: f.write(gdrive_credentials_json) f.flush() self.credentials = ServiceAccountCredentials.from_json_keyfile_name( f.name, scopes=scopes )
Example #17
Source File: workers.py From crmint with Apache License 2.0 | 5 votes |
def _ga_setup(self, v='v4'): credentials = ServiceAccountCredentials.from_json_keyfile_name(_KEY_FILE) service = 'analyticsreporting' if v == 'v4' else 'analytics' self._ga_client = build(service, v, credentials=credentials)
Example #18
Source File: workers.py From crmint with Apache License 2.0 | 5 votes |
def _get_ml_client(self): credentials = ServiceAccountCredentials.from_json_keyfile_name(_KEY_FILE) self._ml_client = build('ml', 'v1', credentials=credentials)
Example #19
Source File: workers.py From crmint with Apache License 2.0 | 5 votes |
def _get_automl_client(): """Constructs a Resource for interacting with the AutoML API.""" # You might be wondering why we're using the discovery-based Google API # client library as opposed to the more modern Google Cloud client library. # The reason is that the modern client libraries (e.g. google-cloud-automl) # are not supported on App Engine's Python 2 runtime. # See: https://github.com/googleapis/google-cloud-python credentials = ServiceAccountCredentials.from_json_keyfile_name(_KEY_FILE) return build('automl', 'v1beta1', credentials=credentials)
Example #20
Source File: train_NN.py From deep-transfer-learning-crop-prediction with MIT License | 5 votes |
def authorize_gspread(output_google_doc, worksheet_name, create_worksheet = False): scope = ['https://www.googleapis.com/auth/spreadsheets'] credentials = ServiceAccountCredentials.from_json_keyfile_name(AUTH_FILE_NAME, scope) gc = gspread.authorize(credentials) sh = gc.open_by_url(output_google_doc) if create_worksheet: wks = sh.add_worksheet(title=worksheet_name, rows="1", cols="20") else: wks = sh.worksheet(worksheet_name) headers = gspread.httpsession.HTTPSession(headers={'Connection': 'Keep-Alive'}) gc = gspread.Client(auth=credentials, http_session=headers) gc.login() return wks
Example #21
Source File: GWLogger.py From SWProxy-plugins with GNU Lesser General Public License v3.0 | 5 votes |
def get_worksheet(self, key, sheet): date = datetime.date.today() days_until_saturday = 5 - date.weekday() next_saturday = date + datetime.timedelta(days_until_saturday) scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCredentials.from_json_keyfile_name(key, scope) gc = gspread.authorize(credentials) sheet_name = 'Guildwar %s' % next_saturday.strftime('%m-%d-%Y') return gc.open(sheet_name)
Example #22
Source File: spreadsheet_api.py From ocs-ci with MIT License | 5 votes |
def __init__(self, sheet_name, sheet_index): # use creds to create a client to interact with the Google Drive API scope = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive' ] google_api = os.path.expanduser(config.RUN['google_api_secret']) creds = ServiceAccountCredentials.from_json_keyfile_name( google_api, scope ) client = gspread.authorize(creds) self.sheet = client.open(sheet_name).get_worksheet(sheet_index)
Example #23
Source File: import-mailbox-to-gmail.py From import-mailbox-to-gmail with Apache License 2.0 | 5 votes |
def get_credentials(username): """Gets valid user credentials from a JSON service account key file. Args: username: The email address of the user to impersonate. Returns: Credentials, the obtained credential. """ credentials = ServiceAccountCredentials.from_json_keyfile_name( args.json, scopes=SCOPES).create_delegated(username) return credentials
Example #24
Source File: member_sheets.py From mitoc-trips with GNU General Public License v3.0 | 5 votes |
def connect_to_sheets(): """ Returns a Google Sheets client and the creds used by that client. If intentionally disabling Google Sheets functionality, `None` will be returned as both the client and client credentials. This occurs even if the proper credential file is present. If missing credentials while in DEBUG mode, a "soft failure" will occur: the logger will note the missing credentials file and will return `None` for both client and credentials. This allows us to run a webserver in a development environment that will never actually update Google spreadsheets. We can go through the flow of modifying discounts without running a Celery job to update the spreadsheet. """ scope = ['https://spreadsheets.google.com/feeds'] credfile = settings.OAUTH_JSON_CREDENTIALS creds_present = credfile and os.path.exists(credfile) # Avoid unnecessary handshake with a service we'll never use if settings.DISABLE_GSHEETS: return None, None if not creds_present: if settings.DEBUG: logger.error( "OAUTH_JSON_CREDENTIALS is missing! " "Unable to update Google Sheets." ) return None, None raise KeyError("Specify OAUTH_JSON_CREDENTIALS to update Google Sheets") credentials = ServiceAccountCredentials.from_json_keyfile_name(credfile, scope) return gspread.authorize(credentials), credentials
Example #25
Source File: resultsImporter.py From nmos-testing with Apache License 2.0 | 5 votes |
def main(): parser = argparse.ArgumentParser() parser.add_argument("--json", required=True, nargs="+", help="json test results filename(s) to import") parser.add_argument("--sheet", required=True, help="spreadsheet url") parser.add_argument("--credentials", default="credentials.json", help="credentials filename") parser.add_argument("--start_col", default="1", type=int, help="reserve some columns for manually entered details") parser.add_argument("--insert", action="store_true", help="insert new results at the top rather than the bottom") args = parser.parse_args() credentials = ServiceAccountCredentials.from_json_keyfile_name(args.credentials, SCOPES) gcloud = gspread.authorize(credentials) spreadsheet = gcloud.open_by_url(args.sheet) worksheets = spreadsheet.worksheets() for json_file_name in args.json: with open(json_file_name) as json_file: test_results = json.load(json_file) try: worksheet = next(x for x in worksheets if x.title == test_results["suite"]) except StopIteration: print(" * ERROR: Worksheet {} not found".format(test_results["suite"])) # could add_worksheet? sys.exit(1) gsheets_import(test_results, worksheet, json_file_name, args.start_col, args.insert)
Example #26
Source File: utils_auth.py From gsc-logger with Apache License 2.0 | 5 votes |
def get_Auth(): credentials = ServiceAccountCredentials.from_json_keyfile_name(cfg.CREDENTIAL_SERVICE, cfg.DEFAULT_SCOPES) http = httplib2.Http(memcache, timeout=60) #http = httplib2.Http() return credentials.authorize(http)
Example #27
Source File: generate-google-id-jwt.py From endpoints-tools with Apache License 2.0 | 5 votes |
def generate_jwt(args): """Generates a signed JSON Web Token using a service account. Based on https://cloud.google.com/endpoints/docs/service-to-service-auth""" # Make sure the service account has "Service Account Token Creator" permissions in Google IAM credentials = ServiceAccountCredentials.from_json_keyfile_name( args.service_account_file).create_scoped(['https://www.googleapis.com/auth/cloud-platform']) service = googleapiclient.discovery.build( serviceName='iam', version='v1', credentials=credentials) now = int(time.time()) header_json = json.dumps({ "typ": "JWT", "alg": "RS256"}) payload_json = json.dumps({ 'iat': now, "exp": now + 3600, 'iss': args.issuer if args.issuer else credentials.service_account_email, "target_audience": 'https://' + args.aud, "aud": "https://www.googleapis.com/oauth2/v4/token" }) header_and_payload = '{}.{}'.format( base64.urlsafe_b64encode(header_json), base64.urlsafe_b64encode(payload_json)) slist = service.projects().serviceAccounts().signBlob( name="projects/-/serviceAccounts/" + credentials.service_account_email, body={'bytesToSign': base64.b64encode(header_and_payload)}) res = slist.execute() signature = base64.urlsafe_b64encode( base64.decodestring(res['signature'])) signed_jwt = '{}.{}'.format(header_and_payload, signature) return signed_jwt
Example #28
Source File: generate-jwt.py From endpoints-tools with Apache License 2.0 | 5 votes |
def main(args): """Generates a signed JSON Web Token using a Google API Service Account.""" credentials = ServiceAccountCredentials.from_json_keyfile_name( args.service_account_file) now = int(time.time()) payload = { "exp": now + credentials.MAX_TOKEN_LIFETIME_SECS, "iat": now, "aud": args.aud, } if args.email: payload["email"] = args.email if args.groupId: payload["groupId"] = args.groupId if args.issuer: payload["iss"] = args.issuer payload["sub"] = args.issuer else: payload["iss"] = credentials.service_account_email payload["sub"] = credentials.service_account_email signed_jwt = oauth2client.crypt.make_signed_jwt( credentials._signer, payload, key_id=credentials._private_key_id) return signed_jwt
Example #29
Source File: spreadsheet.py From heltour with MIT License | 5 votes |
def _open_doc(url): scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCredentials.from_json_keyfile_name( settings.GOOGLE_SERVICE_ACCOUNT_KEYFILE_PATH, scope) gc = gspread.authorize(credentials) try: return gc.open_by_url(url) except gspread.SpreadsheetNotFound: raise SpreadsheetNotFound
Example #30
Source File: auth.py From edx2bigquery with GNU General Public License v2.0 | 5 votes |
def get_service_acct_creds(key_file, verbose=False): '''Generate service account credentials using the given key file. key_file: path to file containing private key. ''' ### backcompatability for .p12 keyfiles if key_file.endswith('.p12') or key_file.endswith('.pem'): from edx2bigquery_config import auth_service_acct as SERVICE_ACCT if verbose: print "using key file" print "service_acct=%s, key_file=%s" % (SERVICE_ACCT, KEY_FILE) try: creds = ServiceAccountCredentials.from_p12_keyfile( SERVICE_ACCT, key_file, scopes=BIGQUERY_SCOPE) except Exception as err: # fallback to old google SignedJwtAssertionCredentials call with open (key_file, 'rb') as f: key = f.read(); creds = SignedJwtAssertionCredentials( SERVICE_ACCT, key, BIGQUERY_SCOPE) return creds ### creds = ServiceAccountCredentials.from_json_keyfile_name( key_file, BIGQUERY_SCOPE) return creds