Search code examples
pythoniteratorgeneratorpython-2.xyield

Yield an item with Python Bottle doesn't work


When using:

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)

the page index.html is successfully displayed, but the yield part is not working:

  • N stays always at 0, for every new request

  • print yielditem() gives <generator object yielditem at 0x0000000002D40EE8>

How to make this yield work normally in this Bottle Python context?

What I expect is: 0 should be printed at the first request, 1 should be printed at the second request, etc.


Solution

  • It looks you are printing the generator itself not its values:

    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)