dsl*_*ack 2 python permissions google-sheets google-sheets-api
通过以下内容,我可以以编程方式在 Google 表格中创建电子表格,但该表格的所有者是开发者帐户(一个以“gserviceaccount.com”结尾的疯狂字符串),而我的普通帐户无法查看该电子表格。我还需要做什么才能将 Google 用户添加到读/写权限?
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
# ... json_key is the json blob that has the credentials
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_dict(json_key, scope)
service = discovery.build('sheets', 'v4', credentials=credentials)
spreadsheet = {
"properties": {"title": "my test spreadsheet"}
}
service.spreadsheets().create(body=spreadsheet).execute()
Run Code Online (Sandbox Code Playgroud)
编辑:
我尝试将范围更改为,['https://www.googleapis.com/auth/drive']但下面的答案仍然对我不起作用。当我跑步时
print [xx for xx in dir(service) if not xx.startswith('_')]
Run Code Online (Sandbox Code Playgroud)
我明白了
['new_batch_http_request', u'spreadsheets']
Run Code Online (Sandbox Code Playgroud)
换句话说,这不是我定义的服务permissions()中的方法。service我应该采取什么不同的做法?
小智 5
我通过阅读克里斯留下的评论弄清楚了这一点。他的评论中缺少的只是您实际上需要在他的drive_service. 请注意我用来构建不同对象的范围的变化:
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
key = '/path/to/service_account.json'
# Build 'Spreadsheet' object
spreadsheets_scope = [ 'https://www.googleapis.com/auth/spreadsheets' ]
sheets_credentials = ServiceAccountCredentials.from_json_keyfile_name(key, spreadsheets_scope)
sheets_service = build('sheets', 'v4', credentials=sheets_credentials)
# returns 'Spreadsheet' dict
# https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#resource-spreadsheet
spreadsheet = sheets_service.spreadsheets().create(
body={
"properties": {
'title': 'spreadsheets test',
},
"sheets": [],
}
).execute()
# id for the created file
spreadsheetId = spreadsheet['spreadsheetId']
# url of your file
spreadsheetUrl = spreadsheet['spreadsheetUrl']
# Build 'Permissions' object
drive_scope = [ 'https://www.googleapis.com/auth/drive' ]
drive_credentials = ServiceAccountCredentials.from_json_keyfile_name(key, drive_scope)
drive_service = build('drive', 'v3', credentials=drive_credentials)
# returns 'Permissions' dict
permissions = drive_service.permissions().create(
fileId=spreadsheetId,
transferOwnership=True,
body={
'type': 'user',
'role': 'owner',
'emailAddress': 'example@email.com',
}
).execute()
# apply permission
drive_service.files().update(
fileId=spreadsheetId,
body={'permissionIds': [permissions['id']]}
).execute()
print ('\nOpen me:\n\n%s\n' % spreadsheetUrl)
Run Code Online (Sandbox Code Playgroud)
因此,逻辑是,“电子表格资源”由其build所有属性和工作表数据组成,所有者设置为您的服务帐户。接下来,创建一个“驱动资源”,这是带有permissions()方法的资源。 返回用于电子表格文件的execute()新创建的权限ID 。update()