python后端明明if和else中都有return,可还是报错The view function did not return a valid response

python后端明明if和else中都有return,可还是报错The view function did not return a valid response
python代码:

from flask import *

app = Flask(__name__)

def space (name):
    route = "./data/" + name + "_good.txt"
    display = name + ".html"
    write_data = open(route, "r+")
    good_data = int(write_data.read())
    if request.method == 'POST':
        good_data += 1
        write_data.seek(0)
        write_data.truncate()
        write_data.write(str(good_data))
        return render_template(display, good=good_data)
    else:
        return render_template(display, good=good_data)

@app.route('/cs.html', methods=["GET","POST"])
def space_cs ():
    space(name='cs')

if __name__ == "__main__":
    app.config["JSON_AS_ASCII"] = False
    app.run(host="0.0.0.0", port=610, debug=True, threaded=True, processes=1)

python报错:

Traceback (most recent call last):
  File "C:\Program Files\Python37\lib\site-packages\flask\app.py", line 2548, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Program Files\Python37\lib\site-packages\flask\app.py", line 2528, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Program Files\Python37\lib\site-packages\flask\app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Program Files\Python37\lib\site-packages\flask\app.py", line 1823, in full_dispatch_request
    return self.finalize_request(rv)
  File "C:\Program Files\Python37\lib\site-packages\flask\app.py", line 1842, in finalize_request
    response = self.make_response(rv)
  File "C:\Program Files\Python37\lib\site-packages\flask\app.py", line 2135, in make_response
    f"The view function for {request.endpoint!r} did not"
TypeError: The view function for 'space_cs' did not return a valid response. The function either returned None or ended without a return statement.

请问这样怎么改啊

基于Monster 组和GPT的调写:
space_cs 函数中返回 space 函数的返回值。用 return 关键字来完成:

@app.route('/cs.html', methods=["GET","POST"])
def space_cs ():
    return space(name='cs')


你的函数space有返回值,但space_cs 没有,return出去就可以了


def space_cs ():
    return space(name='cs')
  • 这篇博客: 基于Python电影网站系统的日志中的 2. ValueError: View function did not return a response 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 添加关键字return,视图无返回值