在 mlab 中连接到 mongodb 时验证失败

authendication failed when connecting to mongodb in mlab

我正在尝试使用 Flask 连接到 mlab.com 中的 mongodb,但是当我 运行 我的 Flask 脚本出现身份验证失败错误时,请帮忙。

我的代码:

from flask import Flask, jsonify, request
from flask_pymongo import PyMongo

app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'mydb'
app.config['MONGO_URI'] = 'mongodb://user:pwd@ds157799.mlab.com:57799/mydb'


mongo = PyMongo(app)

@app.route('/framework', methods=['GET'])
def get_all_frameworks():
    framework = mongo.db.framework 

    output = []

    for q in framework.find():
        output.append({'name' : q['name'], 'language' : q['language']})

    return jsonify({'result' : output})

错误:

  File "mongo.py", line 12, in <module>
    mongo = PyMongo(app)
  File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\flask_pymongo\__init__.py", line 97, in __init__
    self.init_app(app, config_prefix)
  File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\flask_pymongo\__init__.py", line 283, in init_app
    mechanism=auth_mechanism)
  File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\database.py", line 1167, in authenticate
    connect=True)
  File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\mongo_client.py", line 588, in _cache_credentials
    sock_info.authenticate(credentials)
  File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\pool.py", line 620, in authenticate
    auth.authenticate(credentials, self)
  File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\auth.py", line 486, in authenticate
    auth_func(credentials, sock_info)
  File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\auth.py", line 237, in _authenticate_scram_sha1
    res = sock_info.command(source, cmd)
  File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\pool.py", line 517, in command
    collation=collation)
  File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\network.py", line 125, in command
    parse_write_concern_error=parse_write_concern_error)
  File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\helpers.py", line 145, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: Authentication failed.

请帮忙解决这个问题。

您可以使用它作为登录数据库的替代方法。这已经过测试并且有效:

connection = pymongo.MongoClient(HOST, PORT)
db = connection[databasename]
db.authenticate(database_user, database_pass)

我为我的数据库创建了一个带密码的新用户,并且工作正常。

https://www.reddit.com/r/flask/comments/5ftqvm/how_to_use_pymongo_with_hosted_mongodb_mlab/

这很好用。对我来说,通过来自 mLab 数据库的 URI 字符串连接也不起作用。