def lambda_handler()

in src/main/python/CommandHander/command_handler.py [0:0]


def lambda_handler(event, context):
  LOGGER.info(event)

  http_method = event['httpMethod']
  if http_method != 'POST':
    response = {
      'statusCode': 405,
      'body': json.dumps({'error': 'mehtod not allowed'}),
      'isBase64Encoded': False
    }
    return response

  query = json.loads(event['body'])
  query_output_location = query['ResultConfiguration']['OutputLocation']
  url_parse_result = urlparse(query_output_location, scheme='s3')
  s3_bucket_name = url_parse_result.netloc
  if s3_bucket_name != ATHENA_QUERY_OUTPUT_BUCKET_NAME:
    response = {
      'statusCode': 400,
      'body': json.dumps({'error': 'invalid output_location'}),
      'isBase64Encoded': False
    }
    return response

  athena_work_group = query.get('WorkGroup', ATHENA_WORK_GROUP_NAME)
  if athena_work_group != ATHENA_WORK_GROUP_NAME:
    response = {
      'statusCode': 400,
      'body': json.dumps({'error': 'invalid athena work group'}),
      'isBase64Encoded': False
    }
    return response

  req_user_id = event['queryStringParameters']['user']

  athena_client = boto3.client('athena', region_name=AWS_REGION_NAME)
  try:
    response = athena_client.start_query_execution(**query)
    query_execution_id = response['QueryExecutionId']
    LOGGER.info('QueryExecutionId: %s' % query_execution_id)

    dynamodb = boto3.resource('dynamodb', region_name=AWS_REGION_NAME)
    ddb_table = dynamodb.Table(DDB_TABLE_NAME)

    expired_date = datetime.datetime.utcnow() + datetime.timedelta(days=7)
    #TODO: should handle ProvisionedThroughputExceededException
    ddb_table.put_item(Item={
      'user_id': req_user_id,
      'query_id': query_execution_id,
      'query_status': 'QUEUED',
      #XXX: The TTL attribute’s value must be a timestamp in Unix epoch time format in seconds.
      'expired_at': math.ceil(expired_date.timestamp())
    })

    response = {
      'statusCode': 200,
      'body': json.dumps(response),
      'isBase64Encoded': False
    }
  except Exception as ex:
    response = {
      'statusCode': 500,
      'body': repr(ex),
      'isBase64Encoded': False
    }
  return response