'Gmail API python batch request "service.users().messages().list"

I have this piece of code:

def get_user_messages_ids():
    email_list = mongo_client.email_list
    users = email_list.find()
    for user in users:
        delegated_credentials = creds.with_subject(user['email'])
        service = build('gmail', 'v1', credentials=delegated_credentials)
        results = service.users().messages().list(maxResults=400, userId=user['email']).execute()
        print(results.get('messages', []))

This code works, but the problem is performance. We have 2500 users and it takes 34 minutes to complete this loop. I read about batching, but I can't do it due to the fact that I need to create a separate service with credentials (variable - delegated_credentials) for each request to create a service. Has anyone had the same problem and what is the solution?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source