我这里有一个例子:https ://github.com/kanjih-ciandt/docker-jupyter-gcloud/blob/master/ka.ipynb
但是,基本上你首先需要安装一些软件包:
!pip install google-cloud --user
!pip install --upgrade google-cloud-bigquery[pandas] --user
!pip install google-cloud-storage --user
如果您已经有一个服务帐户文件,只需执行此操作(替换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)
但是,如果您有权访问某些 GCP 项目,但不知道如何创建服务帐户,则可以直接在 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)
])
您可以在此处找到完整示例:https ://github.com/kanjih-ciandt/docker-jupyter-gcloud/blob/master/ka.ipynb
总而言之,如果你想从 Docker 执行这个 notebook,你可以使用这个镜像:https ://cloud.docker.com/u/hkanjih/repository/docker/hkanjih/docker-jupyter-gcloud