Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo with flask

Tags:

flask

pymongo

I am trying to return my posts, but instead I get

TypeError: 'Cursor' object is not callable.

How can I correct 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)
like image 481
vishnusathyanesan Avatar asked Apr 26 '12 19:04

vishnusathyanesan


People also ask

Can we use MongoDB with Flask?

Here we are introducing the Flask extension of the MongoDB: MongoEngine . You can use MongoEngine independently without relying on the Flask, but you can use it in combination with Flask. After you configure the mongodb information, you can create a data model using MongoEngine.

Which is better PyMongo or MongoEngine?

Both PyMongo and MongoEngine can be used to access data from a MongoDB database. However, they work in very different ways and offer different features. PyMongo is the MongoDB recommended library. It makes it easy to use MongoDB documents and maps directly to the familiar MongoDB Query Language.

Does Flask support NoSQL database?

Connecting Flask with SQL databases like PostgreSQL and SQLite is a cinch. But the framework syncs perfectly with NoSQL databases like CouchDB, too. And as an added benefit, you can query your data easily when you use CouchDB with Flask.


1 Answers

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

  • A flask.Response object (or a werkzeug.wrappers.Response object). Using Flask's render_template will return a response object.
  • A tuple in the form (content, status_code, headers)
  • A WSGI callable (A function or callable object that takes two params and returns an iterable).

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

The best solution is to either use flask.jsonfiy to return a JSON response or to create a template to render the posts and use render_template to return the appropriate response.

like image 100
Sean Vieira Avatar answered Feb 05 '23 13:02

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!