微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PyDrive 2.0 – AuthenticationError:在重定向中找不到代码

如何解决PyDrive 2.0 – AuthenticationError:在重定向中找不到代码

设置

我正在使用PyDrive 2.0连接到Google Drive API。

def connect_google_drive_api():
    
    import os   
        
    # use Gdrive API to access Google Drive
    os.chdir('/Users/my/fol/ders/access_google_drive')
    from pydrive.auth import GoogleAuth
    from pydrive.drive import GoogleDrive
    
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth() # client_secrets.json need to be in the same directory as the script
    drive = GoogleDrive(gauth)
    
    return drive

工作目录/Users/mypath/access_google_drive包含client_secrets.json,看起来像

{"web":{"client_id":"xxx","project_id":"invoice-creation-290413","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_secret":"xxx","redirect_uris":["http://localhost:8080/"],"javascript_origins":["http://localhost:8080"]}}

我用client_id替换了真实的client_secretxxx


问题

当浏览器(Safari 14.0)显示Gdrive api link wants to access your Google Account并单击Allow时,该过程似乎卡住了。

大约20秒后,显示以下错误

Failed to find "code" in the query parameters of the redirect.
Try command-line authentication
Traceback (most recent call last):

  File "<ipython-input-36-792f41ab7318>",line 1,in <module>
    gauth.LocalWebserverAuth()

  File "/opt/anaconda3/lib/python3.7/site-packages/pydrive2/auth.py",line 125,in _decorated
    code = decoratee(self,*args,**kwargs)

  File "/opt/anaconda3/lib/python3.7/site-packages/pydrive2/auth.py",line 273,in LocalWebserverAuth
    raise AuthenticationError("No code found in redirect")

AuthenticationError: No code found in redirect

我该如何解决

解决方法

我正在将connect_google_drive_api()导入另一个脚本,例如脚本x.py

connect_google_drive_api()函数和x.py都具有os.chdir('/Users/my/fol/ders/access_google_drive')行,用于将工作目录设置为client_secrets.json所在的位置。

使用以下代码,我实际上建立了连接,没有任何问题,

def connect_google_drive_api():
        
    # use Gdrive API to access Google Drive
    from pydrive2.auth import GoogleAuth
    from pydrive2.drive import GoogleDrive
    
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth() # client_secrets.json need to be in the same directory as the script    
    
    drive = GoogleDrive(gauth)
    
    return drive
,

试图从Jupiter笔记本运行此代码。将浏览器从Safari(14.0.1)切换到Chrome(87.0.4280.88)后,我能够成功进行身份验证

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。