0

I just encountered a problem while playing with Flask and MongoDB. Here are scenarios

With Authorization Enabled

If I use PyMongo() from flask_pymongo with mongo = PyMongo(app) pattern, I just get Authorization Errors. While I am able to successfully retrieve database via MonogoClient() from pymongo using same connection string.

Without Authorization Enabled

If I use flask_pymongo, no errors. But I am not getting any data either. For example, mongo.db.collection_names() just returns empty array. With MongoClient(), the same operation was successful.

I am using:

  • python = 3.6.3
  • flask = 0.12.2
  • flask_pymongo = 0.5.1
  • pymongo = 3.5.1

Thanks in Advance

ShivaGaire
  • 2,283
  • 1
  • 20
  • 31
Nafees Anwar
  • 6,324
  • 2
  • 23
  • 42
  • Here is the simple example of MongoDB with Flask https://stackoverflow.com/a/53998723/10849262 – v.k Jan 02 '19 at 00:28
  • Here is the simple example of MongoDB with Flask https://stackoverflow.com/a/53998723/10849262 – v.k Jan 02 '19 at 00:29

1 Answers1

0

I've been using Flask with Flask-PyMongo for a while now, and below is how I make my connections to a mongodb.

from flask import Flask
from flask_cors import CORS
from flask_pymongo import PyMongo

app = Flask(__name__)
CORS(app) # very important!

USERNAME = '<username>'
PASSWORD = '<password>'
PORT = '27017'
HOST = 'localhost'

app.config['MONGO_DBNAME'] = '<DB Name>'
app.config['MONGO_HOST'] = HOST
app.config['MONGO_PORT'] = PORT
app.config['MONGO_USERNAME'] = USERNAME
app.config['MONGO_PASSWORD'] = PASSWORD
mongo = PyMongo(app)

You may not need the CORS(app) depending on your setup.

To create multiple connections do the following:

# Users db
app.config['MONGO2_DBNAME'] = 'users'
app.config['MONGO2_HOST'] = HOST
app.config['MONGO2_PORT'] = PORT
app.config['MONGO2_USERNAME'] = USERNAME
app.config['MONGO2_PASSWORD'] = PASSWORD
users_mongo = PyMongo(app, config_prefix='MONGO2')

I should also note that I had problems connecting with authorization through Flask-PyMongo because the database needed to have authorization configured a certain way. Flask-PyMongo expects the db authority to be on the database itself and not elsewhere. So when creating a user and password for a db do the following inside a mongo shell:

Create user admin

use admin
db.createUser({user: "userAdmin", pwd: "", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )

Create user on YOUR db

use <YOUR db>
db.createUser({user: "", pwd: "", roles:[{ role: "dbAdmin", db: ""}, {role: "readWrite", db: ""}]})

Within mongo and even with PyMongo you can create users within one database and give them access to other dbs, but Flask-PyMongo for whatever reason does not play nice here and you'll need the user created within the database you want to use.

Hope this helps as I've struggled here as well. Feel free to ask for clarification

Sylv
  • 41
  • 1
  • 8