python - 运行python webapp时出现TypeError,python代码中的什么异常可能导致它?
问题描述
我使用 python flask 和 PostgreSQL 作为后端为 Web 应用程序编写了框架。它应该允许提交要保存的文本。但是当我尝试运行它时,我得到以下类型错误:
TypeError:视图函数没有返回有效响应。该函数要么返回 None ,要么在没有 return 语句的情况下结束。
回溯到错误页面:
Traceback (most recent call last) File
"/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 2464,
in call return self.wsgi_app(environ, start_response) File
"/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 2450,
in wsgi_app response = self.handle_exception(e) File
"/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1867,
in handle_exception reraise(exc_type, exc_value, tb) File
"/opt/anaconda3/lib/python3.8/site-packages/flask/_compat.py", line
39, in reraise raise value File
"/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 2447,
in wsgi_app response = self.full_dispatch_request() File
"/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1953,
in full_dispatch_request return self.finalize_request(rv) File
"/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1968,
in finalize_request response = self.make_response(rv) File
"/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 2097,
in make_response raise TypeError( TypeError: The view function did not
return a valid response. The function either returned None or ended
without a return statement. The debugger caught an exception in your
WSGI application. You can now look at the traceback which led to the
error. To switch between the interactive traceback and the plaintext
one, you can click on the "Traceback" headline. From the text
traceback you can also create a paste of it. For code execution
mouse-over the frame you want to debug and click on the console icon
on the right side.
You can execute arbitrary Python code in the stack frames and there
are some extra helpers available for introspection:
dump() shows all variables in the frame dump(obj) dumps all that's
known about the object Brought to you by DON'T PANIC, your friendly
Werkzeug powered traceback interpreter.
我的代码如下,找了半天也没发现什么问题:
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
ENV = 'dev'
if ENV == 'dev':
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Gray@localhost/Phict'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Feedback(db.Model):
__tablename__ = 'feedback'
id = db.Column(db.Integer, primary_key=True)
comments = db.Column(db.Text())
def __init__(self, comments):
self.comments = comments
@app.route('/')
def index():
return render_template('index.html')
@app.route('/submit', methods=['POST'])
def submit():
if request.method == 'POST':
comments = request.form['fileToUpload']
data = Feedback(comments)
db.session.add(data)
db.session.commit()
if __name__ == '__main__':
app.run()
解决方案
正如@snakecharmerb在他上面的评论中所说
提交函数不返回任何内容。它必须返回一些东西,即使它只是一个空字符串。
因此,在您的情况下,您可能需要将重定向对象返回到主页,例如
@app.route('/submit', methods=['POST'])
def submit():
if request.method == 'POST':
comments = request.form['fileToUpload']
data = Feedback(comments)
db.session.add(data)
db.session.commit()
# you can add a 'flash' message and then redirect to the index page
return redirect(url_for('index')) # -- HERE --
参考这个话题https://flask.palletsprojects.com/en/1.1.x/api/#flask.redirect
推荐阅读
- html - 更改浏览器大小时图像位于文本之上
- github - 使用 azure rest api 创建 GitHub 服务连接给出错误
- python - 循环Python的这种语法是什么
- flutter - FutureBuilder 中的构建器在 Flutter 中不起作用
- java - 使用自己的方法结果再次调用 Spring Controller 方法
- php - 我怎样才能在另一个中嵌入一个 echo statmtement?
- php - 从 API 函数返回数组或嵌套数组
- javascript - 如果等于变量,则删除节点子级
- php - 如何将多张图片添加到数据库中
- python - 从 tkinter 中的条目计算平均值时如何避免除以零错误