我在使用 MongoHQ Heroku 插件时遇到问题。我的应用程序在本地工作,并且 os 变量在 Heroku 上存在且格式正确。但是,当我尝试访问数据库时,它会引发错误:OperationFailure: database error: unauthorized db:my_database ns:my_database.cars lock type:0 client:128.62.187.133
. 如果我尝试从 MongoHQ 硬编码连接字符串并在本地运行,我会得到同样的错误。
我的应用程序如下:
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)
...
编辑:MongoHQ 支持帮助了我。问题是我调用的是我的数据库my_database
,而不是 MongoHQ 插件给我的实际数据库名称。例如,db = connection.app52314314
。那个改变解决了它。