Note that this is not the recommended approach. You should use the BigQuery client library because that is idiomatic Python.
See the bigquery_client notebook for examples.
In [56]:
PROJECT='cloud-training-demos' # CHANGE THIS
from googleapiclient.discovery import build
service = build('bigquery', 'v2')
In [44]:
# information about the ch04 dataset
dsinfo = service.datasets().get(datasetId="ch04", projectId=PROJECT).execute()
for info in dsinfo.items():
print(info)
In [40]:
# list tables in dataset
tables = service.tables().list(datasetId="ch04", projectId=PROJECT).execute()
for t in tables['tables']:
print(t['tableReference']['tableId'] + ' was created at ' + t['creationTime'])
In [80]:
# send a query request
request={
"useLegacySql": False,
"query": "SELECT start_station_name , AVG(duration) as duration , COUNT(duration) as num_trips FROM `bigquery-public-data`.london_bicycles.cycle_hire GROUP BY start_station_name ORDER BY num_trips DESC LIMIT 5"
}
print(request)
response = service.jobs().query(projectId=PROJECT, body=request).execute()
print('----' * 10)
for r in response['rows']:
print(r['f'][0]['v'])
In [77]:
# send a query request that will not terminate within the timeout specified and will require paging
request={
"useLegacySql": False,
"timeoutMs": 0,
"useQueryCache": False,
"query": "SELECT start_station_name , AVG(duration) as duration , COUNT(duration) as num_trips FROM `bigquery-public-data`.london_bicycles.cycle_hire GROUP BY start_station_name ORDER BY num_trips DESC LIMIT 5"
}
response = service.jobs().query(projectId=PROJECT, body=request).execute()
print(response)
In [78]:
jobId = response['jobReference']['jobId']
print(jobId)
In [79]:
# get query results
while (not response['jobComplete']):
response = service.jobs().getQueryResults(projectId=PROJECT,
jobId=jobId,
maxResults=2,
timeoutMs=5).execute()
while (True):
# print responses
for row in response['rows']:
print(row['f'][0]['v']) # station name
print('--' * 5)
# page through responses
if 'pageToken' in response:
pageToken = response['pageToken']
# get next page
response = service.jobs().getQueryResults(projectId=PROJECT,
jobId=jobId,
maxResults=2,
pageToken=pageToken,
timeoutMs=5).execute()
else:
break
Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License