是否可以从dict而非文件中加载凭证?这将使在云功能中使用短脚本更加容易,因为这样就无需上传文件了。通常,授权是这样的:
const fs = require('fs');
requ().then((result) => {
//here result is the file's representing string
const path = __dirname + '/tempFiles' + Date.now(); // a temporary file to send it
fs.writeFile(path, result, function(err) {
if(err) throw err;
return res.sendFile(path);
})
});
如果凭据存储在这样的变量中:
import pygsheets
gc = pygsheets.authorize(service_file='client_secret.json')
是否可以用secret = {
"type": "service_account",
"project_id": "XXXXXXXXXX",
"private_key_id": "XXXXXXXXXX",
"private_key": "XXXXXXXXXX"
"client_email": "XXXXXXXXXX",
"client_id": "XXXXXXXXXX",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "XXXXXXXXXX"
}
而不是custom_credentials
加载它们? docs除了使用“此选项将忽略任何其他参数”之外,没有提供任何使用说明。以下代码:
service_file
引发以下错误:
import pygsheets
gc = pygsheets.authorize(custom_credentials=secret)
还有另一种方法吗?例如,在AttributeError: 'dict' object has no attribute 'before_request'
中,有以下选项:
gspread
有什么建议吗?谢谢!!!
答案 0 :(得分:2)
就这样做了!因此,我们最终要做的是编写一个tempfile,然后加载进行授权。下面的工作示例:
import tempfile
def _google_creds_as_file():
temp = tempfile.NamedTemporaryFile()
temp.write(json.dumps({
"type": "service_account",
"project_id": "xxxx-yyy",
"private_key_id": "xxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY----------END PRIVATE KEY-----\n",
"client_email": "xxx@yyyy.iam.gserviceaccount.com",
"client_id": "xxxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxx%40xxxx.iam.gserviceaccount.com"
}))
temp.flush()
return temp
creds_file = _google_creds_as_file()
gc = pygsheets.authorize(service_account_file=creds_file.name)
答案 1 :(得分:1)
感谢@kontinuity的建议。经过一番挖掘,我发现实际上已经有一个拉取请求: https://github.com/nithinmurali/pygsheets/pull/345
在authorization.py中有一个名为service_account_env_var
的新选项。刚刚尝试过,效果很好。
答案 2 :(得分:1)
custom_credentials应该是here中提到的凭据对象。如果您不想创建tmp文件,则可以直接从json创建对象。
SCOPES = ('https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive')
service_account_info = json.loads(secret)
my_credentials = service_account.Credentials.from_service_account_info(service_account_info, scopes=SCOPES)