在Python中设置Google Drive API

时间:2018-07-10 20:48:18

标签: python google-drive-api

我一直在尝试建立一个非常简单的python程序以连接到Google Drive API,我尝试了数十种我在网上发现的不同方法,但是似乎都没有用,文档无处不在,我无法理解工作。

我需要一种不提示用户看到我将要访问自己的个人驱动器的访问权限的方法,我希望它自动执行此操作而无需每次都接受。

有人能给我发送一个完整的(非常简单的)工作代码模板,我可以使用它来使用python连接到Google的Drive API吗?

这是我的最新尝试,您可以修改它或创建一个新的,我只需要它即可:(

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文件,然后使用新数据编辑同一文件

非常感谢所有帮助。

1 个答案:

答案 0 :(得分:1)

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

主要区别在于登录方法。我没有看到python服务帐户驱动器示例,但是有一个适用于Google Analytics(分析)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格式相同。