我有一个相当大的应用程序,使用Flask,Flask-SQLAlchemy和Flask Whoosh Alchemy进行搜索。当我在本地运行时,一切都很好用。出于某种原因,当我用gunicorn部署它时,我得到SQLAlchemy抱怨会话问题。我得到了:
Object '<School at 0x7fdc2dfbaa10>' is already attached to session '15' (this is '1')
这不会在本地发生。这只发生在使用gunicorn的生产中。我用以下命令运行gunicorn:
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
首先要杀死端口8000上的任何内容然后我使用4个工作程序并将超时设置为120并将其设置为记录到特定位置。
有问题的代码就是我设立学校。
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))
...
我不完全理解为什么将学校设置为全局变量会让SQLAlchemy抱怨。我还没能找到与此特定问题相关的任何内容。我觉得这与gunicorn是多线程的事实有关。