Adding Heroku MongoHQ and PyMongo - OperationFailure: Database Error: Unauthorized

I'm having problems with the MongoHQ Heroku addon. Locally, my application works, and the os variable is present and well-formed on Heroku. However, when I try to access db, it throws an error: OperationFailure: database error: unauthorized db:my_database ns:my_database.cars lock type:0 client:128.62.187.133 . If I try to hardcode the connection string from MongoHQ and run locally, I get the same error.

My app is below:

 import os import datetime from flask import Flask from flask import g from flask import jsonify from flask import json from flask import request from flask import url_for from flask import redirect from flask import render_template from flask import make_response import pymongo from pymongo import Connection from bson import BSON from bson import json_util app = Flask(__name__) def mongo_conn(): # Format: MONGOHQ_URL: mongodb://<user>:<pass>@<base_url>:<port>/<url_path> if os.environ.get('MONGOHQ_URL'): return Connection(os.environ['MONGOHQ_URL']) else: return Connection() @app.route('/', methods=['GET', 'POST']) def hello(): # Get your DB connection = mongo_conn() db = connection.my_database # Create an object car = {"brand": "Ford", "model": "Mustang", "date": datetime.datetime.utcnow()} # Get your collection cars = db.cars # crashes # Insert it cars.insert(car) ... 

Edit: MongoHQ support helped me. The problem was that I called my database my_database instead of the actual database name provided to me by the MongoHQ addon. For example, db = connection.app52314314 . This change fixed it.

+6
source share
2 answers

You probably need to run the authenticate command against DB immediately after connecting.

Try something like this:

 db.authenticate([USER], [PASSWORD]) 

If this does not work, feel free to email support@mongohq.com and we can help you with your specific database.

+3
source

You do not need to do all this. You can simply:

 from pymongo import MongoClient client = MongoClient(os.environ['MONGOHQ_URL']) mongo_db = client.get_default_database() 

It will automatically authenticate you and connect to the prepared database, part of the <url_path> your connection URL.

+1
source

Source: https://habr.com/ru/post/928162/


All Articles