I have one example here: https://github.com/kanjih-ciandt/docker-jupyter-gcloud/blob/master/ka.ipynb
But, basically you first need some packages installed:
!pip install google-cloud --user
!pip install --upgrade google-cloud-bigquery[pandas] --user
!pip install google-cloud-storage --user
If you already have a service account file just execute this (replacing JSON_SERVICE_ACCOUNT_FILE):
import logging
import json
import os
from datetime import datetime
import pprint
from googleapiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials
# Default scope to get access token
_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'
from google.cloud import bigquery
client = bigquery.Client.from_service_account_json(JSON_SERVICE_ACCOUNT_FILE)
# Perform a query.
QUERY = (
'SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` '
'WHERE state = "TX" '
'LIMIT 100')
query_job = client.query(QUERY) # API request
rows = query_job.result() # Waits for query to finish
for row in rows:
print(row.name)
But, if you have access to some GCP project, but don't know how to create a service account you can create it directly in your jupyter notebook:
SERVICE_ACCOUNT='jupytersa'
JSON_SERVICE_ACCOUNT_FILE = 'sa1.json'
GCP_PROJECT_ID='<GCP_PROJECT_ID>'
import subprocess
import sys
import logging
logger = logging.Logger('catch_all')
def run_command(parameters):
try:
return subprocess.check_output(parameters)
except BaseException as e:
logger.error(e)
logger.error('ERROR: Looking in jupyter console for more information')
run_command([
'gcloud', 'iam', 'service-accounts',
'create', SERVICE_ACCOUNT,
'--display-name', "Service Account for BETA SCC API",
'--project', GCP_PROJECT_ID
])
IAM_ROLES = [
'roles/editor'
]
for role in IAM_ROLES:
run_command([
'gcloud', 'projects', 'add-iam-policy-binding',GCP_PROJECT_ID,
'--member', 'serviceAccount:{}@{}.iam.gserviceaccount.com'.format(SERVICE_ACCOUNT, GCP_PROJECT_ID),
'--quiet', '--role', role
])
run_command([
'gcloud', 'iam', 'service-accounts',
'keys', 'create', JSON_SERVICE_ACCOUNT_FILE ,
'--iam-account',
'{}@{}.iam.gserviceaccount.com'.format(SERVICE_ACCOUNT, GCP_PROJECT_ID)
])
The full example you can found here: https://github.com/kanjih-ciandt/docker-jupyter-gcloud/blob/master/ka.ipynb
To conclude, if you want to execute this notebook from Docker you can use this image: https://cloud.docker.com/u/hkanjih/repository/docker/hkanjih/docker-jupyter-gcloud