由于无法在客户端 JavaScript 代码中隐藏客户端密码,因此无法授权客户端 JavaScript 应用程序通过服务器到服务器 OAuth 流使用 BigQuery。
在这种情况下,唯一的解决方案是对来自 JavaScript 应用程序的 API 调用使用服务器端代理。下面是如何通过 AppEngine 代理查询调用的片段(注意:下面的代码对任何用户开放,它会进行任何检查以确保调用正在通过您的特定 JavaScript 客户端运行)。
import httplib2
from apiclient.discovery import build
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from oauth2client.appengine import AppAssertionCredentials
# BigQuery API Settings
SCOPE = 'https://www.googleapis.com/auth/bigquery'
PROJECT_ID = 'XXXXXXXXXX' # REPLACE WITH YOUR Project ID
# Create a new API service for interacting with BigQuery
credentials = AppAssertionCredentials(scope=SCOPE)
http = credentials.authorize(httplib2.Http())
bigquery_service = build('bigquery', 'v2', http=http)
class StartQueryHandler(webapp.RequestHandler):
def post(self):
query_string = self.request.get('query')
jobCollection = bigquery_service.jobs()
jobData = {
'configuration': {
'query': {
'query': query_string,
}
}
}
try:
insertResponse = jobCollection.insert(projectId=PROJECT_ID,
body=jobData).execute()
self.response.headers.add_header('content-type',
'application/json',
charset='utf-8')
self.response.out.write(insertResponse)
except:
self.response.out.write('Error connecting to the BigQuery API')
class CheckQueryHandler(webapp.RequestHandler):
def get(self, job_id):
query_job = bigquery_service.jobs()
try:
queryReply = query_job.getQueryResults(projectId=PROJECT_ID,
jobId=job_id).execute()
self.response.headers.add_header('content-type',
'application/json',
charset='utf-8')
self.response.out.write(queryReply)
except:
self.response.out.write('Error connecting to the BigQuery API')
application = webapp.WSGIApplication(
[('/startquery(.*)', StartQueryHandler),
('/checkquery/(.*)', CheckQueryHandler)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()