问题描述
我想使用 GEVENT
发出异步HTTP POST请求 - 我不关心的回应,我只是想尽快执行请求可能。但是,每当我试图这样做使用 gevent.spawn
,请求不会被执行。我知道这是因为调用。就绪()
或 .successful()
的方法 Greenlet
是从 gevent.spawn
返回总是返回假
。
I'd like to issue an asynchronous HTTP POST request using gevent
-- I don't care about the response, I simply want to execute the request as soon as possible. However, whenever I attempt to do so using gevent.spawn
, the request never executes. I know this because calling the .ready()
or .successful()
methods on the Greenlet
that is returned from gevent.spawn
always returns False
.
不过,Greenlet的的的开始,因为如果我叫 glet = gevent.spawn(...)
,那么 glet.start()
,我得到一个错误说的AssertionError:Greenlet已经开始
However, the Greenlet has started, because if I call glet = gevent.spawn(...)
, then glet.start()
, I get an error saying AssertionError: Greenlet already started
.
我唯一一次获得 glet.ready()==真
是,当我打电话 glet.join()
,但是这是一个阻塞操作。我怎么能有Greenlet执行,而不必等待它完成呢?
The only time I get a glet.ready() == True
is when I call glet.join()
, but this is a blocking operation. How can I have the Greenlet execute without waiting for it to complete?
推荐答案
由于greenlets是合作,您的新greenlet将无法运行,直到你得到它。调用产卵后,调用 gevent.sleep(0)
来产生和你greenlet应该运行。
Since greenlets are cooperative, your new greenlet won't run until you yield to it. After calling spawn, call gevent.sleep(0)
to yield and your greenlet should run.
它将继续运行,直到它做一些事情,导致它产生(如蹬掉了HTTP REQ)。然后你的其他code可以再次恢复。
It will continue to run until it does something that causes it to yield (like kicking off that http req). Then your other code can resume again.
编辑:
要解决你关于 grequests
)的问题时, grequests.send(
医生说:
To address your question about grequests
, the grequests.send()
doc says:
send(r, pool=None, stream=False)
Sends the request object using the specified pool. If a pool isn't
specified this method blocks. Pools are useful because you can specify size
and can hence limit concurrency
因为我们还没有指定一个游泳池,您greenlet的请求块来完成。换句话说,一旦返回greenlet已经完成。获得响应,请参阅 glt.get()
返回greenlet的。
Since you have not specified a pool, the request blocks for your greenlet to finish. In other words, once it returns the greenlet has already completed. To get the response, see glt.get()
of the returned greenlet.
这篇关于为什么gevent.spawn不执行参数化的功能,直到Greenlet.join打个电话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!