我有一堆可以正常工作的代码(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/