首页 > 解决方案 > 如何使带有 Oauth 的 python 命令行工具在 lambda 中工作?

问题描述

嗨,我尝试让这个 python 工具在 python lambda 中运行。

https://github.com/googleapis/google-api-python-client/tree/master/samples/searchconsole

目前,我坚持为 Oauth 加载 client_secrets.json。

出于测试目的,我对其进行了一些更改

from googleapiclient import sample_tools
from datetime import datetime, timedelta

def main():
  testday = datetime.now() - timedelta(days=3)
  start_date = testday.strftime('%Y-%m-%d')
  end_date = testday.strftime('%Y-%m-%d')
  property_uri = 'https://www.example.com'
  print(start_date)


  service, flags = sample_tools.init(
      [], 'webmasters', 'v3', __doc__, __file__, parents=[],
      scope='https://www.googleapis.com/auth/webmasters.readonly')

  # Get totals for the date range.
  request = {
      'startDate': start_date,
      'endDate': end_date
  }
  response = execute_request(service, property_uri, request)
  print(response)

  #Get top 10 queries for the date range, sorted by click count, descending.
  request = {
    'startDate': start_date,
    'endDate': end_date,
    'dimensions': ['query'],
    'rowLimit': 10
  }
  response = execute_request(service, property_uri, request)
  print(response)

def execute_request(service, property_uri, request):
  return service.searchanalytics().query(
      siteUrl=property_uri, body=request).execute()

def lambda_handler(event, context):
    main()

    return {
        'statusCode': 200,
        'body': 'gugus'
    }

我对现在按照本指南工作的库有一些问题

https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html#python-package-venv

我愿意:

python3 -m venv v-env
source v-env/bin/activate
pip install google-api-python-client
pip install --upgrade oauth2client
pip install Pillow
deactivate
cd v-env/lib/python3.7/site-packages
zip -r9 ${OLDPWD}/function.zip .
cd $OLDPWD
zip -g function.zip lambda_function.py
aws lambda update-function-code --function-name GSCPython --zip-file fileb://function.zip

我现在的问题是 client_secrets.json 和可能带有令牌的 webmasters.dat 文件不起作用。可能我需要以某种方式将它们包含到function.zip中?这个怎么做。

不确定身份验证过程是否适用于 --noauth_local_webserver

最初的想法是不使用文件,而是将 client_id 和 client_secret 存储为环境变量,但是 sample_tools 在这里并不是很灵活。我也很高兴提示如何改变它?

谢谢

标签: pythonlambdaoauthgoogle-apigoogle-api-python-client

解决方案


推荐阅读