【问题标题】:Yield an item with Python Bottle doesn't work使用 Python Bottle 生成物品不起作用
【发布时间】:2018-10-30 13:35:41
【问题描述】:

使用时:

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 应该在第二个请求时打印,等等。

【问题讨论】:

    标签: python iterator generator python-2.x yield


    【解决方案1】:

    这与 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()
    

    【讨论】:

      【解决方案2】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 2016-09-23
        • 1970-01-01
        • 2018-08-18
        • 2020-05-21
        • 1970-01-01
        • 2012-01-20
        • 2019-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多