Python/Django 1.5 DatabaseWrapper thread error
Asked Answered
S

2

6

Throwing the following DatabaseError in Django 1.5.1 (and 1.5.0) and mysql when I runserver and attempt to load a local version of the web app:

DatabaseError at /

DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 4365488128 and this is thread id 140735183980896.

The exception location is as follows:

/Users/USERNAME/.envs/PROJECT_NAME/lib/python2.7/site-packages/django/db/backends/init.py in validate_thread_sharing, line 154

This happens only on the first page load. When I hit refresh the the web app loads as expected. The error returns when I alter Django/python code and the local server needs to re-validate. When that happens the first load once again throws the DatabaseError and subsequent loads once again do not.

This issue is only happening on my Django 1.5 projects. I've uninstalled mysql and cleared the mysql binary files located in /usr/local/var/mysql. A fresh install of mysql has not solved this issue.

A similar DatabaseError is discussed here but I'm not able to follow their solution:

https://code.djangoproject.com/ticket/17998

I'm at a loss here, any ideas or expertise would be appreciated. Thank you.

Sutton answered 25/4, 2013 at 17:10 Comment(3)
is your code using threads?Fireguard
I'm not touching threads, no. Basic Django installation, basic MySQL usage.Sutton
In what version of Django does the code work without an error?Zaxis
M
7

I solved the issue by monkey patching before imports of django.*:

import eventlet
eventlet.monkey_patch()

You understood than I use threads here.

Moustache answered 14/1, 2014 at 20:43 Comment(2)
Didn't work for me unfortunately. I changed from eventlet.monkey_patch() to eventlet.monkey_patch(socket=True) because I didn't need anything else for this: https://mcmap.net/q/93001/-timeout-for-python-requests-get-entire-response.Doi
If you are writing a custom management command, the 'monkey_patch' needs to go into your .manage.py file, or a copy of it.Lagan
Z
1

This is for 1.4, but the cause of the problem may be the same as yours:

https://bitbucket.org/akoha/django-digest/issue/10/conflict-with-global-databasewrapper

Two possible solutions in that post, though both appear to be workarounds:

"I have been able to fix the problem by commenting out close_connection in db.py"

"One fix that will definitely work is to replace MultiDb/get_default_db()/self.db by django.db.connection and django.db.tranasction as documented at: https://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly"

Zaxis answered 5/8, 2013 at 12:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.