使用时:

from bottle import route, run, request, view

N = 0

def yielditem():
    global N
    for i in range(100):
        N = i
        yield i

@route('/')
@view('index.html')
def index():
    print yielditem()
    print N

run(host='localhost', port=80, debug=False)


页面index.html成功显示,但是yield部分不起作用:


对于每个新请求,N始终保持为0
print yielditem()给出<generator object yielditem at 0x0000000002D40EE8>


如何使此yield在此Bottle Python上下文中正常工作?

我期望的是:应在第一个请求上打印0,应在第二个请求上打印1,依此类推。

最佳答案

看起来您正在打印生成器本身而不是其值:

from bottle import route, run, request, view

N = 0
def yielditem():
    global N
    for i in range(100):
        N = i
        yield i

yf = yielditem()

@route('/')
@view('index.html')
def index():
    print next(yf)
    print N

run(host='localhost', port=80, debug=False)

07-24 09:30