Search code examples
pythondjangosqlitegevent

Using gevent in custom Django management command


I'm trying to do a hello world with gevent and a Django management command.

from gevent import monkey
monkey.patch_all()

from django.core.management.base import BaseCommand


class Command(BaseCommand):
    # https://docs.djangoproject.com/en/1.11/howto/custom-management-commands/

    def add_arguments(self, parser):
        parser.add_argument(
            '--since',
            dest='since',
            type=int
        )

    def handle(self, *args, **options):
        self.stdout.write(str(options['since']))

Without trying to use gevent or access the Database, this gives me:

Traceback (most recent call last):
  File "./manage.py", line 24, in <module>
    execute_from_command_line(sys.argv)
  File "env/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "env/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "env/lib/python3.6/site-packages/django/core/management/base.py", line 296, in run_from_argv
    connections.close_all()
  File "env/lib/python3.6/site-packages/django/db/utils.py", line 234, in close_all
    connection.close()
  File "env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 221, in close
    self.validate_thread_sharing()
  File "env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 542, in validate_thread_sharing
    % (self.alias, self._thread_ident, thread.get_ident())
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 140735610057536 and this is thread id 4446749960.

This is with Django 1.11.4 and gevent 1.2.2.


Solution

  • Put the call to patch_all in your manage.py script, you noob.