FLASK报错,TypeError,需要valid response

今日继续调试abstract的flask框架项目,遇到这样的报错。

TypeError
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

源代码如下:

from app import app
from flask import render_template,request
import sys
sys.path.append('examples')
sys.path.append('src')
import testrun
@app.route('/')
@app.route('/index')
#def index():
#    return render_template('index.html', title='请您输入')
@app.route('/index',methods=['GET','POST'])
def index():
    input_text=''
    output_text=''
    if request.method == 'POST':
        print('post')
        # 接收数据
        input_text=request.form.get('input_text')
        with open('data/test_news.txt', 'w', encoding='utf=8') as f:
            f.writelines(input_text)
        output_text=testrun.test( )
        print(output_text)
        return render_template('index.html',title='文本摘要结果', input_text=input_text,abstract_text=output_text)

  

后来,看到另外一篇文章
Flask 使用过程
被route()装饰器所装饰的functions()必须有返回值
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
'Hello World!' # 没有关键字return

if __name__ == '__main__':
app.run()
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
受到启示,函数必须有返回值!
把return语句的缩进位置调整一下,

def index():
    input_text=''
    output_text=''
    if request.method == 'POST':
        print('post')
        # 接收数据
        input_text=request.form.get('input_text')
        with open('data/test_news.txt', 'w', encoding='utf=8') as f:
            f.writelines(input_text)
        output_text=testrun.test( )
        print(output_text)
    return render_template('index.html',title='文本摘要结果', input_text=input_text,abstract_text=output_text)

  


终于不再报错。特此记录,以供以后参考。

原文地址:https://www.cnblogs.com/z-cm/p/12805475.html