При попытке подключиться к API Google Analytics через AWS Lambda, что означает этот «ModuleNotFoundError: ни один модуль с именем« google.appengine »» не означает - PullRequest
0 голосов
/ 22 мая 2019

Я пытаюсь подключиться к Google Analytics API через AWS Lambda, а затем извлекаю данные для помещения в экземпляр AWS RDS. Я могу подключиться к своей БД через Lambda, и скрипт отлично работает локально, но при попытке запустить его на Lambda я получаю ModuleNotFoundError: No module named 'google.appengine'.

Ничего не пытался решить эту проблему. Google искал Google Appengine и его часть SDK или что-то в этом роде. Хотите знать, что это значит с точки зрения попытки подключиться к лямбда и как действовать.

from __future__ import print_function
import argparse
import sys
import csv
from datetime import datetime

import pymysql
import googleapiclient.discovery

from googleapiclient.errors import HttpError
from googleapiclient import sample_tools
from oauth2client.client import AccessTokenRefreshError
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

def handler(event,context):
  main(sys.argv)

def main(argv):
    #Define the auth scopes to request.
    scope = 'https://www.googleapis.com/auth/analytics.readonly'
    key_file_location = 'serviceaccount.json'

    #Authenticate and construct service.
    service = get_service(

            api_name='analytics',
            api_version='v3',
            scopes=[scope],
            key_file_location=key_file_location)

    #profile_id = profile_id = '######'
    profile_id = profile_id = '########'
    date, sessions = print_results(get_ga_metrics(service,profile_id))
    write_to_sql(date,sessions)

def get_service(api_name, api_version, scopes, key_file_location):
    credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file_location, scopes=scopes)
    service = build(api_name, api_version, credentials=credentials)
    return service

def get_ga_metrics(service, profile_id):
  """Executes and returns data from the Core Reporting API.

  This queries the API for the top 25 organic search terms by visits.

  Args:
    service: The service object built by the Google API Python client library.
    profile_id: String The profile ID from which to retrieve analytics data.

  Returns:
    The response returned from the Core Reporting API.
  """

  return service.data().ga().get(
      ids='ga:' + profile_id,
      start_date='30daysAgo',
      end_date = 'yesterday',
      metrics='ga:sessions',
      dimensions='ga:date'
      ).execute()

def print_results(results):
    date =[]
    sessions =[]
    for row in results.get('rows'):
        date.append(row[0])  #loop thru new values in list to convert to datetime 
        sessions.append(row[1])

    #dateformatted =[]  
    #for dates in date:

         #date1 = datetime.strptime(dates,'%Y%m%d')
         #dateformatted.append(date1)
    dates = [datetime.strptime(x,'%Y%m%d').strftime('%Y-%m-%d') for x in date]

    #print(dateformatted,sessions)
    print(dates)
    return dates,sessions

def write_to_sql(date,sessions):
    db=pymysql.connect(host="################",user="###########",
                  passwd="#########",db="############")

    cur = db.cursor()                
    all_list = list(zip(date,sessions))

    sql = "INSERT INTO analytics (`date`,`sessions`) VALUES (%s,%s);"
    cur.executemany(sql,all_list)
    db.commit()
    cur.close()

main(sys.argv)

Это то, что я получаю, когда запускаю скрипт локально.

['2019-04-22', '2019-04-23', '2019-04-24', '2019-04-25', '2019-04-26', '2019-04-27', '2019-04-28', '2019-04-29', '2019-04-30', '2019-05-01', '2019-05-02', '2019-05-03', '2019-05-04', '2019-05-05', '2019-05-06', '2019-05-07', '2019-05-08', '2019-05-09', '2019-05-10', '2019-05-11', '2019-05-12', '2019-05-13', '2019-05-14', '2019-05-15', '2019-05-16', '2019-05-17', '2019-05-18', '2019-05-19', '2019-05-20', '2019-05-21']

Это ошибка, которую AWS Lambda бросает в меня.

START RequestId: 33b53026-5c40-4040-8bba-8d4d58cdc553 Version: $LATEST
[WARNING]   2019-05-22T17:23:32.437Z        file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth
Traceback (most recent call last):
  File "/var/task/googleapiclient/discovery_cache/__init__.py", line 36, in autodetect
    from google.appengine.api import memcache
ModuleNotFoundError: No module named 'google.appengine'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/task/googleapiclient/discovery_cache/file_cache.py", line 33, in <module>
    from oauth2client.contrib.locked_file import LockedFile
ModuleNotFoundError: No module named 'oauth2client.contrib.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/task/googleapiclient/discovery_cache/file_cache.py", line 37, in <module>
    from oauth2client.locked_file import LockedFile
ModuleNotFoundError: No module named 'oauth2client.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/var/task/googleapiclient/discovery_cache/__init__.py", line 41, in autodetect
    from . import file_cache
  File "/var/task/googleapiclient/discovery_cache/file_cache.py", line 41, in <module>
    'file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth')
ImportError: file_cache is unavailable when using oauth2client >= 4.0.0 or google-auth
END RequestId: 33b53026-5c40-4040-8bba-8d4d58cdc553
REPORT RequestId: 33b53026-5c40-4040-8bba-8d4d58cdc553  Duration: 10011.13 ms   Billed Duration: 10000 ms   Memory Size: 128 MB Max Memory Used: 30 MB  
2019-05-22T17:23:39.538Z 33b53026-5c40-4040-8bba-8d4d58cdc553 Task timed out after 10.01 seconds

1 Ответ

0 голосов
/ 22 мая 2019

Вам нужно отключить обнаружение кэша при создании службы:

service = build(
    api_name,
    api_version,
    credentials=credentials,
    cache_discovery=False,
)
...