Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heroku MongoHQ add-on and PyMongo -- OperationFailure: database error: unauthorized

I'm having trouble with the MongoHQ Heroku addon. Locally my app works and the os variable is present and well-formed on Heroku. However, when I attempt to access the 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 hard-code 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. Problem was that I was calling my database my_database instead of the actual DB name given to me by the MongoHQ addon. E.g., db = connection.app52314314. That change fixed it.

like image 996
Wesley Tansey Avatar asked Oct 20 '12 01:10

Wesley Tansey


2 Answers

You likely need to run the authenticate command against the DB directly after you connect.

Try something like this:

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

If that doesn't work, feel free to email [email protected] and we can help you out with your specific DB.

like image 159
MrKurt Avatar answered Oct 21 '22 04:10

MrKurt


You don't need to do all that. 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 provisioned database, the <url_path> part of your connection url.

like image 40
Dan Gayle Avatar answered Oct 21 '22 05:10

Dan Gayle