代码之家  ›  专栏  ›  技术社区  ›  Sumithran

在python中通过api上传到Google Drive后如何获取链接?

  •  0
  • Sumithran  · 技术社区  · 7 年前

    这里我使用谷歌驱动器API与python上传文件到谷歌驱动器,我如何才能得到上传文件的链接。

    我试过了 print (res['exportLinks'])

    KeyError:“导出链接”

    #!/usr/bin/env python
    
    from __future__ import print_function
    import os
    
    from apiclient import discovery
    from httplib2 import Http
    from oauth2client import file, client, tools
    
    SCOPES = 'https://www.googleapis.com/auth/drive'
    store = file.Storage('storage.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES)
        creds = tools.run_flow(flow, store)
    DRIVE = discovery.build('drive', 'v2', http=creds.authorize(Http()))
    
    FILES = (('hello.txt', False),)
    
    for filename, convert in FILES:
        metadata = {'title': filename}
        res = DRIVE.files().insert(convert=convert, body=metadata,
                media_body=filename, fields='mimeType,exportLinks').execute()
        if res:
            print (res['exportLinks'])
    

    有没有其他方法可以做到这一点。

    提前谢谢。

    1 回复  |  直到 7 年前
        1
  •  2
  •   user10417531 user10417531    7 年前

    我发现 this page ,表示您可以通过调用 file.get('id') -就是 res.get('id') 就你而言。

        # ...
        res = DRIVE.files().insert(convert=convert, body=metadata,
            media_body=filename, fields='mimeType,exportLinks,id').execute() # <-- EDIT: added id here
        print('Uploaded file to {url}'.format(url='https://drive.google.com/open?id=' + res.get('id')))