Unrecognized arguments using oauth2 and Google APIs

前端 未结 1 1958
一向
一向 2021-01-19 16:56

I\'m using the Google API services in some scripts and having some problems. This error is something weird, but here we go. I have a script that is listing my Google Drive f

相关标签:
1条回答
  • 2021-01-19 17:44

    This is happening because you are importing the oauth2client.tools module.

    To work correctly this module relies on the standard argparse module. In case you don't know, this standard module is used to write user-friendly command-line interfaces with easy management of command line arguments. This does not get along with your usage of sys.argv[1] and sys.argv[2] arguments.

    To work around this, you can add new arguments to the command line like in the sample below. With this modification you would then run the tool like this

    python3 drive_list.py -ci "your_client_id" -cs "your_client_secret"
    

    Here is your code slightly modified to add the new command line arguments:

    import argparse
    from apiclient import discovery
    from httplib2 import Http
    from oauth2client import file, client, tools
    
    # ID and SECRET arguments as new command line parameters
    # Here is where you extend the oauth2client.tools startnd arguments
    tools.argparser.add_argument('-ci', '--client-id', type=str, required=True, help='The client ID of your GCP project')
    tools.argparser.add_argument('-cs', '--client-secret', type=str, required=True,
                                 help='The client Secret of your GCP project')
    
    SCOPES = 'https://www.googleapis.com/auth/drive.readonly.metadata'
    
    
    def list_files(drive):
        """Receive the service and list the files"""
        files = drive.files().list().execute().get('files', [])
        for f in files:
            print(f['name'], f['mimeType'], f['id'])
    
    
    def main():
        store = file.Storage('storage.json')
        creds = store.get()
        if not creds or creds.invalid:
            # You want to be sure to parse the args to take in consideration the new parameters
            args = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
            flow = client.OAuth2WebServerFlow(args.client_id, args.client_secret, SCOPES)
            creds = tools.run_flow(flow, store, tools.argparser.parse_args())
        drive_sdk = discovery.build('drive', 'v3', http=creds.authorize(Http()))
        list_files(drive_sdk)
    
    
    if __name__ == "__main__":
        main()
    
    0 讨论(0)
提交回复
热议问题