使用Bottlepy-Geven生成多个greenlets

2024-05-12 14:10:58 发布

您现在位置:Python中文网/ 问答频道 /正文

{py是一个新的异步编程教程。在

我运行了页面上给出的程序:

from gevent import monkey; monkey.patch_all()

from time import sleep
from bottle import route, run

@route('/stream')
def stream():
    yield 'START'
    sleep(3)
    yield 'MIDDLE'
    sleep(5)
    yield 'END'

run(host='0.0.0.0', port=8080, server='gevent')

当我访问URL http://localhost:8080/stream,打印START,然后是MIDDLE和{}时,它的工作与预期一样。在

根据文件

monkey patching enables gevent to prevent Python’s blocking APIs (and functions like time.sleep()) from blocking the current thread, and passes the CPU to the next greenlet instead.

但是,当我修改上面的代码以打印当前的greenlet信息时,我得到了用于所有三个yield语句的相同greenlet实例。在

^{pr2}$

控制台输出:

<Greenlet at 0x7f9fd733a9c8: _handle_and_close_when_done(<bound method WSGIServer.handle of <WSGIServer at , <bound method StreamServer.do_close of <WSGIServer, (<gevent._socket3.socket object, fd=7, family=2, t)>
<Greenlet at 0x7f9fd733a9c8: _handle_and_close_when_done(<bound method WSGIServer.handle of <WSGIServer at , <bound method StreamServer.do_close of <WSGIServer, (<gevent._socket3.socket object, fd=7, family=2, t)>
<Greenlet at 0x7f9fd733a9c8: _handle_and_close_when_done(<bound method WSGIServer.handle of <WSGIServer at , <bound method StreamServer.do_close of <WSGIServer, (<gevent._socket3.socket object, fd=7, family=2, t)>

根据bottlepy文档,每次时间。睡觉()已执行?

此外,当我运行类似的程序而不使用gevent和monkey patching时,如下所示:

from time import sleep
from bottle import route, run

@route('/stream')
def stream():
    yield 'START \n'
    sleep(3)
    yield 'MIDDLE \n'
    sleep(5)
    yield 'END'

run(host='0.0.0.0', port=8080)

我得到了和以前一样的回答(开始后是中间,结束时间是3秒和5秒),与瓶装医生的评论相反,下面是黑体字:

If you run this script and point your browser to http://localhost:8080/stream, you should see START, MIDDLE, and END show up one by one (rather than waiting 8 seconds to see them all at once).

我是不是少了点什么?在


Tags: andofrunfromimportclosestreamgevent
2条回答

Per the bottlepy docs, shouldn't a new greenlet instance be spawned each time the time.sleep() is executed?

不,恐怕那里的药检有点混乱。在

为每个传入的HTTP请求生成一个新的greenlet。然后生成的greenlet从头到尾处理整个请求。如果这个greenlet产生(显式或隐式),那么另一个greenlet可以自由地做一些工作(大概是处理其他一些HTTP请求)。在

当您调用monkeypatchedtime.sleep时,正在处理HTTP请求的greenlet被挂起,从而产生任何其他活动的greenlet(如果有)。当time.sleep返回时(在指定的秒数之后),将唤醒先前为您的请求提供服务的greenlet,并从sleep调用之后恢复运行。在

希望有帮助!在

2个答案:

  • 在同一个请求中,你将看到同一个请求。尝试同时发送几个请求,以查看更多的greelet的打印输出。在
  • 您的例子适用于我的Macchrome瓶子文档说明您可能需要在某些浏览器上生成更多字节:

    Note: Some browsers buffer a certain amount of data before they start rendering a page. You might need to yield more than a few bytes to see an effect in these browsers. Additionally, many browsers have a limit of one concurrent connection per URL. If this is the case, you can use a second browser or a benchmark tool (e.g. ab or httperf) to measure performance.

相关问题 更多 >