user1601716 user1601716 -4 years ago 86
Python Question

return multiple generators python

This is in reference to flask sub function not yielding results

How can I return multiple generators, like so ...

Currently no matter what I try, it does the first one only, for instance if I do a list of generators and loop through that, it still does the first one.

Any thoughts?

#!/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)

Answer Source

When you use return you exit the function; anything after that line won't be executed.

Instead, you'll have to chain your generators. Use itertools.chain() here:

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download