簡體   English   中英

在 Python 中使用 Gspread 共享給多個用戶

[英]Share to multiple users using Gspread in Python

我正在開發一個自動化腳本,該腳本使用 python 和 gspread 庫自動化 Google 電子表格。 使用它,我可以使用 share() 方法將創建的電子表格共享給單個用戶。 但是如何與多個用戶共享呢? 請建議我這樣做的方法!

我使用的代碼

spreadSheet.share("example@gmail.com", perm_type='user', role='writer')

我也嘗試將收件人添加到字符串列表中但不工作

spreadSheet.share(["email1@gmail.com", "email2@gmail.com"], perm_type='user', role='writer')

@田池

嘗試模式 2

from oauth2client.service_account import ServiceAccountCredentials
import gspread
from googleapiclient.discovery import build

scopes=[scope1, scope2]
cred=ServiceAccountCredentials.from_json_keyfile_name('myjsonfilepath', scopes)
driveClient = build("drive", "v3", credentials=cred)
emailRecepients = ['xxx', 'yyy', ,,,]
batch = driveClient.new_batch_http_request()
if len(emailRecepients) > 0 and len(emailRecepients)<=100:
    for e in emailRecepients:             
       batch.add(driveClient.permissions().create(fileId='id', body={"role": "reader", "type": "user", "emailAddress": e}))
    a = batch.execute()
    print(a)

我相信你的目標如下。

  • 您想與多個用戶共享 Google 電子表格。
  • 您想使用 gspread for python 來實現這一點。

為了與用戶共享 Google Drive 上的文件,在當前階段,使用 Drive API 的“Permissions: create”。 在“權限:創建”處,一個用戶通過一個 API 調用添加。 所以,在這種情況下,我認為可以考慮以下模式。

模式一:

在此模式中,僅使用 gspread。 在這種情況下,使用 email 地址數的 API 調用。

import gspread
from googleapiclient.discovery import build

gc = gspread.oauth(credentials_filename="###", authorized_user_filename="###") # Please use your gspread client.
spreadSheet = gc.open_by_key(spreadsheetId) # Please use your Class Spreadsheet.

emails = ["###", "###",,,] # Please set email addresses you want to share.
for e in emails:
    spreadSheet.share(e, perm_type="user", role="writer")

模式二:

在此模式中,使用了 python 的 gspread 和 googleapis。 在這種情況下,使用批處理請求。 這樣,每個請求都由異步進程運行。 並且,使用了一個 API 調用。 但是,在批量請求的情況下,一個批量請求可以包含 100 個請求。 所以,請注意這一點。

import gspread
from googleapiclient.discovery import build

gc = gspread.oauth(credentials_filename="###", authorized_user_filename="###") # Please use your gspread client.

spreadsheetId = "###" # Please set Spreadsheet ID.
emails = ["###", "###",,,] # Please set email addresses you want to share.

service = build("drive", "v3", credentials=gc.auth)
batch = service.new_batch_http_request()
for e in emails:
    batch.add(service.permissions().create(fileId=spreadsheetId, body={"role": "writer", "type": "user", "emailAddress": e}))
batch.execute()

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM