使用时:
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上下文中正常工作?
我的期望是:0
应该在第一次请求时打印,1
应该在第二次请求时打印,等等。
答案 0 :(得分:3)
这没有任何与Bottle有关,它只是关于生成器功能。
当你致电yielditem()
时,你会得到一个生成器对象 yielditem
。它并没有神奇地开始迭代它。
如果您想迭代生成器对象,则必须使用print(next(yielditem()))
等显式执行此操作。
你想如何使用那个生成器是另一个故事:如果你想在多个函数调用期间访问同一个生成器对象,你可以把它放在名为的函数之外:
generator_object = yielditem()
def print_it(): # this is like your `index` function
print "Current value: {}".format(next(generator_object))
for x in range(10): # this is like a client reloading the page
print_it()
答案 1 :(得分: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)