我尝试在下一段代码中使用OAuth 2.0 for Server to Server(两条腿)使用Google Fusion Table:
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
scopes = ['https://www.googleapis.com/auth/fusiontables']
credentials = ServiceAccountCredentials\
.from_json_keyfile_name('***file-name***.json', scopes)
fusiontables = build('fusiontables', 'v2', credentials=credentials)
obj = fusiontables.query().sql(sql='select * from ***table-id***').execute()
当我从表中读取时,一切都很好,但是当我尝试插入一些数据时:
obj = fusiontables.query().sql(
sql="INSERT INTO ***table-id*** (Location, Number) VALUES('Paris', 1234)")\
.execute()
我收到了错误:
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/fusiontables/v2/query?alt=json&sql=INSERT+INTO+***table-id***+%28Location%2C+Number%29+VALUES%28%27Paris%27%2C+1234%29 returned "Forbidden">
问题:有人知道我在插入Google Fusion Table时遇到了什么问题吗?
UPD:
发现不推荐使用oauth2client,尝试按google.auth中描述的docs和请求进行查询:
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
credentials = service_account.Credentials.from_service_account_file('***filename***.json')
if credentials.requires_scopes:
credentials = credentials.with_scopes(scopes=['https://www.googleapis.com/auth/fusiontables'])
authed_session = AuthorizedSession(credentials)
r = authed_session.post('https://www.googleapis.com/fusiontables/v2/query',
data={
"sql": "***My SQL***",
"hdrs": True,
"typed": True,
})
作为预览,我得到了相同的结果: SELECT 成功, INSERT 成功。
感谢。