Skip to content

SynchronousOnlyOperation exception while running django on gevent workers #3429

@peekuh

Description

@peekuh

I'm having trouble getting the gevent worker type to serve my django application. Here's what I've done so far:

in my wsgi.py file, called the patch_all method.

import os

from django.core.wsgi import get_wsgi_application

if os.environ.get('GEVENT_ENABLED', 'false').lower() == 'true':
    from gevent import monkey
    monkey.patch_all() 

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')

application = get_wsgi_application()

this is the command I use to deploy the application:

.venv/bin/python3.13 -m gunicorn --workers 4 --worker-class gevent --bind 0.0.0.0:8000 myapp.wsgi:application

here's the View I see the error on (just one of many endpoints that are failing with the same error)

from django.contrib.auth import login, authenticate
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.authtoken.models import Token

class LoginView(UserSerializerMixin, APIView):
    permission_classes = [AllowAny]
    serializer_class = LoginSerializer
    throttle_scope = 'login'
    
    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        email = serializer.validated_data['email']
        password = serializer.validated_data['password']
        
        user = authenticate(request, username=email, password=password)
        
        if user is not None:            
            token, created = Token.objects.get_or_create(user=user)
            
            response = JsonResponse({
                'token': token.key,  
                'user':  self.serialize_user_data(user)
            })

            return response
        
        return Response({"error": "Invalid credentials"}, status=status.HTTP_400_BAD_REQUEST)

