0

I'm wondering whether it is safe to use global variables in my Alexa Skill. Here is my setup:

* Python skill using flask-ask
* Deployed using Zappa as aws-lambda function
* Accessed over the AWS API gateway 
* Is an endpoint for an Alexa Skill with multiple languages

Consequently, I must identify each users language at the beginning. Then I must serve him the dialogues in this language for the remainder of the interaction. My idea is to use the on_session_started decorator. Something like this:

@ask.on_session_started
def new_session():
    global LANG
    if x:
        LANG = "EN"
    else:
        LANG = "DE"

There are several issues at play here. Because everything is so intertwined I'm really unsure about potential issues. In particular my uncertainty has to do with these aspect:

  • Lambda functions run in containers. On consecutive calls either the same container is used or a new one is created.
    1. How does this affect flask-ask in general?
    2. How does this affect a user session, which consists of multiple questions <-> answers?
  • Since I use the on_session_started decorator the global variable is only set once, at the beginning of the session:
    • How does this affect 2.? Could it be that between the first user request and the second request Lambda uses a new container and LANG is reset? Or is the same flask(-ask) instance active until the session ends?
mc51
  • 1,883
  • 14
  • 28
  • 1
    I've never looked into Alexa before, but Isn't that (storing persistent data) what the [session object](https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#session-object) is for? – larsks Jan 06 '18 at 20:49
  • Yes, you're right. Also, the user's locale is also transmitted with each request. Actually, this is where I take the information about his language. – mc51 Jan 06 '18 at 20:59

1 Answers1

4

Global variables are very problematic in Lambda based Alexa skills. Their lifetime is uncertain, and may be shared between different users of your skill. I've been burned by using these before, and the result was intermittent problems that were tough to debug.

It's best to use the session object, a database such as dynamoDB, or just pass variables between functions as needed. That way you will have complete control over how long they live, and who/what can see them.

Ron Lisle
  • 1,164
  • 6
  • 11