lambda任务超时

时间:2018-04-11 00:47:05

标签: amazon-web-services aws-lambda alexa alexa-skills-kit

我正在Python 3.6中编写一个Lambda函数,它将Alexa技能连接到一个非常浅的MySQL数据库。我对lambda函数超时有些困难;我一直有时间错误。这是(最近的)错误:

{   “errorMessage”:“2018-04-11T00:29:23.341Z 49ebf0c0-3d1f-11e8-899e-61ea93a8a4cb任务在30.03秒后超时” }

我不认为这是我的代码。这就是原因。我基于Amazon Alexa Color Lambda'蓝图'构建了我的lambda,但该模板也不适用于我。我还尝试使用AWS CLI使用模板创建不同的lambdas,并得到相同的“Timed Out”错误。

这是我用来创建lambdas的命令:

aws lambda create-function \
    --region us-east-1 \
    --function-name WallyFlow \ 
    --zip-file fileb://~/wallyflow_lambda.zip \ 
    --runtime python3.6 \ 
    --profile wallyflow_admin \  
    --timeout 30 \ 
    --memory-size 1024 \ 
    --handler wallyflow_lambda.handler \ 
    --role arn:aws:iam::517237838660:role/lambda-s3-execution-role

注意:我正在使用此方法,因为我需要部署包来包含mysql库。

我尝试过不同的lambda函数(甚至不使用mysql的程序),将超时时间增加到300,并将内存加倍到2048.

我的想法是问题在于角色或个人资料,但是,即使我已经阅读了官方文档和补充材料,我也很难确定问题所在。

有人可以帮忙吗?

我已将下面的lambda函数包含在出现问题的概率中。

    import MySQLdb

    db = MySQLdb.connect(user="*****",
                     passwd="*****",
                     port=*****,
                     host="*****",
                     db="*****")
    cursor = db.cursor()


    def build_speechlet_response(title, output, reprompt_text, 
    should_end_session):
         return {
        'outputSpeech': {
            'type': 'PlainText',
            'text': output
        },
        'card': {
            'type': 'Simple',
            'title': "SessionSpeechlet - " + title,
            'content': "SessionSpeechlet -" + output
        },
        'reprompt':{
            'outputSpeech': {
                'type': 'PlainText',
                'text': reprompt_text
            }
        },
        'shouldEndSession': should_end_session
    }

def build_response(session_attributes, speechlet_response):
    return {
        'version': '1.0',
        'sessionAttributes': session_attributes,
        'response': speechlet_response
    }

########################################################
def get_welcome_response():
    session_attributes={}
    card_title = "Welcome"
    speech_output = "Welcome to Wally Flow, mindfulness with Walabot and Alexa."\
                    "How can I help you?"
    reprompt_text = "I'm sorry. I didn't catch that." \
                    "How can I help you?"

    should_end_session = False
    return build_response(session_attributes,
                          build_speechlet_response(card_title,speech_output,
                                                   reprompt_text,should_end_session))
def get_mst_response():
    session_attributes={}
    card_title = "Maximum Still Time"
    sql = "SELECT MaxStillTime FROM wallyflowdb.mstTable ORDER BY initTime DESC LIMIT 1"
    cursor.execute(sql)   
    mst = cursor.fetchone()
    speech_output = "Your maximum still time is set to {}.".format(mst[0])
    reprompt_text = None
    should_end_session = False
    return build_response(session_attributes,
                          build_speechlet_response(card_title,speech_output,
                                                   reprompt_text,should_end_session))
def get_mc_response():
    session_attributes={}
    card_title="Move Count"
    sql = "SELECT MoveCount FROM wallyflowdb.mcTable ORDER BY initTime DESC LIMIT 1"
    cursor.execute(sql)
    mc = cursor.fetchone()
    speech_output = "Your current movement count is {}.".format(mc[0])
    reprompt_text = None
    should_end_session = False
    return build_response(session_attributes,
                          build_speechlet_response(card_title,speech_output,
                                                   reprompt_text,should_end_session))
