|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2016 Google Inc. All Rights Reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +"""Loads data into BigQuery from a local file. |
| 18 | +
|
| 19 | +For more information, see the README.md under /bigquery. |
| 20 | +
|
| 21 | +Example invocation: |
| 22 | + $ python load_data_from_file.py example_dataset example_table \ |
| 23 | + example-data.csv |
| 24 | +
|
| 25 | +The dataset and table should already exist. |
| 26 | +""" |
| 27 | + |
| 28 | +import argparse |
| 29 | +import time |
| 30 | +from gcloud import bigquery |
| 31 | + |
| 32 | + |
| 33 | +def load_data_from_file(dataset_name, table_name, source_file_name): |
| 34 | + bigquery_client = bigquery.Client() |
| 35 | + dataset = bigquery_client.dataset(dataset_name) |
| 36 | + table = dataset.table(table_name) |
| 37 | + |
| 38 | + # Reload the table to get the schema. |
| 39 | + table.reload() |
| 40 | + |
| 41 | + with open(source_file_name, 'rb') as source_file: |
| 42 | + # This example uses CSV, but you can use other formats. |
| 43 | + # See https://cloud.google.com/bigquery/loading-data |
| 44 | + job = table.upload_from_file( |
| 45 | + source_file, source_format='text/csv') |
| 46 | + |
| 47 | + job.begin() |
| 48 | + |
| 49 | + wait_for_job(job) |
| 50 | + |
| 51 | + print('Loaded {} rows into {}:{}.'.format( |
| 52 | + job.output_rows, dataset_name, table_name)) |
| 53 | + |
| 54 | + |
| 55 | +def wait_for_job(job): |
| 56 | + while True: |
| 57 | + job.reload() |
| 58 | + if job.state == 'DONE': |
| 59 | + if job.error_result: |
| 60 | + raise RuntimeError(job.error_result) |
| 61 | + return |
| 62 | + time.sleep(1) |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == '__main__': |
| 66 | + parser = argparse.ArgumentParser( |
| 67 | + description=__doc__, |
| 68 | + formatter_class=argparse.RawDescriptionHelpFormatter) |
| 69 | + parser.add_argument('dataset_name') |
| 70 | + parser.add_argument('table_name') |
| 71 | + parser.add_argument( |
| 72 | + 'source_file_name', help='Path to a .csv file to upload.') |
| 73 | + |
| 74 | + args = parser.parse_args() |
| 75 | + |
| 76 | + load_data_from_file( |
| 77 | + args.dataset_name, |
| 78 | + args.table_name, |
| 79 | + args.source_file_name) |
0 commit comments