简体   繁体   English

使用 python Gspread Oauth 凭证文件保存在 gspread 文档中指定的目录以外的位置

[英]Using python Gspread Oauth with credentials file saved somewhere other than in the directory specified in gspread documentation

The instructions for authentication can be found here: https://gspread.readthedocs.io/en/latest/oauth2.html#for-end-users-using-oauth-client-id可以在此处找到身份验证说明: https://gspread.readthedocs.io/en/latest/oauth2.html#for-end-users-using-oauth-client-id

Step 7 in the authentication sequence says: "Move the downloaded file to ~/.config/gspread/credentials.json. Windows users should put this file to %APPDATA%\gspread\credentials.json"身份验证序列中的第 7 步说:“将下载的文件移动到 ~/.config/gspread/credentials.json。Windows 用户应将此文件放入 %APPDATA%\gspread\credentials.json”

Is anyone aware of a way to keep the credentials.json file somewhere else and use it to authorize gpread?有没有人知道将credentials.json文件保存在其他地方并使用它来授权gpread的方法?

Alternatively I have thought about using shutil.move to grab the json file move it to the desired location but need to be able to do that without making assumptions about the whereabout of the python library or even if it is on a windows or unix machine. Alternatively I have thought about using shutil.move to grab the json file move it to the desired location but need to be able to do that without making assumptions about the whereabout of the python library or even if it is on a windows or unix machine. Any environmental variables that would reveal location of certain libraries?I could do something like this:任何可以显示某些库位置的环境变量?我可以这样做:

import gspread, os, shutil
loc = gspread.__location__
cred_path = os.path.join(loc, "credentials.json")
if not os.path.isfile(cred_path):
    shutil.move(input("Enter creds path:"), cred_path)

Found the solution to my own question.找到了我自己的问题的解决方案。 This function will set all the relevant environmental variables to your directory of choice where the credentials.json file should be kept (and the authorized_user.json file.):此 function 会将所有相关的环境变量设置到您选择的目录中,其中应保存 credentials.json 文件(以及 authorized_user.json 文件。):

import gspread.auth as ga
def gspread_paths(dir):
    ga.DEFAULT_CONFIG_DIR = dir
    ga.DEFAULT_CREDENTIALS_FILENAME = os.path.join(
        ga.DEFAULT_CONFIG_DIR, 'credentials.json')
    ga.DEFAULT_AUTHORIZED_USER_FILENAME = os.path.join(
        ga.DEFAULT_CONFIG_DIR, 'authorized_user.json')
    ga.DEFAULT_SERVICE_ACCOUNT_FILENAME = os.path.join(
        ga.DEFAULT_CONFIG_DIR, 'service_account.json')
    ga.load_credentials.__defaults__ = (ga.DEFAULT_AUTHORIZED_USER_FILENAME,)
    ga.store_credentials.__defaults__ = (ga.DEFAULT_AUTHORIZED_USER_FILENAME, 'token')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM