1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

EC2(Python3)->BigQuery

Last updated at Posted at 2017-01-17

前提

・GCPのアカウントが準備できていること
・BigQueryに接続可能なtableが存在すること

実行環境の準備

ec2
-pyenv
-naconda3-4.0.0
-pandas
-httplib2
-google-api-python-client

モジュール追加

sudo su -
pyenv global naconda3-4.0.0
pip install httplib2
pip install google-api-python-client

GoogleCloudSDKの導入(python2.x環境で実行)と認証

pyenv global system
curl https://sdk.cloud.google.com | bash
~/google-cloud-sdk/bin/gcloud auth login

※認証情報は~/.config配下に出力される

ごく少ないレコードのテーブルで実行

import pandas as pd
query = 'SELECT * FROM dataset_name.table_name'
pd.read_gbq(query, 'your_project_ID')

→pd.read_gbqで認証が走るが、EC2が実行元となるため、
 localhostでリスンする認証用URLがうまく受け取れない

#Oauth2での認証情報生成

from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
flow = OAuth2WebServerFlow(client_id='your_client_id',
                           client_secret='your_client_secret',
                           scope='https://www.googleapis.com/auth/bigquery',
                           redirect_uri='urn:ietf:wg:oauth:2.0:oob')
storage = Storage('bigquery_credentials.dat')
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ')
credentials = flow.step2_exchange(code)
storage.put(credentials)

※your_client_id、your_client_sercretは~/.config配下から

上記処理実行後、カレントディレクトリに「bigquery_credentials.dat」が作成される。
→pandas.read_gbqは上記を認証情報として利用

ごく少ないレコードのテーブルで実行

import pandas as pd
query = 'SELECT * FROM dataset_name.table_name'
pd.read_gbq(query, 'your_project_ID')

参考

https://developers.google.com/api-client-library/python/guide/aaa_oauth
http://stackoverflow.com/questions/37792709/accessing-big-query-from-cloud-datalab-using-pandas

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?