File size: 3,952 Bytes
54f81bf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | import logging
import pprint
import json
import os, sys
import httplib2
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
from googleapiclient.errors import HttpError
from secret import GOOGLE_PRIVATE_KEY_FILE, GOOGLE_DEVELOPER_PROJECT_ID, GOOGLE_DEVELOPER_PROJECT_NUMBER, GOOGLE_SERVICE_EMAIL
from census_schema import demo_schema, group_schema, family_schema, income_schema
class GoogleBigQueryClient():
"""
Google BigQuery API Client for GDELT access and processing.
"""
def __init__(self):
"""
Build authorized Google Big Query API Client from project_id and project_number given project google service email.
"""
SCOPE = 'https://www.googleapis.com/auth/bigquery'
self.get_private_key()
credentials = SignedJwtAssertionCredentials(GOOGLE_SERVICE_EMAIL, self.private_key, SCOPE)
http = httplib2.Http()
self.http = credentials.authorize(http)
self.client = build('bigquery', 'v2', http=self.http)
def get_private_key(self):
"""
Read from *.pem private key file. File path specified in secrets.py.
"""
BASE = os.path.dirname(os.path.abspath(__file__))
f = file(os.path.join(BASE, GOOGLE_PRIVATE_KEY_FILE), 'rb')
self.private_key = f.read()
f.close()
def test_access(self):
"""
Small response test to test authorized client. Working as of 02/25/15.
"""
datasets = self.client.datasets()
response = datasets.list(projectId=GOOGLE_DEVELOPER_PROJECT_NUMBER, all="true").execute()
print(response)
print('dataset list: \n')
for d in response['datasets']:
print("%s\n" % d['id'])
def loadTable(service, projectId, datasetId, targetTableId, sourceCSV, tableSchema, skip=0):
"""
Load table from Google Cloud Storage into Big Query.
"""
try:
jobCollection = service.jobs()
jobData = {
'projectId': projectId,
'configuration': {
'load': {
'sourceUris': [sourceCSV],
'skipLeadingRows': skip,
'fieldDelimiter': ",",
'allowQuotedNewLines': True,
'maxBadRecords': 1,
'schema': {
'fields': tableSchema
},
'destinationTable': {
'projectId': projectId,
'datasetId': datasetId,
'tableId': targetTableId
},
}
}
}
insertResponse = jobCollection.insert(projectId=projectId,
body=jobData).execute()
import time
while True:
job = jobCollection.get(projectId=projectId,
jobId=insertResponse['jobReference']['jobId']).execute()
print(">>> Google says the upload is: " + job['status']['state'])
if 'DONE' == job['status']['state']:
if 'errors' in job['status']:
print(job['status']['errors'])
return
time.sleep(10)
if 'errorResult' in job['status']:
print 'Error loading table: ', pprint.pprint(job)
return
except HttpError as err:
print 'Error in loadTable: ', pprint.pprint(err.resp)
def main():
client = GoogleBigQueryClient()
client.test_access()
# loadTable(client.client, GOOGLE_DEVELOPER_PROJECT_ID, "new_jersey", "new_jersey_demo", "gs://demographic-data/NewJerseyQuery.csv", demo_schema)
# loadTable(client.client, GOOGLE_DEVELOPER_PROJECT_ID, "new_jersey", "new_jersey_group", "gs://groupquarter-data/NewJerseyGQuery.txt", group_schema)
# loadTable(client.client, GOOGLE_DEVELOPER_PROJECT_ID, "new_jersey", "new_jersey_family", "gs://family-data/NewJerseyFQuery.txt", family_schema)
# loadTable(client.client, GOOGLE_DEVELOPER_PROJECT_ID, "new_jersey", "new_jersey_income", "gs://income-data/NewJerseyIncome.csv", income_schema)
if __name__ == "__main__":
main() |