Skip to content

Instantly share code, notes, and snippets.

@mandatoryprogrammer
Created September 12, 2018 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mandatoryprogrammer/450625bdc351c41eec7a43b716e9b16a to your computer and use it in GitHub Desktop.
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
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