0

I'm using Flask in combination with Huey to process long-running tasks out of context. So in essence, a flask context is started by one of the Huey consumers (a worker process) and it does a lot of work that takes some time. In this process I use the Flask global 'g' object to store a user.

@staticmethod
def CurrentUser():
    if g:
        if hasattr(g, 'usr'):
            user = g.usr
        else:
            # no user is linked to g yet - see if we can find and load one by searching for a UUID in the cookies
            user = UserStateManager.LoadUserState()
            g.usr = user
    else:
        # no g object - maybe we are running outside of the flask context - use a default user
        user = UserStateManager.DefaultUserstate()

    return user

The problem is that after 20 minutes or so the g.usr object is suddenly gone. It's a hard to debug problem, because the code at that point is being run by a Huey task worker, and I can't run this inside an IDE. (Well, I can, but the context is different, so it's a different situation).

I can see it starts out fine, because it writes records to the database that include a user-id, but after about twenty minutes, the user-id fields are suddenly empty. It would almost seem as though the g-object is cleaned up somewhere.

So my question is if anyone knows what might trigger the disapperance of the usr data in the g-object. Is there a timeout, or some form of garbage collection going on for the g-object?

Erik Oosterwaal
  • 4,272
  • 3
  • 44
  • 64

1 Answers1

0

The g will have the information as long as the request is alive.

g is bounded to the application context, and will be in memory till de request ends.

It's definitely not a good place to store your user information for task queues

Rafael Marques
  • 1,501
  • 15
  • 23
  • I know it will. In this situation the flask app is not running under a webserver, it is more like a script that has Flask for configuration (described here:). So there is no real "request" just a script that uses Flask for configuration. I expected the g-object to remain intact as long as the Flask context is not finished. – Erik Oosterwaal Jan 09 '19 at 15:12