Exception Value: DatabaseWrapper objects created in a thread can only be used in that same thread.
問題描述:
使用django框架實現的web后端服務,使用orm語句插入數據時報錯,報錯信息如下;
django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias ‘default’ was created in thread id 8576 and this is thread id 11652
報錯代碼位置如圖。
問題分析:
項目本地調試是完全ok的,部署到服務器上就出現這個問題。
1.好了開始對代碼做各種排查,發現並沒有問題。
2.然后開始各種github搜索問題,這個問題出現的頻率也不高,最終找到兩個比較符合說法
- gevent模塊開線程的沖突:https://blog.csdn.net/u014007037/article/details/86645862
- gunicorn起服務的沖突:https://github.com/benoitc/gunicorn/issues/927
問題解決
突然想到,我們項目開始使用uwsgi啟動服務的,也是在問題發生前換成了gunicorn部署,於是趕緊換回uwsgi來啟動服務,成功了!!
查看了gunicorn的配置文件,發現里面也調用了gevent的模塊。
這樣的話,大概率就是gevent的問題了。