def get_stillTime_response():
    session_attributes={}
    card_title="Stillness Time"
    sql = "SELECT StillTime FROM wallyflowdb.stillTable ORDER BY initTime DESC LIMIT 1"
    cursor.execute(sql)
    stillTime = cursor.fetchone()
    speech_output = "Your current movement count is {}.".format(stillTime[0])
    reprompt_text=None
    should_end_session=False
    return build_response(session_attributes,
                          build_speechlet_response(card_title,speech_output,
                                                   reprompt_text,should_end_session))
def get_lmt_response():
    session_attributes={}
    card_title="Last Move Time"
    sql = "SELECT LastMoveTime FROM wallyflowdb.lmtTable ORDER BY initTime DESC LIMIT 1"
    cursor.execute(sql)
    lmt = cursor.fetchone()
    speech_output = "Your last move time was {}".format(lmt[0])
    reprompt_text=None
    should_end_session=False
    return build_response(session_attributes,
                          build_speechlet_response(card_title,speech_output,
                                                   reprompt_text,should_end_session))
def get_startTime_response():
    session_attributes = {}
    card_title="Start Time"
    sql = "SELECT StartTime FROM wallyflowdb.stTable ORDER BY initTime DESC LIMIT 1"
    cursor.execute(sql)
    startTime = cursor.fetchone()
    speech_output = "You started this mindfulness session at {}".format(startTime[0])
    reprompt_text=None
    should_end_session=False
    return build_response(session_attributes,
                          build_speechlet_response(card_title,speech_output,
                                                   reprompt_text,should_end_session))    
def handle_session_end_request():
    card_title = "Session Ended"
    speech_output = "Thank you for using Wally Flow, mindfulness with Walabot and Alexa."\
                    "Have a mindful day!"
    should_end_session = True
    return build_response({}, build_speechlet_response(
        card_title, speech_output, None, should_end_session))

###########################################################################
#Events

def on_session_started(session_started_request, session):
    #Called when session starts
    print("on_session_started requestId=" + session_started_request['requestId']
          +", sessionId=" +session['sessionId'])

def on_launch(launch_request, session):
    #Called when the user launches the skill without specifiying what they want
    print("on_launch requestId=" + launch_request['requestId'] +
          " , sessionId =" + session['sessionId'])
    #Dispatch to your skill's launch
    return get_welcome_response()

def on_intent(intent_request, session):
    #Called when the user specifies an intent for this skill
    print("on_intent requestId =" + intent_request['requestId'] +
          ", sessiodId=" + session['sessionId'])
    intent = intent_request['intent']
    intent_name = intent_request['intent']['name']

    if intent_name == "MaxStillTimeIntent":
        return get_mst_response()
    elif intent_name == "MoveCountIntent":
        return get_mc_response()
    elif intent_name == "StillTimeIntent":
        return get_stillTime_response()
    elif intent_name == "LastMoveTimeIntent":
        return get_lmt_response()
    elif intent_name == "StartTimeIntent":
        return get_startTime_response()
    elif intent_name == "AMAZON.HelpIntent":
        return get_welcome_response()
    elif intent_name == "AMAZON.CANCELIntent" or intent_name == "AMAZON.StopIntent":
        return handle_session_end_request()
    else:
        raise ValueError("Invalid intent")


def on_session_ended(session_ended_request, session):
    #Called when the user ends the session
    #Not called when the skil returns should_ends_session=True
    print("on_session_ended requestId=" + session_ended_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    #add cleanup logic here

###############################################################
#Main Handler
def wallyflow_lambda(event, context):
    """
    Route the incoming request based on type (LaunchRequest, IntentRequest, etc.)
    The JSON body of the request is provided in the event parameter
    """
    print("event.session.application.applicationId=" +
          event['session']['application']['applicationId'])

    if (event['session']['application']['applicationId'] !=
        "amzn1.ask.skill.1a61b436-2b39-448c-a2bb-1ad391fe666b"):
        raise ValueError("Invalid Application ID")

    if event['session']['new']:
        on_session_started({'requestId': event['request']['requestId']},event['session'])

    if event['request']['type'] == "LaunchRequest":
        return on_launch(event['request'],event['session'])
    elif event['request']['type'] == "IntentRequest":
        return on_intent(event['request'], event['session'])
    elif event['request']['type'] == "SessionEndedRequest":
        return on_session_ended(event['request'], event['session'])

0 个答案:

没有答案