When I am trying to authenticate mongodb by using pymongo, it shows the below error,
command SON([('saslStart', 1), ('mechanism', 'SCRAM-SHA-1'),
('autoAuthorize', 1), ('payload',
Binary('n,,n=user,r=Mzk1NDU4ODUwNzU4', 0))]) on namespace
the_database.$cmd failed: Authentication failed.
My authentication code
client.fw_mongo.authenticate('user', 'password' )
fw_mongo is my mongodb name
What is wrong with this code?
Your code is correct, but your password is not the same as you configured MongoDB with.
try:
from pymongo import MongoClient
Client = MongoClient("mongodb://" + username + ":" + password + "server_details")
def collection_object():
db = Client.db_name
collection = db.collection_name
return collection
Related
I am not able to connect through bottle with my MongoDB. The usual way works fine:
from pymongo import MongoClient
client = MongoClient('....uri_string....')
db = client.myCluster
collection = db.collection
collection.insert_one({'key': 'value'})
But if I try it this way, I am not able to connect.
from bottle import Bottle
from bottle.ext.mongo import MongoPlugin
app = Bottle()
database_name = 'myCluster'
db_uri = '....uri_string....'
db_plugin = MongoPlugin(uri=db_uri, db=database_name)
app.install(db_plugin)
#app.route('/')
def index(mongodb):
mongodb['collection'].insert({'key': 'value'})
mongodb['collection'].insert({'key': 'value2'})
return 'Inserted Data'
app.run(debug=True, reloader=True)
I get the error:
pymongo.errors.OperationFailure: Authentication failed., full error: {'ok': 0, 'errmsg': 'Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}
I am using the free MongoDB Cloud.
I'm trying to connect to a postgres-DB, which unfortunately has a name with a whitespace in it:
%load_ext sql
from sqlalchemy import create_engine
%sql postgresql://postgres:dbpass#localhost/Test DB
(psycopg2.OperationalError) FATAL: database "Test DB" does not exist
I've tried to follow some tipps on the internet and used:
import urllib.parse
urllib.parse.quote_plus("Test DB")
which simply results in a string "Test+DB" (this does not work).
How can I adress the database, without changing its name?
Best regards!
I was able to solve it by using sqlalchemy's create_engine(), therefore being able to simply save the string (with its whitespace) as a variable (eg database_name):
import sqlalchemy as db
database_name = 'Test DB'
engine = db.create_engine('postgresql://' + 'user_name' + ':' + 'password' + '#localhost/' + database_name)
connection = engine.connect()
s = 'SELECT id FROM user'
df = pd.read_sql_query(s, engine)
df.head()
Hope it helps, best regards.
I'm trying to create a connection and add a document with mongoengine through an SSH tunnel.
A successful attempt with pymongo can be seen below, I simply want something similar with mongoengine. :-)
from auth import *
import pymongo
from sshtunnel import SSHTunnelForwarder
server = SSHTunnelForwarder(
(HOST_IP, HOST_PORT),
ssh_username = SSH_USER,
ssh_password = SSH_PASS,
remote_bind_address = ('localhost', 27017)
)
server.start()
client = pymongo.MongoClient('127.0.0.1', server.local_bind_port)
db = client[MONGO_DB]
db.authenticate(MONGO_USER, MONGO_PASS)
coll = db.queue_db
coll.insert({"testFile42":43})
server.stop()
mongoengine.connect(
db=DB_NAME,
host="127.0.0.1",
port=server.local_bind_port
)
Question: How to provide pemfile password in pymongo mongoclient in the connection string?
import pymongo
from pymongo import MongoClient
sslCAFile = data['COMMON_SETTINGS']['sslCAFile'] //reading cafile path from configurationfile
sslpemkeyfile = data['COMMON_SETTINGS']['sslpemkeyfile'] //reading pemfile path from configurationfile(which is encrypted with password)
// now i need to connect by giving the password . but i dont see any parameter for that in pymongo documentation and in authentication examples
connection =
MongoClient(mongos_ip,int(mongos_port),ssl=True,ssl_certfile=sslpemkeyfile,ssl_ca_certs=sslCAFile)
//Help me on this!!!
Unfortunately the current version of pymongo doesn't support this feature
ref: https://jira.mongodb.org/browse/PYTHON-640
What about this:
import ssl
connection = MongoClient(mongos_ip, int(mongos_port),
ssl=True,
ssl_certfile=sslpemkeyfile,
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs=sslCAFile)
It is from here: http://api.mongodb.org/python/current/examples/authentication.html
I have a small flask application which I am deploying to Heroku.
My local configuration looks like this:
from flask import Flask
from flask.ext.mongoengine import MongoEngine
app = Flask(__name__)
app.debug = True
app.config["MONGODB_SETTINGS"] = {'DB': "my_app"}
app.config["SECRET_KEY"] = "secretpassword"
db = MongoEngine(app)
So, I know that I need to configure the app to use the Mongo URI method of connection, and I have my connection info:
mongodb://<user>:<password>#alex.mongohq.com:10043/app12345678
I am just a little stuck as to the syntax for modifying my app to connect through the URI.
So I got it working (finally):
from flask import Flask
from mongoengine import connect
app = Flask(__name__)
app.config["MONGODB_DB"] = 'app12345678'
connect(
'app12345678',
username='heroku',
password='a614e68b445d0d9d1c375740781073b4',
host='mongodb://<user>:<password>#alex.mongohq.com:10043/app12345678',
port=10043
)
Though I anticipate that various other configurations will work.
When you look at the flask-mongoengine code, you can see what configuration variables are available
So this should work:
app.config["MONGODB_HOST"] = 'alex.mongohq.com/app12345678'
app.config["MONGODB_PORT"] = 10043
app.config["MONGODB_DATABASE"] = 'dbname'
app.config["MONGODB_USERNAME"] = 'user'
app.config["MONGODB_PASSWORD"] = 'password'
db = MongoEngine(app)
I'm not sure, if app123 is the app or the database name. You might have to fiddle arround a little to get the connection. I had the same problem with Mongokit + MongoLab on Heroku :)
Also you could use the URI like this.
app.config["MONGODB_SETTINGS"] = {'DB': "my_app", "host":'mongodb://<user>:<password>#alex.mongohq.com:10043/app12345678'}
I have actually no idea, at what point "MONGODB_SETTINGS" is read, but it seemed to work, when I tried it in the shell.
I figured out how to use the flask.ext.mongoengine.MongoEngine wrapper class to do this rather than mongoengine.connect():
from flask import Flask
from flask.ext.mongoengine import MongoEngine
app = Flask(__name__)
HOST = '<hostname>' # ex: 'oceanic.mongohq.com'
db_settings = {
'MONGODB_DB': '<database>',
'MONGODB_USERNAME': '<username>',
'MONGODB_PASSWORD': '<password>',
'MONGODB_PORT': <port>,
}
app.config = dict(list(app.config.items()) + list(db_settings.items()))
app.config["MONGODB_HOST"] = ('mongodb://%(MONGODB_USERNAME)s:%(MONGODB_PASSWORD)s#'+
HOST +':%(MONGODB_PORT)s/%(MONGODB_DB)s') % db_settings
db = MongoEngine(app)
if __name__ == '__main__':
app.run()
If you're using mongohq, app.config["MONGODB_HOST"] should match the Mongo URI under Databases->Admin->Overview.
You can then follow MongoDB's tumblelog tutorial using this setup to write your first app called tumblelog.
Using python's nifty object introspection (python oh how I love you so), you can see how the MongoEngine wrapper class accomplishes this:
from flask.ext.mongoengine import MongoEngine
import inspect
print(inspect.getsource(MongoEngine))
...
conn_settings = {
'db': app.config.get('MONGODB_DB', None),
'username': app.config.get('MONGODB_USERNAME', None),
'password': app.config.get('MONGODB_PASSWORD', None),
'host': app.config.get('MONGODB_HOST', None),
'port': int(app.config.get('MONGODB_PORT', 0)) or None
}
...
self.connection = mongoengine.connect(**conn_settings)
...
self.app = app