由於無法在客戶端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()
非常感謝提示 – shabeer90 2012-08-16 09:17:57