我正在公司域上工作,以将任意数量的n个Google表格连接到python脚本以抓取数据并创建另一个电子表格。该公司不允许将Google表格直接共享到其gcp环境。
因此,我走了Oauth的路线来完成此任务。我在堆栈上找到了下面的代码(原谅我失去了链接),并根据需要对其进行了调整。
[问题是我无法获得身份验证,因为我不断收到错误400:redirect_url_mismatch-请求http://localhost:8080/中的重定向UR1与授权的不匹配。
[授权的URL是:[http://localhost:8080],这与我在代码中进行的调用相同(相同的URL在javascript来源中也得到授权)。
[我认为问题是尾随的/
没有在gcp环境下的授权URls中捕获,但是该团队告诉我尾随的/
不被支持(由于[ C0],因此将其省略)。
我花了一整天的时间,不确定是什么问题或如何解决。
/
我哪里出错了?
您需要将from oauth2client.tools import run_flow, argparser
from oauth2client.file import Storage
rscope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
CLIENT_ID = 'MY CLIENT ID'
CLIENT_SECRET = 'MY CLIENT SECRET'
flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=rscope,
redirect_url='http://localhost:8080')
storage = Storage('mycredentials.csv')
credentials = run_flow(flow, storage, argparser.parse_args([]))
import requests
import gspread, ast
from oauth2client.client import AccessTokenCredentials
data = {
'refresh_token' : credentials.refresh_token,
'client_id' : credentials.client_id,
'client_secret' : credentials.client_secret,
'grant_type' : 'refresh_token',
}
r = requests.post('https://accounts.google.com/o/oauth2/token', data = data)
try :
credentials.access_token = ast.literal_eval(r.text)['access_token']
except Exception:
pass;
gc = gspread.authorize(credentials)
设置为GCP中的重定向URL。
[在GCP中设置客户凭据时,您需要为凭据设置重定向URL。这是在授予授权后您的客户端可以返回的回调URL-与OAuth同意屏幕中的授权域不同。
https://localhost:8080
,然后单击APIs & Services > Credentials
。+ CREATE CREDENTIALS > OAuth Client ID
并给您的客户凭据一个名称。Web Application
下,输入Authorized redirect URIs
现在,您将需要下载这些新凭据并在您的应用程序中使用它们。也可能需要更改应用程序中列出的协议才能使用https://localhost:8080
,如下所示:
https
希望对您有帮助!