使用 Flask 将表单数据发送到 MongoDB

Send form data to MongoDB using Flask

我在使用 Flask 设置将 form 数据发送到 MongoDB 时遇到问题。表格看起来像这样:https://jsfiddle.net/8gqLtv7e

在客户端,我没有看到任何错误。但是当我提交表单时,我收到了 500 Internal Server Error 并且我很难找到解决方案。问题是我的 views.py 文件下面的最后一行:

@app.route('/recordReport', methods=['POST'])
def recordReport():
    homeReportsCollection = db["reports"]
    address=request.form.get['address']
    rgbImage=request.form.get['rgb']
    homeReportsCollection.insert({'address':address, 'rgb':rgbImage})

因为如果我将其替换为 return json.dumps({'status':'OK', 'address':'address', 'rgb':'rgbImage'}),我可以在浏览器中看到正确的数据。我只是无法将它发送到 MongoDB.

中的集合

此答案是评论的摘要(找到解决方案的地方)。


Have you tried typecasting address and rgbImage to String before inserting?

类型失效是数据库操作中许多常见错误的根源。

There used to be a bug in Mongo back in 2013. The data would be inserted into the collection. But Mongo would not return a correct status response. That led to servers going 500. Have you tried verifying if the data was indeed inserted into the collection?

Additionally run your flask app in debug=True mode. That might give additional data.

Flask 具有非常好的调试回溯报告支持。这通常是个好主意。事实上,这应该是遇到错误时要做的第一件事。

So this is weird, I turned on debug=True and I get the following error: ValueError: View function did not return a response. BUT the data did actually get sent to DB via homeReportsCollection.insert({'address':address, 'rgb':rgbImage}) line. I see it in my collection. How do I fix the error? Because the user is redirected to /recordReport.

所以数据确实被插入到集合中。这可能是 Flask 唯一的问题。追溯说明了一切。 Flask 要求视图方法返回一些内容。

Try returning something in your function recordReport(). Return anything you want. It could be an OK message. It could be the _id of the document you just inserted into the collection. Just don't return None. Try this.

此行为记录在 SO question

Yeah, I returned an HTML template and no error now.

这确实是解决方案。 Return 来自您的 视图方法的 None 以外的东西。这也验证了提问者在问题中观察到的行为:

Because if I replace that with return json.dumps({'status':'OK', 'address':'address', 'rgb':'rgbImage'}), I can see the correct data in my browser.