简体   繁体   English

使用Flask-PyMongo插入文档

[英]Insert a document with Flask-PyMongo

I have a MongoDB database and I want to use Flask-PyMongo to work with it in my Flask app. 我有一个MongoDB数据库,我想在Flask应用程序中使用Flask-PyMongo来使用它。 How do I add a database and a collection so I can add user documents? 如何添加数据库和集合,以便可以添加用户文档?

from flask import Flask, render_template, url_for
from flask.ext.pymongo import PyMongo

app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'microblogdb'
app.config['MONGO_URI'] = 'mongodb://briangunsel:password@microblog:27017/microblogdb'
mongo = PyMongo(app, config_prefix='MONGO')


@app.route('/')
def home():
    posts = mongo.db.posts.find({})
    return render_template('users.html', posts=posts)

app.run(debug=True)

Update: With only that code above, when I start up the server (python init .py) and I go to load the web page, it loads for about 10 seconds and then gives me this error https://gist.github.com/anonymous/62ca41e98e67b304838d . 更新:仅使用上面的代码,当我启动服务器(python init .py)并加载网页时,它加载了大约10秒钟,然后出现此错误https://gist.github.com / anonymous / 62ca41e98e67b304838d I am running the database microblogdb in another cmd prompt, and I set the mongo --dbpath to \\data\\, which is a folder I created in the microblog folder. 我在另一个cmd提示符下运行数据库microblogdb ,并将mongo --dbpath设置为\\ data \\,这是我在microblog文件夹中创建的文件夹。 Through the mongo interpreter, I added a posts collection, it is still giving me the same error. 通过mongo解释器,我添加了一个posts集合,它仍然给我同样的错误。

mongo.db.users returns the users collection on the database you configured . mongo.db.users返回您配置的数据库上的users集合。 Flask-PyMongo is using the PyMongo driver, which has extensive documentation. Flask-PyMongo使用的是PyMongo驱动程序,该驱动程序包含大量文档。 PyMongo's tutorial explains how to insert a document. PyMongo的教程介绍了如何插入文档。 You already have code that fetches the users who have online=True . 您已经有了可以获取online=True用户的代码。

app.config['MONGO_URI'] = 'mongodb://username:password@host:port/db_name'
user_id = mongo.db.users.insert_one({'name': 'david'}).inserted_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM