使用 Python 生成物品 瓶子不起作用
Yield an item with Python Bottle doesn't work
使用时:
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
在这个BottlePython上下文中正常工作?
我期望的是: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)
这与 Bottle 没有任何关系,它仅与生成器函数有关。
当您调用 yielditem()
时,您会得到一个 生成器对象 yielditem
,正如 Python 告诉您的那样。它不会神奇地开始迭代它。
如果你确实想遍历生成器对象,你必须明确地这样做,像 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()
使用时:
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
始终保持为 0print yielditem()
给出<generator object yielditem at 0x0000000002D40EE8>
如何让这个yield
在这个BottlePython上下文中正常工作?
我期望的是: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)
这与 Bottle 没有任何关系,它仅与生成器函数有关。
当您调用 yielditem()
时,您会得到一个 生成器对象 yielditem
,正如 Python 告诉您的那样。它不会神奇地开始迭代它。
如果你确实想遍历生成器对象,你必须明确地这样做,像 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()