Full traceback of the error

 Exception ignored in: <function _after_fork at 0x706e6bf4d120>
 Traceback (most recent call last):
   File "/python/cpython-3.13-linux-x86_64-gnu/lib/python3.13/threading.py", line 1588, in _after_fork
     thread._after_fork(new_ident=ident)
   File "/python/cpython-3.13-linux-x86_64-gnu/lib/python3.13/threading.py", line 1424, in _after_fork
     Thread._after_fork(self, new_ident=new_ident)
   File "/python/cpython-3.13-linux-x86_64-gnu/lib/python3.13/threading.py", line 934, in _after_fork
     assert self._handle.ident == new_ident
 AttributeError: '_DummyThread' object has no attribute '_handle'
 Exception ignored in: <bound method _ForkHooks.after_fork_in_child of <gevent.threading._ForkHooks object at 0x706e6b6f4c20>>
 Traceback (most recent call last):
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/gevent/threading.py", line 376, in after_fork_in_child
     assert len(active) == 1
 AssertionError:
 Exception ignored in: <function _after_fork at 0x706e6bf4d120>
 Traceback (most recent call last):
   File "/python/cpython-3.13-linux-x86_64-gnu/lib/python3.13/threading.py", line 1588, in _after_fork
     thread._after_fork(new_ident=ident)
   File "/python/cpython-3.13-linux-x86_64-gnu/lib/python3.13/threading.py", line 1424, in _after_fork
     Thread._after_fork(self, new_ident=new_ident)
   File "/python/cpython-3.13-linux-x86_64-gnu/lib/python3.13/threading.py", line 934, in _after_fork             
     assert self._handle.ident == new_ident
 AttributeError: '_DummyThread' object has no attribute '_handle'
 Exception ignored in: <bound method _ForkHooks.after_fork_in_child of <gevent.threading._ForkHooks object at 0x706e6b6f4c20>>
 Traceback (most recent call last):
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/gevent/threading.py", line 376, in after_fork_in_child                                                                                                                             
     assert len(active) == 1
 AssertionError: 
 [2025-10-20 19:20:14,162] ERROR [django.request] Internal Server Error: /api/v1/auth/login/                      
 Traceback (most recent call last):
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/core/handlers/exception.py", line 55, in inner
     response = get_response(request)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/core/handlers/base.py", line 197, in _get_response
     response = wrapped_callback(request, *callback_args, **callback_kwargs)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper
     return view_func(request, *args, **kwargs)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/views/generic/base.py", line 104, in view    
     return self.dispatch(request, *args, **kwargs)
            ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/rest_framework/views.py", line 509, in dispatch     
     response = self.handle_exception(exc)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/rest_framework/views.py", line 469, in handle_exception
     self.raise_uncaught_exception(exc)
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
     raise exc
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/rest_framework/views.py", line 506, in dispatch     
     response = handler(request, *args, **kwargs)
   File "/opt/app-root/src/users/views.py", line 59, in post
     user = authenticate(request, username=email, password=password)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/views/decorators/debug.py", line 75, in sensitive_variables_wrapper
     return func(*func_args, **func_kwargs)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/contrib/auth/__init__.py", line 79, in authenticate
     user = backend.authenticate(request, **credentials)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/contrib/auth/backends.py", line 42, in authenticate
     user = UserModel._default_manager.get_by_natural_key(username)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/contrib/auth/base_user.py", line 37, in get_by_natural_key
     return self.get(**{self.model.USERNAME_FIELD: username})
            ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/manager.py", line 87, in manager_method
     return getattr(self.get_queryset(), name)(*args, **kwargs)
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 645, in get        
     num = len(clone)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 382, in __len__    
 [2025-10-20 19:20:14,162] ERROR [django.request] Internal Server Error: /api/v1/auth/login/
     self._fetch_all()
     ~~~~~~~~~~~~~~~^^
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 1928, in _fetch_all
     self._result_cache = list(self._iterable_class(self))
                          ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 91, in __iter__    
     results = compiler.execute_sql(
         chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
     )
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/sql/compiler.py", line 1572, in execute_sql
     cursor = self.connection.cursor()
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/utils/asyncio.py", line 24, in inner
     raise SynchronousOnlyOperation(message)
 django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
 Traceback (most recent call last):
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/core/handlers/exception.py", line 55, in inner                                                                                                                              
     response = get_response(request)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/core/handlers/base.py", line 197, in _get_response                                                                                                                          
     response = wrapped_callback(request, *callback_args, **callback_kwargs)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper
     return view_func(request, *args, **kwargs)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/views/generic/base.py", line 104, in view    
     return self.dispatch(request, *args, **kwargs)
            ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/rest_framework/views.py", line 509, in dispatch     
     response = self.handle_exception(exc)                                                                        
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/rest_framework/views.py", line 469, in handle_exception                                                                                                                            
     self.raise_uncaught_exception(exc)
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^                                                                           
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception                                                                                                                    
     raise exc
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/rest_framework/views.py", line 506, in dispatch
     response = handler(request, *args, **kwargs)                                                                 
   File "/opt/app-root/src/users/views.py", line 59, in post                                                      
     user = authenticate(request, username=email, password=password)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/views/decorators/debug.py", line 75, in sensitive_variables_wrapper                                                                                                         
     return func(*func_args, **func_kwargs)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/contrib/auth/__init__.py", line 79, in authenticate                                                                                                                         
     user = backend.authenticate(request, **credentials)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/contrib/auth/backends.py", line 42, in authenticate                                                                                                                         
     user = UserModel._default_manager.get_by_natural_key(username)
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/contrib/auth/base_user.py", line 37, in get_by_natural_key                                                                                                                  
     return self.get(**{self.model.USERNAME_FIELD: username})
            ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                                                     
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/manager.py", line 87, in manager_method                                                                                                                           
     return getattr(self.get_queryset(), name)(*args, **kwargs)
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 645, in get        
     num = len(clone)                                                                                             
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 382, in __len__
     self._fetch_all()                                                                                            
     ~~~~~~~~~~~~~~~^^
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 1928, in _fetch_all
     self._result_cache = list(self._iterable_class(self))                                                        
                          ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/query.py", line 91, in __iter__    
     results = compiler.execute_sql(
         chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size                                             
     )                                                                                                            
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/db/models/sql/compiler.py", line 1572, in execute_sql                                                                                                                       
     cursor = self.connection.cursor()
   File "/opt/app-root/src/.venv/lib/python3.13/site-packages/django/utils/asyncio.py", line 24, in inner         
     raise SynchronousOnlyOperation(message)                                                                      
 django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions