2017-08-02 73 views
0

所以我读过这篇文章:Adding session attributes in Python for Alexa skills它解决了我能够存储多个会话变量的问题。在Python中调用会话变量以获得Alexa技能

但是,现在我的问题是回忆这些会话变量在另一个函数。这里是什么,我试图做一个例子:

speech_output = "Your invoice for " + session['attributes']['invoiceAmount'] + \ 
       " dollars." 

我也试过这种代码来设置本地变量session变量:

invoice_amount = int(session['attributes']['invoiceAmount']) 

我在做什么错?我之前从未使用Python进行过编程,所以我只是通过查看Amazon最喜欢的颜色示例代码并根据自己的需要进行调整来教自己。我实际上有三个会话变量,但显然如果我可以让他们中的一个工作,我可以找出另一个。谢谢。

回答

0

您的问题很可能涉及session变量的范围。

以下代码是来自颜色专家技能的意图调用。 正如您在第1行中看到的,变量session被定义为参数。在第12行,该变量被传递给函数set_color_in_session(intent,session)

def on_intent(intent_request, session): # <------------- 
    """ Called when the user specifies an intent for this skill """ 

    print("on_intent requestId=" + intent_request['requestId'] + 
      ", sessionId=" + session['sessionId']) 

    intent = intent_request['intent'] 
    intent_name = intent_request['intent']['name'] 

    # Dispatch to your skill's intent handlers 
    if intent_name == "MyColorIsIntent": 
     return set_color_in_session(intent, session) # <------------- 
    elif intent_name == "WhatsMyColorIntent": 
     return get_color_from_session(intent, session) # <------------- 
    elif intent_name == "AMAZON.HelpIntent": 
     return get_welcome_response() 
    else: 
     raise ValueError("Invalid intent") 

从提供的信息,我相信你定义自己的功能通过定制意图被解雇,最容易忘记的session变量传递给这些函数。再次,变量session将只存在于你的函数中,如果它作为参数传入的话。以功能def get_color_from_session(intent, session):为例。由于session作为参数传入,因此它在第6行的此函数中可用,favorite_color = session['attributes']['favoriteColor']

如果您没有传入变量session,那么您将引用一个名为session的本地变量,该变量可能不存在。

def get_color_from_session(intent, session): 
    session_attributes = {} 
    reprompt_text = None 

    if "favoriteColor" in session.get('attributes', {}): 
     favorite_color = session['attributes']['favoriteColor'] #<------------- 
     speech_output = "Your favorite color is " + favorite_color + \ 
         ". Goodbye." 
     should_end_session = True 
    else: 
     speech_output = "I'm not sure what your favorite color is. " \ 
         "You can say, my favorite color is red." 
     should_end_session = False 

    # Setting reprompt_text to None signifies that we do not want to reprompt 
    # the user. If the user does not respond or says something that is not 
    # understood, the session will end. 
    return build_response(session_attributes, build_speechlet_response(
     intent['name'], speech_output, reprompt_text, should_end_session)) 
+0

我不知道,但我检查了我的代码,并且确实将session变量通过on_intent函数传递给每个函数,因为我只是剪切并粘贴原始代码并更改了意图和函数的名称。 但是,我链接到上面的其他文章最后有关于手动创建lambda处理程序的代码。我不知道我应该在哪里放置该代码。这可能是问题吗? –

1

我真的很抱歉,我终于明白了错误。我的会话变量存储整数,但我试图连接这些整数与文本。我没有意识到我需要先将它们转换为字符串。我转换为一个字符串,并解决了我所有的问题。

+0

你可以删除这个问题吗? –

+0

它说我不应该删除问题,当我点击删除。 –