Pimongo with a flask

I try to get my messages back, but instead I get

TypeError: Cursor cannot be called.

How can i fix this? Here is my code:

from flask import Flask from flask.ext.pymongo import PyMongo app = Flask(__name__) mongo = PyMongo(app) from pymongo import Connection connection = Connection() db = connection.test_database collection = db.test_collection @app.route('/') def home_page(): post = {"author":"mike","text":"jiii"} posts = db.posts posts.insert(post) return posts.find() if __name__=='__main__': app.run(debug=True) 
+7
source share
4 answers

find () returns a Cursor object that you must iterate over to access the documents returned by the query. How in:

 for post in posts.find(): # do something with post 
+10
source

When you return something from a Flask handler, it must be one of the following types:

When you return the PyMongo Cursor object, Flask sees that it is not an instance of flask.Response (actually, flask.Flask.response_class ), but not a tuple, so it assumes that it must be a WSGI object and tries to call it (hence the error).

The best solution is to either use flask.jsonfiy to return a JSON response, or create a template to display messages and use render_template to return the corresponding response.

+6
source

The answers given above are correct. Flag views are expected to return some kind of HTTP response. Therefore, you need to process the data and make an answer, perhaps using the functions of the Flasks utility. In addition, the find() method returns a cursor that you need to iterate over at some point.

You just need to change the last line of the form:

 @app.route('/') def home_page(): post = {"author":"mike","text":"jiii"} posts = db.posts posts.insert(post) return render_template(posts.find(), "index.html") 

And specify index.html , which contains something like:

 {% for post in posts %} <h2>Post by {{ post.author}}</h2> <p>{{ post.text }}</p> {% endfor %} 
0
source

Using:

 from flask_pymongo import Pymongo 

instead:

 from flask.ext.pymongo import PyMongo 
0
source

All Articles