Flask子函数未返回结果

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

我有一段代码(1300行),它运行得很好,现在我想把flask引入进来。为此,我想用flask.Response来调用我方法中的一个函数,这个函数又会调用我类中的另一个方法。

这里有一段测试代码,能重现我遇到的问题。

#!/usr/bin/env python

import flask

class TestClass(object):

    app = flask.Flask(__name__)
    def __init__(self):
        pass

    def worker(self):
        yield 'print test\n'

    @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():
            tc.worker()
        return flask.Response(test_method_sub_function(),mimetype= 'text/plain')


tc = TestClass()
tc.app.run(debug=True)

index.html 里只有一个文本框和一个提交按钮。

我遇到的问题是,一旦点击提交按钮,请求成功发送了,但页面却是空白的,Python命令行和浏览器里都没有错误信息。我期待的结果是能在页面上显示“print test”这段文字,并换行。

如果有人能帮忙,我会非常感激。我希望能避免完全重写我的代码。明白我需要把代码中的'print'替换成'yield'命令。

1 个回答

0

你里面的 test_method_sub_function() 函数没有返回任何东西;它只是创建了一个生成器(通过调用一个生成器函数),然后就结束了。

至少应该 返回 tc.worker() 的调用:

def test_method_sub_function():
    return tc.worker()

这样的话,路由就能正常工作了。不过你也可以直接使用 tc.worker(),不必使用这个嵌套函数:

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

有一点要注意:虽然你把 Flask 对象当作类的属性使用是可以的,但最好还是把它放在一个类里面。把 app 对象和路由放在类外面:

import flask

class TestClass(object):    
    def worker(self):
        yield 'print test\n'

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():
    return flask.Response(tc.worker(), mimetype='text/plain')

app.run(debug=True)

撰写回答