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: Uncomment the line below to set the `launch_browser` variable.
31+ # launch_browser = True
32+ #
33+ # The `launch_browser` boolean variable indicates if a local server is used
34+ # as the callback URL in the auth flow. A value of `True` is recommended,
35+ # but a local server does not work if accessing the application remotely,
36+ # such as over SSH or from a remote Jupyter notebook.
37+
4038 appflow = flow .InstalledAppFlow .from_client_secrets_file (
4139 'client_secrets.json' ,
4240 scopes = ['https://www.googleapis.com/auth/bigquery' ])
@@ -46,7 +44,33 @@ def authenticate_and_query(project, query, launch_browser=True):
4644 else :
4745 appflow .run_console ()
4846
49- run_query (appflow .credentials , project , query )
47+ credentials = appflow .credentials
48+ # [END bigquery_auth_user_flow]
49+
50+ # [START bigquery_auth_user_query]
51+ from google .cloud import bigquery
52+
53+ # TODO: Uncomment the line below to set the `project` variable.
54+ # project = 'user-project-id'
55+ #
56+ # The `project` variable defines the project to be billed for query
57+ # processing. The user must have the bigquery.jobs.create permission on
58+ # this project to run a query. See:
59+ # https://cloud.google.com/bigquery/docs/access-control#permissions
60+
61+ client = bigquery .Client (project = project , credentials = credentials )
62+
63+ query_string = """SELECT name, SUM(number) as total
64+ FROM `bigquery-public-data.usa_names.usa_1910_current`
65+ WHERE name = 'William'
66+ GROUP BY name;
67+ """
68+ query_job = client .query (query_string )
69+
70+ # Print the results.
71+ for row in query_job .result (): # Wait for the job to complete.
72+ print ("{}: {}" .format (row ['name' ], row ['total' ]))
73+ # [END bigquery_auth_user_query]
5074
5175
5276if __name__ == '__main__' :
@@ -58,9 +82,8 @@ def authenticate_and_query(project, query, launch_browser=True):
5882 help = 'Use a local server flow to authenticate. ' ,
5983 action = 'store_true' )
6084 parser .add_argument ('project' , help = 'Project to use for BigQuery billing.' )
61- parser .add_argument ('query' , help = 'BigQuery SQL Query.' )
6285
6386 args = parser .parse_args ()
6487
65- authenticate_and_query (
66- args .project , args . query , launch_browser = args .launch_browser )
88+ main (
89+ args .project , launch_browser = args .launch_browser )
0 commit comments