python - flask子函数未产生结果

标签 python flask

我有一堆可以正常工作的代码(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” ”和换行符。”

任何援助将不胜感激。我试图避免完全重写我的所有代码。了解到我将必须在代码中用“ yield”命令替换“ print”。

最佳答案

嵌套的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)

关于python - flask子函数未产生结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25345290/

相关文章:

python - 将字符串返回到 SWIG python 接口(interface)的最佳方法是什么?

python - 如何删除字符串中 x 字符的 1 个实例并在 Python3 中找到它组成的单词?

python - 通过子列表的给定元素从列表中分隔一组子列表

Python Flask 从 root 或静态提供静态文件,如 .htaccess 和 robots?

python - 控制 Flask 应用程序中的 URL 顺序

python - Messenger 机器人每 5 条消息发送一条消息

python - 多索引数据帧行替换

python - 我用的是哪个 python ?

java - Flask future 的可持续性

python - celery 的困难 : function object has no property 'delay'