【问题标题】:How to store Google Auth Credentials object in Django?如何在 Django 中存储 Google Auth Credentials 对象?
【发布时间】:2020-01-19 19:06:34
【问题描述】:

我正在尝试将 Google 跟踪代码管理器集成到我的项目中。在官方文档中,Google 建议使用 oauth2client 库。不幸的是,该库已弃用。我使用了 google_auth_oauthlib。我可以使用此令牌获取令牌并向 Google Tag Manager API 发送请求。但我不决定如何在 Django 中存储凭据对象。在 oauth2client 库中,模型有 CredentialsField。我们可以使用 DjangoORMStorage 在此字段中存储 Credentials 对象。但我不能使用这个已弃用的库。有没有其他的方法?

Google 跟踪代码管理器文档是 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)

【问题讨论】:

    标签: django python-3.x google-tag-manager google-authentication oauth2client


    【解决方案1】:

    只需切换到 Django 2 pip install Django==2.2.12 我做到了,效果很好

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 2019-10-22
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多