1

I'm trying integrate Google Tag Manager into my project. In official document, Google suggests oauth2client library. Unfortunately, this library deprecated. I used google_auth_oauthlib. I can get token and send request to Google Tag Manager API with this token. But I don't decide how can I store credentials object in Django. In oauth2client lib, there is CredentialsField for model. We can store Credentials object in this field with using DjangoORMStorage. But I can't use this deprecated library. Are there any alternative ways?

Google Tag Manager document is here

My codes here:

from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build

FLOW = Flow.from_client_secrets_file(
    settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
    scopes=[settings.GOOGLE_OAUTH2_SCOPE])

class GTMAuthenticateView(APIView):
    def get(self,request,**kwargs):
        FLOW.redirect_uri = settings.GOOGLE_OAUTH2_REDIRECT_URI
        authorization_url, state = FLOW.authorization_url(access_type='offline',
        include_granted_scopes='true')
        return Response({'authorization_url':authorization_url,'state':state})

    def post(self, request, **kwargs):
        FLOW.fetch_token(code=request.data['code'])
        credentials = FLOW.credentials
        return Response({'token':credentials.token})

class GTMContainerView(APIView):
    def get(self,request,**kwargs):
        service = get_service()
        containers = self.get_containers(service)
        return Response({'containers':str(containers),'credentials':str(FLOW.credentials)})

    @staticmethod
    def get_containers(service):
        account_list = service.accounts().list().execute()
        container_list = []
        for account in account_list['account']:
            containers = service.accounts().containers().list(parent=account["path"]).execute()
            for container in containers["container"]:
                container["usageContext"] = container["usageContext"][0].replace("['", "").replace("']", "")
                container_list.append(container)
        return container_list

def get_service():
    try:
        credentials = FLOW.credentials
        service = build('tagmanager', 'v2', credentials=credentials)
        return service
    except Exception as ex:
        print(ex)
kamilyrb
  • 2,502
  • 3
  • 10
  • 25

1 Answers1

0

Just switch over to Django 2 pip install Django==2.2.12 I did it and works fine