Plays2 Plays2 - 6 months ago 51
Python Question

Flask server with MongoDB (flask-pymongo)

I'm trying to set up a flask server which adds data/users to a mongoDB database.
I set up the DB (using mongo shell) like so:

>use dbname
switched to dbname
> {username:"user", password:"pass"} )
WriteResult({ "nInserted" : 1 })

And confirm the data is written with db.users.find().

I added a mongo user like so:

>use admin
switched to db admin
>var w = { user:"user", roles:["readWriteAnyDatabase"], pwd:"password"}

My looks like:

MONGO_URI = 'mongodb://user:password@localhost:27017/dbname'

and my python looks like this:

from flask import render_template, flash, redirect, Flask
from app import app
from flask_pymongo import PyMongo
from .forms import LoginForm

appp = Flask(__name__)
mongo = PyMongo(appp)

@app.route('/login', methods=['GET', 'POST'])
def login:
form = LoginForm()
if form.validate_on_submit():
user = {"username":,
post_id = mongo.db.users.insert_one(user)
flash('Login req: u=%s, p=%s' % (, str(
return redirect('/index')

I thought all was well but I got this when I tried it out:

enter image description here

It appears to say something about the config_prefix? The docs say config_prefix is set to 'MONGO' by default and in my config the prefix is mongo. I must be missing something SOS


You have a typo in

@app.route('/login', methods=['GET', 'POST'])

PyMongo uses current_app variable from flask which refers to the application instance handling the request. In this case app handles the request but appp has the configuration. So this line should become

@appp.route('/login', methods=['GET', 'POST'])