I am working on a little web app to help me manage my gmail. I have set it up through Google's API with the following function using the OAuth token I received through django-allauth
.
import google.oauth2.credentials
from .choices import GMAIL
from allauth.socialaccount.models import SocialToken, SocialAccount
from apiclient.discovery import build
def get_credentials(user):
account = SocialAccount.objects.get(user=user.id)
token = SocialToken.objects.get(app=GMAIL, account=account).token
credentials = google.oauth2.credentials.Credentials(token)
service = build('gmail', 'v1', credentials=credentials)
return service
This seems to work sometimes, but unfortunately, it isn't very reliable. It times out frequently at the build()
function, only succeeding about a third of the time. I am wondering what could cause this behavior and if there is a more reliable way to access the API?
I found the following AuthorizedSession
class from these docs:
from google.auth.transport.requests import AuthorizedSession
authed_session = AuthorizedSession(credentials)
response = authed_session.request(
'GET', 'https://www.googleapis.com/storage/v1/b')
But I don't know how to turn it into the kind of object that works with Google's API:
def get_labels(user):
service = get_credentials(user)
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
return labels
Unfortunately, Google's docs recommend using a deprecated package that I was hoping to avoid.
This is my first time really using an OAuth-enforced API. Does anyone have any advice?
EDIT: I posted after trying from my Macbook. I tried it on my Windows machine as well, where it works more consistently, but it takes about 20 seconds each time just to do build()
. I feel like I am doing something wrong.