|
| 1 | +# Copyright 2017 Google Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Demonstrates how to authenticate to Google BigQuery using the Google Cloud |
| 16 | +Client Libraries.""" |
| 17 | + |
| 18 | +import argparse |
| 19 | + |
| 20 | + |
| 21 | +def implicit(): |
| 22 | + from google.cloud import bigquery |
| 23 | + |
| 24 | + # If you don't specify credentials when constructing the client, the |
| 25 | + # client library will look for credentials in the environment. |
| 26 | + bigquery_client = bigquery.Client() |
| 27 | + |
| 28 | + # Make an authenticated API request |
| 29 | + datasets = list(bigquery_client.list_datasets()) |
| 30 | + print(datasets) |
| 31 | + |
| 32 | + |
| 33 | +def explicit(): |
| 34 | + from google.cloud import bigquery |
| 35 | + |
| 36 | + # Explicitly use service account credentials by specifying the private key |
| 37 | + # file. All clients in google-cloud-python have this helper, see |
| 38 | + # https://google-cloud-python.readthedocs.io/en/latest/core/modules.html |
| 39 | + # #google.cloud.client.Client.from_service_account_json |
| 40 | + bigquery_client = bigquery.Client.from_service_account_json( |
| 41 | + 'service_account.json') |
| 42 | + |
| 43 | + # Make an authenticated API request |
| 44 | + buckets = list(bigquery_client.list_datasets()) |
| 45 | + print(buckets) |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == '__main__': |
| 49 | + parser = argparse.ArgumentParser( |
| 50 | + description=__doc__, |
| 51 | + formatter_class=argparse.RawDescriptionHelpFormatter) |
| 52 | + |
| 53 | + subparsers = parser.add_subparsers(dest='command') |
| 54 | + subparsers.add_parser('implicit', help=implicit.__doc__) |
| 55 | + subparsers.add_parser('explicit', help=explicit.__doc__) |
| 56 | + |
| 57 | + args = parser.parse_args() |
| 58 | + |
| 59 | + if args.command == 'implicit': |
| 60 | + implicit() |
| 61 | + elif args.command == 'explicit': |
| 62 | + explicit() |
0 commit comments