返回多个生成器python

时间:2014-08-17 02:12:31

标签: python flask generator

这是参考flask sub function not yielding results

如何返回多个生成器,如此...

目前无论我尝试什么,它只做第一个,例如,如果我做一个生成器列表并循环通过它,它仍然是第一个。

有什么想法吗?

#!/usr/bin/env python

import flask
import time

class TestClass(object):

    def __init__(self):
        pass

    def worker(self):
        a='1234'
        b=a + '45\n'
        yield b
        time.sleep(3)
        yield a

    def worker2(self):
        time.sleep(3)
        c = '9876'
        yield c

tc = TestClass()
app = flask.Flask(__name__)


@app.route('/')
def test_method_get_stuff():
    return flask.render_template('index.html')

@app.route('/', methods=['POST'])
def test_method_post_stuff():
    def test_method_sub_function():
        return tc.worker()
        return tc.worker2()
    return flask.Response(test_method_sub_function(),mimetype= 'text/plain')

app.run(debug=True)

1 个答案:

答案 0 :(得分:2)

当您使用return时,退出该功能;在该行之后的任何事情都不会被执行。

相反,您必须链接您的生成器。在这里使用itertools.chain()

from itertools import chain

@app.route('/', methods=['POST'])
def test_method_post_stuff():
    def test_method_sub_function():
        return chain(tc.worker(), tc.worker2())
    return flask.Response(test_method_sub_function(),mimetype= 'text/plain')