Created
September 12, 2018 21:45
-
-
Save mandatoryprogrammer/450625bdc351c41eec7a43b716e9b16a to your computer and use it in GitHub Desktop.
Google Cloud Python API/Library Use Environment Variable Instead of JSON for Service Credentials
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import os | |
# Imports the Google Cloud client library | |
from google.cloud import storage | |
# Need this for the monkeypatch | |
from google.oauth2 import service_account | |
# Patch in a new method for loading a dict | |
@classmethod | |
def from_service_account_dict(cls, credentials_info, *args, **kwargs): | |
credentials = service_account.Credentials.from_service_account_info( | |
credentials_info) | |
if cls._SET_PROJECT: | |
if 'project' not in kwargs: | |
kwargs['project'] = credentials_info.get('project_id') | |
kwargs['credentials'] = credentials | |
return cls(*args, **kwargs) | |
storage.Client.from_service_account_dict = from_service_account_dict | |
# And now we'll use it to set up Google Storage client | |
storage_client = storage.Client.from_service_account_dict( | |
json.loads( | |
os.environ.get( "GOOGLE_CREDENTIALS" ) | |
) | |
) | |
# Create a bucket for show | |
bucket_name = 'your-bucket-name-here' | |
# Creates the new bucket | |
bucket = storage_client.create_bucket(bucket_name) | |
print('Bucket {} created.'.format(bucket.name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment