我一直在尝试建立一个非常简单的python程序来连接到googledriveapi,我尝试了很多种不同的方法,但是似乎都没有效果,文档到处都是,我无法让它工作。在
我需要一个方法,不提示用户授予访问权限看到我将访问我自己的个人驱动器,我希望它自动做到这一点,而不是我必须接受每次。在
有谁能给我一个完整的(非常简单的)工作代码模板,我可以用它连接到使用python的googledriveapi?在
这是我最近的一次尝试,你可以修改这个或创建一个新的,我只需要它工作:(
import google.oauth2.credentials
import google_auth_oauthlib.flow
from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError
# Use the client_secret.json file to identify the application requesting
# authorization. The client ID (from that file) and access scopes are required.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json',
scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'])
# Indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required.
flow.redirect_uri = 'http://localhost:8888/'
# Generate URL for request to Google's OAuth 2.0 server.
# Use kwargs to set optional request parameters.
authorization_url, state = flow.authorization_url(
# Enable offline access so that you can refresh an access token without
# re-prompting the user for permission. Recommended for web server apps.
access_type='offline',
# Enable incremental authorization. Recommended as a best practice.
include_granted_scopes='true')
print(state)
# code = input('Enter verification code: ').strip()
try:
credentials = flow.step2_exchange(state)
print(json.dumps(json.loads(credentials._to_json([])), sort_keys=True, indent=4))
except FlowExchangeError:
print("Your verification code is incorrect or something else is broken.")
exit(1)
奖金:我要用这个来上传一个CSV文件,然后用新数据编辑同一个文件
非常感谢你的帮助。在
你应该使用服务帐户。服务帐户就像虚拟用户。服务帐户有自己的驱动器帐户,您可以通过编程方式访问该帐户,并上传和下载。您还可以与服务器帐户共享您自己的google驱动器帐户上的一个或多个文件夹。通过授权它并授予它访问你的驱动器帐户的权限。不会显示同意屏幕或登录屏幕
主要区别在于登录方法。我没有看到一个python服务帐户驱动器的例子,但有一个为谷歌分析api。如果你看一下,改变它应该不难。您将需要使服务帐户凭据您现在拥有的凭据文件将无法工作。在
Hello Analytics API: Python quickstart for service accounts
您需要在代码中更改的主要内容是范围api名称和版本。创建驱动器服务后,代码将与Oauth2格式相同。在
相关问题 更多 >
编程相关推荐