在Python中设置googledriveapi

2024-05-04 07:09:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试建立一个非常简单的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文件,然后用新数据编辑同一个文件

非常感谢你的帮助。在


Tags: thetofromimportclientauthjsonaccess
1条回答
网友
1楼 · 发布于 2024-05-04 07:09:14

你应该使用服务帐户。服务帐户就像虚拟用户。服务帐户有自己的驱动器帐户,您可以通过编程方式访问该帐户,并上传和下载。您还可以与服务器帐户共享您自己的google驱动器帐户上的一个或多个文件夹。通过授权它并授予它访问你的驱动器帐户的权限。不会显示同意屏幕或登录屏幕

主要区别在于登录方法。我没有看到一个python服务帐户驱动器的例子,但有一个为谷歌分析api。如果你看一下,改变它应该不难。您将需要使服务帐户凭据您现在拥有的凭据文件将无法工作。在

Hello Analytics API: Python quickstart for service accounts

"""A simple example of how to access the Google Analytics API."""

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


def get_service(api_name, api_version, scopes, key_file_location):
    """Get a service that communicates to a Google API.

    Args:
        api_name: The name of the api to connect to.
        api_version: The api version to connect to.
        scopes: A list auth scopes to authorize for the application.
        key_file_location: The path to a valid service account JSON key file.

    Returns:
        A service that is connected to the specified API.
    """

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
            key_file_location, scopes=scopes)

    # Build the service object.
    service = build(api_name, api_version, credentials=credentials)

    return service


def get_first_profile_id(service):
    # Use the Analytics service object to get the first profile id.

    # Get a list of all Google Analytics accounts for this user
    accounts = service.management().accounts().list().execute()

    if accounts.get('items'):
        # Get the first Google Analytics account.
        account = accounts.get('items')[0].get('id')

        # Get a list of all the properties for the first account.
        properties = service.management().webproperties().list(
                accountId=account).execute()

        if properties.get('items'):
            # Get the first property id.
            property = properties.get('items')[0].get('id')

            # Get a list of all views (profiles) for the first property.
            profiles = service.management().profiles().list(
                    accountId=account,
                    webPropertyId=property).execute()

            if profiles.get('items'):
                # return the first view (profile) id.
                return profiles.get('items')[0].get('id')

    return None


def get_results(service, profile_id):
    # Use the Analytics Service Object to query the Core Reporting API
    # for the number of sessions within the past seven days.
    return service.data().ga().get(
            ids='ga:' + profile_id,
            start_date='7daysAgo',
            end_date='today',
            metrics='ga:sessions').execute()


def print_results(results):
    # Print data nicely for the user.
    if results:
        print 'View (Profile):', results.get('profileInfo').get('profileName')
        print 'Total Sessions:', results.get('rows')[0][0]

    else:
        print 'No results found'


def main():
    # Define the auth scopes to request.
    scope = 'https://www.googleapis.com/auth/analytics.readonly'
    key_file_location = '<REPLACE_WITH_JSON_FILE>'

    # Authenticate and construct service.
    service = get_service(
            api_name='analytics',
            api_version='v3',
            scopes=[scope],
            key_file_location=key_file_location)

    profile_id = get_first_profile_id(service)
    print_results(get_results(service, profile_id))


if __name__ == '__main__':
    main()

您需要在代码中更改的主要内容是范围api名称和版本。创建驱动器服务后,代码将与Oauth2格式相同。在

相关问题 更多 >