[英]How do I yield to another request when using gunicorn with asyncio?
I'm trying to use the gaiohttp worker in Gunicorn with a Django app I'm developing with the following command: 我正在尝试将Gunicorn中的gaiohttp worker与正在使用以下命令开发的Django应用程序配合使用:
gunicorn -k gaiohttp -b localhost:8080 myproject.wsgi
My ultimate goal is to be able to process requests concurrently - ie have 1 gunicorn worker process multiple requests concurrently. 我的最终目标是能够同时处理请求-即让一名gunicorn工人同时处理多个请求。 There are I/O bound operations which makes these requests slow.
有I / O绑定操作,这些操作使这些请求变慢。
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
...
Questions: 问题:
How can I perform an operation such as yield from asyncio.sleep(10)
within my view code? 如何在我的视图代码中执行诸如
yield from asyncio.sleep(10)
的操作?
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())
Clearly there's something I'm not understanding about asyncio or gaiohttp. 显然,我对asyncio或gaiohttp尚不了解。
How can I have asyncio.sleep(10)
block for the current requests, but not block gunicorn from processing other requests? 如何为当前请求设置
asyncio.sleep(10)
阻止,但不阻止gunicorn处理其他请求?
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). 抱歉,您无法从wsgi应用程序调用协程-WSGI是同步协议,以及在其之上构建的框架(Django,Flask,Pyramid)。
I've implemented gaiohttp
worker but it's second class citizen in asyncio world. 我实现了
gaiohttp
worker,但它是asyncio世界中的二等公民。 If you really need asynchronous HTTP server please try aiohttp.web . 如果您确实需要异步HTTP服务器,请尝试aiohttp.web 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.