将gunicorn与asyncio结合使用时,我如何屈服于另一个请求?
我正在尝试将Gunicorn中的gaiohttp工作者与我正在通过以下命令开发的Django应用程序配合使用:
I'm trying to use the gaiohttp worker in Gunicorn with a Django app I'm developing with the following command:
gunicorn -k gaiohttp -b localhost:8080 myproject.wsgi
我的最终目标是能够同时处理请求-即让一名gunicorn工作人员并发处理多个请求.有一些I/O绑定操作会使这些请求变慢.
My ultimate goal is to be able to process requests concurrently - i.e. have 1 gunicorn worker process multiple requests concurrently. There are I/O bound operations which makes these requests slow.
我知道在处理请求时已经在运行事件循环:
I know an event loop is already running when I'm processing a request:
class MyView(View):
def get(self, request):
loop = asyncio.get_event_loop()
loop.is_running() # True
...
问题:
-
如何在视图代码中执行acodeio.sleep(10)中的
yield之类的操作
?
class MyView(View):
def get(self, request):
# Raises AssertionError: yield from wasn't used with future
yield from asyncio.sleep(10)
我可以将任务添加到事件循环中,但是在处理请求时它们不会阻塞
I can add tasks to the event loop, however they don't block while processing the request
@asyncio.coroutine
def simulate_work():
yield from asyncio.sleep(10)
class MyView(View):
def get(self, request):
# This runs simulate_work(), however, it doesn't block
# the response is returned before simulate_work() is finished
loop = asyncio.get_event_loop()
task = loop.create_task(simulate_work())
我尝试使用期货,但是事件循环已经在运行
I try to use futures, but the event loop is already running
@asyncio.coroutine
def simulate_work(future):
yield from asyncio.sleep(10)
future.set_result('Done!')
class MyView(View):
def get(self, request):
future = asyncio.Future()
asyncio.async(simulate_work(future))
loop = asyncio.get_event_loop()
# Raises RuntimeError: Event loop is running.
loop.run_until_complete(future)
print(future.result())
很明显,我对asyncio或gaiohttp不太了解.
Clearly there's something I'm not understanding about asyncio or gaiohttp.
如何为当前请求提供 asyncio.sleep(10)
阻止,但不能阻止gunicorn处理其他请求?
How can I have asyncio.sleep(10)
block for the current requests, but not block gunicorn from processing other requests?
对不起,您不能从wsgi应用程序中调用协程-WSGI是同步协议,以及在其之上构建的框架(Django,Flask,金字塔).
Sorry, you cannot call coroutines from your wsgi application -- WSGI is synchronous protocol, as well as frameworks built on top of it (Django, Flask, Pyramid).
我已经实现了 gaiohttp
worker,但它是asyncio世界中的二等公民.如果您确实需要异步HTTP服务器,请尝试 aiohttp.web .
I've implemented gaiohttp
worker but it's second class citizen in asyncio world. If you really need asynchronous HTTP server please try aiohttp.web.