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.
Related
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
)
i've made a local server using flask and mongoDB which works great on windows, but when i moved my code to the raspberry pi, i've got an error which i couldn't figure out why it occurs.
the code im using:
1) for the flask server
from flask import Flask
from flask import jsonify
from flask import request
import pymongo
import time
import datetime
import json
app = Flask(__name__)
client = pymongo.MongoClient("localhost", 27017)
db = client['mqtt-db']
obs_collection = db['mqtt-collection']
#app.route("/obs")
def obs():
data_str = request.args.get("data")
print data_str
data = json.loads(data_str)
print data
data["date"] = datetime.datetime.now()
obs_collection.save(data)
return "success"
#app.route("/get_obs")
def get_obs():
res = []
for row in obs_collection.find():
del row['_id']
res.append(row)
return jsonify(res)
#app.route("/delete_all")
def delete_all():
res = obs_collection.delete_many({})
return jsonify({"deleted": res.deleted_count})
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
2) script for inserting messages into db , using mqtt protocol:
import paho.mqtt.client as mqtt
import pymongo
import json
import datetime
topic = "sensor"
host = "10.0.0.6"
client = pymongo.MongoClient("localhost", 27017)
db = client['mqtt-db']
mqtt_collection = db['mqtt-collection']
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(topic)
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
data_str = str(msg.payload)
data = json.loads(data_str)
print data_str
print data
data["date"] = datetime.datetime.now()
mqtt_collection.save(data)
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(host, 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
the error occurs when i try to retrieve data from the server using "get_obs" function.
the error is: "Value Error: dictionary update sequence element #0 has length 4; 2 is required"
appreciate your help.
as #davidism suggested, the solution was to update to the latest version of Flask
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
I'm trying to use MongoDB on Amazon EC2 using Python3.4.3.
I followed this answer: modified security groups setting and edited "/etc/mongod.conf" (comment out bind_id). However, when I run following code, I got this error:
ServerSelectionTimeoutError: SSL handshake failed: [Errno 54] Connection reset by peer
What else should I do?
The code I run is:
import pymongo
import ssl
client = pymongo.MongoClient('ec2-**-**-*-**.us-west-2.compute.amazonaws.com', 27017,
ssl=True, ssl_keyfile='/Users/S/FILENAME.pem')
db = client["test"]
db.artist
collection = db.artist
import gzip
import json
from io import StringIO
with gzip.open('artist.json.gz', "rt") as a_file:
count=0
bulk = []
for line in a_file:
jdata = json.load(StringIO(line))
bulk.append(jdata)
count += 1
if 1000 < count:
print ('bulk insert!')
collection.insert_many(bulk)
bulk = []
count = 0
if len(bulk) > 0:
collection.insert_many(bulk)
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