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)
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.
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.
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.
When you return something from a Flask handler it must be one of the following types of things:
flask.Response object (or a werkzeug.wrappers.Response object). Using Flask's render_template will return a response object.(content, status_code, headers)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With