2

I have a fairly large app which is using Flask, with Flask-SQLAlchemy and Flask Whoosh Alchemy for searching. Everything works great when I run it locally. For some reason when I deploy it with gunicorn I get SQLAlchemy complaining of session issues. I am getting:

 Object '<School at 0x7fdc2dfbaa10>' is already attached to session '15' (this is '1')

This does not happen locally. This only happens in production with gunicorn. I run gunicorn with the following command:

lsof -ti:8000 | xargs kill -9 && gunicorn serve:app -b 127.0.0.1:8000 --daemon -w4 -t120 --log-level=DEBUG --log-file=/home/me/uhoh.log && tail -f uhoh.log

First to kill anything on port 8000 then I use 4 workers and a timeout of 120 and set it to log to a specific place.

The code in question is just me setting a school.

def post(self):
    groups_form = GroupsForm(request.form)
    ok = True
    if not groups_form.kids.data:
        ok = False
    if not groups_form.staff.data:
        ok = False
    groups_form.kids.choices = [(k,'x') for k in groups_form.kids.data]
    groups_form.staff.choices = [(s,'x') for s in groups_form.staff.data]
    if groups_form.validate():
        group = Group()
        group.name = groups_form.name.data
        group.kids = []
        for kid in groups_form.kids.data:
            group.kids.append(Kid.query.get(kid))

        for kid in group.kids:
            kid.current_group = groups_form.name.data
        group.school = g.current_school //This is the line the error is complaining about. 
        group.staff = []
        for user in groups_form.staff.data:
            group.staff.append(User.query.get(user))
        ...

I don't totally understand why setting the school to a global variable would make SQLAlchemy complain. I haven't been able to find anything related to this specific issue. I have a feeling it has to do with the fact that gunicorn is multithreaded.

Johnston
  • 20,196
  • 18
  • 72
  • 121

0 Answers0