Google OAuth 2.0使用Python进行GCP BigQuery
我正在寻找一个代码片段,用于使用python连接到GCP大查询服务来实现oAuth 2.0身份验证 我正在使用GoogleCloudShell编写python代码。但我收到的访问令牌请求不正确Google OAuth 2.0使用Python进行GCP BigQuery,python,google-cloud-platform,oauth-2.0,google-bigquery,google-oauth,Python,Google Cloud Platform,Oauth 2.0,Google Bigquery,Google Oauth,我正在寻找一个代码片段,用于使用python连接到GCP大查询服务来实现oAuth 2.0身份验证 我正在使用GoogleCloudShell编写python代码。但我收到的访问令牌请求不正确 access_token = google.fetch_token(token_url=token_url,client_id=client_id,client_secret=client_secret,authorization_response=redirect_response). 我还需要自动执
access_token = google.fetch_token(token_url=token_url,client_id=client_id,client_secret=client_secret,authorization_response=redirect_response).
我还需要自动执行此过程,因此需要避免手动粘贴重定向响应。建议您使用BigQuery Python客户端库。Pip包
googlecloudbigquery
提供了这一功能。您还需要使用服务帐户json文件设置GOOGLE_应用程序_凭据
使用此过程,您不需要处理令牌生成和续订,因为此过程由后台的客户端库负责
有关详细说明,请参阅Python部分。中记录了如何从GCP控制台和中设置身份验证
要使用,您需要验证您的服务帐户。gcloud
命令gcloud iam服务帐户密钥创建[FILE\u NAME].json--iam帐户[NAME]@[PROJECT\u ID].iam.gserviceaccount.com
生成一个json密钥文件,其中包含必要的私有信息(如项目ID、私钥等)
进行BigQueryAPI调用时,需要向应用程序代码提供此类凭据。可以通过设置指向服务帐户JSON文件路径的环境变量GOOGLE\u APPLICATION\u CREDENTIALS
来完成
export GOOGLE_APPLICATION_CREDENTIALS="PATH/TO/SERVICE_ACCOUNT.json"
但是,这仅在当前shell会话期间有效,因此如果此会话过期或打开新会话,则需要再次设置此变量。验证凭据的另一种方法是使用方法在Python脚本的内部 在下面的Python代码中,使用方法
google.oauth2.Credentials对服务帐户进行身份验证。从_service_account_文件
,从位于google云存储中的CSV文件生成一个新的BigQuery表,并将新数据插入到该表中
from google.cloud import bigquery
from google.oauth2 import service_account
# Path to the service account credentials
key_path = "/PATH/TO/SERVICE-ACCOUNT.json"
credentials = service_account.Credentials.from_service_account_file(
key_path,
scopes=["https://www.googleapis.com/auth/cloud-platform"],
)
# Instantiation of the BigQuery client
bigquery_client = bigquery.Client()
GCS_URI = "gs://MY_BUCKET/MY_CSV_FILE"
DATASET_ID = "MY_DATASET"
TABLE_ID = "MY_TABLE"
def bq_insert_from_gcs(target_uri = GCS_URI, dataset_id = DATASET_ID, table_id = TABLE_ID):
"""This method inserts a CSV file stored in GCS into a BigQuery Table."""
dataset_ref = bigquery_client.dataset(dataset_id)
job_config = bigquery.LoadJobConfig()
# Schema autodetection enabled
job_config.autodetect = True
# Skipping first row which correspnds to the field names
job_config.skip_leading_rows = 1
# Format of the data in GCS
job_config.source_format = bigquery.SourceFormat.CSV
load_job = bigquery_client.load_table_from_uri(target_uri,\
dataset_ref.table(table_id),\
job_config=job_config)\
print('Starting job {}'.format(load_job.job_id))
print('Loading file {} into the Bigquery table {}'.format(target_uri, table_id))
load_job.result()
return 'Job finished.\n'
def bq_insert_to_table(rows_to_insert, dataset_id = DATASET_ID, table_id= TABLE_ID):
"""This method inserts rows into a BigQuery table"""
# Prepares a reference to the dataset and table
dataset_ref = bigquery_client.dataset(dataset_id)
table_ref = dataset_ref.table(table_id)
# API request to get table call
table = bigquery_client.get_table(table_ref)
# API request to insert the rows_to_insert
print("Inserting rows into BigQuery table {}".format(table_id))
errors = bigquery_client.insert_rows(table, rows_to_insert)
assert errors == []
bq_insert_from_gcs()
rows_to_insert = [( u'Alice', u'cat'),\
(u'John', u'dog')]
bq_insert_to_table(rows_to_insert)
另外,我强烈建议使用Python 3实现您的脚本,因为从2020年1月1日起,
google cloud bigquery将不再支持Python 2。您将需要导出到json的serviceaccount的凭据。
GCP->IAM和Admin->Service Accounts,在这三个小点下,您将找到为您的帐户创建密钥
正如前面的回答中提到的,您还需要
那么像这样的事情就行了
from google.cloud import bigquery
from google.oauth2 import service_account
def BigQuery():
try:
credentials = service_account.Credentials.from_service_account_file(
'/Credentials.json')
project_id = '[project_id]
client = bigquery.Client(credentials= credentials,project=project_id)
query = ('SELECT Column1, Column2 FROM `{}.{}.{}` limit 20'.format('[project_id]','[dataset]','[table]'))
query_job = client.query(query)
results = query_job.result()
for row in results:
print('Column1 1 : {}, Column 2: {}'.format(row.Column1, row.Column2))
except:
print('Error!')
if __name__ == '__main__':
BigQuery()
您正试图在Cloud Shell中使用OAuth“用户凭据”。这需要web浏览器,而Cloud Shell没有。更改策略以使用服务帐户。