Search code examples
pythondjangopython-asynciouwsgi

How to make uWSGI main thread not serve requests for the Django web application?


In my Django application, in the __init__.py, I have a class which spins up an event loop.

class X:
  def __init__(self):
    self.__loop = asyncio.get_event_loop()

  async def foo(self):
    ...

  def do_stuff(self):
    # some logic here
    self.__loop.run_until_complete(foo())

In the __init__.py I just have

x = X()

In my Django views, I do

from myapp import x

def example_view(request):
  result = x.do_stuff()
  return JsonResponse({"result": result})

But the problem is that with uWSGI, if the thread that serves the request is same as that was used during initialization, I get the Django's SynchronousOnlyOperation exception as it detects a running event loop in that particular thread.

So my question is, is there a way not to use that initializing thread for serving requests or some other alternative to fix this issue?

uwSGI is configured to run multiple processes and multiple threads, with --enable-threads


Solution

  • How about this:

    class X:
    
        async def foo(self):
            ...
    
        def do_stuff(self):
            asyncio.run(foo())