返回多个生成器 Python

0 投票
1 回答
1898 浏览
提问于 2025-04-18 17:32

这是关于flask子函数没有返回结果的内容。

我想知道如何返回多个生成器,比如这样……

目前无论我尝试什么,它只会执行第一个生成器。例如,如果我创建一个生成器的列表并循环遍历它,结果还是只执行第一个。

有什么想法吗?

#!/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 个回答

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')

撰写回答