2323import argparse
2424
2525
26- def run_query (credentials , project , query ):
27- from google .cloud import bigquery
28-
29- client = bigquery .Client (project = project , credentials = credentials )
30- query_job = client .query (query )
31-
32- # Print the results.
33- for row in query_job .result (): # Wait for the job to complete.
34- print (row )
35-
36-
37- def authenticate_and_query (project , query , launch_browser = True ):
26+ def main (project , launch_browser = True ):
27+ # [START bigquery_auth_user_flow]
3828 from google_auth_oauthlib import flow
3929
30+ # TODO: Use a local server in the auth flow? This is recommended but does
31+ # not work if accessing the application remotely, such as over SSH or
32+ # from a remote Jupyter notebook.
33+ # launch_browser = True
34+
4035 appflow = flow .InstalledAppFlow .from_client_secrets_file (
4136 'client_secrets.json' ,
4237 scopes = ['https://www.googleapis.com/auth/bigquery' ])
@@ -46,7 +41,31 @@ def authenticate_and_query(project, query, launch_browser=True):
4641 else :
4742 appflow .run_console ()
4843
49- run_query (appflow .credentials , project , query )
44+ credentials = appflow .credentials
45+ # [END bigquery_auth_user_flow]
46+
47+ # [START bigquery_auth_user_query]
48+ from google .cloud import bigquery
49+
50+ # TODO: This project will be billed for the query processing. The user must
51+ # have the bigquery.jobs.create permission on this project to run a
52+ # query. See:
53+ # https://cloud.google.com/bigquery/docs/access-control#permissions
54+ # project = 'user-project-id'
55+
56+ client = bigquery .Client (project = project , credentials = credentials )
57+
58+ query_string = """SELECT name, SUM(number) as total
59+ FROM `bigquery-public-data.usa_names.usa_1910_current`
60+ WHERE name = 'William'
61+ GROUP BY name;
62+ """
63+ query_job = client .query (query_string )
64+
65+ # Print the results.
66+ for row in query_job .result (): # Wait for the job to complete.
67+ print ("{}: {}" .format (row ['name' ], row ['total' ]))
68+ # [END bigquery_auth_user_query]
5069
5170
5271if __name__ == '__main__' :
@@ -58,9 +77,8 @@ def authenticate_and_query(project, query, launch_browser=True):
5877 help = 'Use a local server flow to authenticate. ' ,
5978 action = 'store_true' )
6079 parser .add_argument ('project' , help = 'Project to use for BigQuery billing.' )
61- parser .add_argument ('query' , help = 'BigQuery SQL Query.' )
6280
6381 args = parser .parse_args ()
6482
65- authenticate_and_query (
66- args .project , args . query , launch_browser = args .launch_browser )
83+ main (
84+ args .project , launch_browser = args .launch_browser )
0 commit comments