简体   繁体   中英

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

How about this:

class X:

    async def foo(self):
        ...

    def do_stuff(self):
        asyncio.run(foo())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM