Python - Cannot connect Python to MongoDB - python

I'm using Python 3.4 the latest version of MongoDB and already installed pymongo using
pip install pymongo
When I run this .py file
from pymongo import MongoClient
if __name__ == "__main__":
con = MongoClient()
db = con.test_database
people = db.people
people.insert({'name':'Mike', 'food':'cheese'})
people.insert({'name':'John', 'food':'ham', 'location':'UK'})
people.insert({'name':'Michelle', 'food':'cheese'})
peeps = people.find()
print("INSERT & FIND TEST")
for person in peeps:
print(person)
I got this error:
Traceback (most recent call last):
File "C:/Users/Alberto/Documents/Python/Kivy/Code/testmongo.py", line 10, in <module>
people.insert({'name':'Mike', 'food':'cheese'})
File "C:\Python34\lib\site-packages\pymongo\collection.py", line 2197, in insert
with self._socket_for_writes() as sock_info:
File "C:\Python34\lib\contextlib.py", line 59, in __enter__
return next(self.gen)
File "C:\Python34\lib\site-packages\pymongo\mongo_client.py", line 712, in _get_socket
server = self._get_topology().select_server(selector)
File "C:\Python34\lib\site-packages\pymongo\topology.py", line 142, in select_server
address))
File "C:\Python34\lib\site-packages\pymongo\topology.py", line 118, in select_servers
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it
Anyone know how to fix this?

if you are using Local Mongodb
myclient = pymongo.MongoClient('mongodb://<yourUsername>:<yourPassword>#<IPAddress>:27017/<yourDB>?retryWrites=true&w=majority')
If you are using Atlas Mongodb
myclient = pymongo.MongoClient('mongodb+srv://<yourUsername>:<yourPassword>#<YourCluster>.mongodb.net/<yourDB>?retryWrites=true&w=majority')

Just try to replace the connection with the following line.
con = MongoClient('localhost', 27017)
It works fine for me.

Related

mysql database problem unable to connect python [duplicate]

This question already has answers here:
Authentication plugin 'caching_sha2_password' is not supported
(28 answers)
Closed 2 years ago.
I'm trying to connect my database to python code but always I got an error
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="*****",
passwd="*******",
)
mycursor = db.cursor()
mycursor.execute("CREATE DATABASE testdatabase")
the error says:
Traceback (most recent call last):
File , line 3, in <module>
db = mysql.connector.connect(
File Programs\Python\Python38-32\lib\site-packages\mysql\connector\__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "Programs\Python\Python38-32\lib\site-packages\mysql\connector\connection.py", line 95, in __init__
self.connect(**kwargs)
File Programs\Python\Python38-32\lib\site-packages\mysql\connector\abstracts.py", line 716, in connect
self._open_connection()
\Programs\Python\Python38-32\lib\site-packages\mysql\connector\connection.py", line 208, in _open_connection
self._do_auth(self._user, self._password,
File "Programs\Python\Python38-32\lib\site-packages\mysql\connector\connection.py", line 137, in _do_auth
packet = self._protocol.make_auth(
File Programs\Python\Python38-32\lib\site-packages\mysql\connector\protocol.py", line 99, in make_auth
packet += self._auth_response(client_flags, username, password,
File Programs\Python\Python38-32\lib\site-packages\mysql\connector\protocol.py", line 58, in _auth_response
auth = get_auth_plugin(auth_plugin)(
File Programs\Python\Python38-32\lib\site-packages\mysql\connector\authentication.py", line 190, in get_auth_plugin
raise errors.NotSupportedError(
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
[Finished in 0.2s]
The answer is instead of installing pip install mysql.connector install mysql.connector-python which is pip install mysql.connector-python

Pymongo Exception handling not working right in python 3

I'm running a script to check if pymongo exceptions are successfully caught, but so far the only errors I get are Pycharm IDE errors. I turned the mongo daemon off to test this out. The relevant portion of the script is as follows, with IDE errors following after it:
import pymongo
from pymongo import MongoClient
from pymongo import errors
import os
from os.path import basename
def make_collection_name(path):
filename = os.path.splitext(basename(path))[0]
collection_name = filename
if collection_name in db.collection_names():
db[collection_name].drop()
return collection_name
if __name__ == '__main__':
try:
client = MongoClient()
except pymongo.errors.ConnectionFailure as e:
print("Could not connect to MongoDB: %s") % e
except pymongo.errors.ServerSelectionTimeoutError as e:
print("Could not connect to MongoDB: %s") % e
filepath = **hidden filepath**
db = client.TESTDB
collection_name = make_collection_name(filepath)
Instead of having the exceptions handled, I rather get the following errors from the IDE:
Traceback (most recent call last):
File "**hidden path**", line 278, in <module>
collection_name = make_collection_name(filepath)
File "**hidden path**", line 192, in make_collection_name
if collection_name in db.collection_names():
File "C:\Python34\lib\site-packages\pymongo\database.py", line 530, in collection_names
ReadPreference.PRIMARY) as (sock_info, slave_okay):
File "C:\Python34\lib\contextlib.py", line 59, in __enter__
return next(self.gen)
File "C:\Python34\lib\site-packages\pymongo\mongo_client.py", line 859, in _socket_for_reads
with self._get_socket(read_preference) as sock_info:
File "C:\Python34\lib\contextlib.py", line 59, in __enter__
return next(self.gen)
File "C:\Python34\lib\site-packages\pymongo\mongo_client.py", line 823, in _get_socket
server = self._get_topology().select_server(selector)
File "C:\Python34\lib\site-packages\pymongo\topology.py", line 214, in select_server
address))
File "C:\Python34\lib\site-packages\pymongo\topology.py", line 189, in select_servers
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it
Process finished with exit code 1
Beginning in PyMongo 3 (not Python 3, PyMongo 3!), the MongoClient constructor no longer blocks trying to connect to the MongoDB server. Instead, the first actual operation you do will wait until the connection completes, and then throw an exception if connection fails.
http://api.mongodb.com/python/current/migrate-to-pymongo3.html#mongoclient-connects-asynchronously
As you can see from your stack trace, the exception is thrown from db.collection_names(), not from MongoClient(). So, wrap your call to make_collection_name in try / except, not the MongoClient call.

Cannot connect to remote MongoDB server using flask-mongoengine

Trying to connect to a MongoDB cluster hosted on a remote server using flask-mongoengine but the following error is thrown:
File "test.py", line 9, in <module>
inserted = Something(some='whatever').save()
File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/mongoengine/document.py", line 323, in save
object_id = collection.save(doc, **write_concern)
File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/collection.py", line 2186, in save
with self._socket_for_writes() as sock_info:
File "/usr/lib/python3.5/contextlib.py", line 59, in __enter__
return next(self.gen)
File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/mongo_client.py", line 762, in _get_socket
server = self._get_topology().select_server(selector)
File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/topology.py", line 210, in select_server
address))
File "/home/lokesh/Desktop/Work/Survaider_Apps/new_survaider/survaider-env/lib/python3.5/site-packages/pymongo/topology.py", line 186, in select_servers
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: admin:27017: [Errno -2] Name or service not known
Below is the code I am using:
# test.py
from my_app_module import app
from flask_mongoengine import MongoEngine
db = MongoEngine(app)
class Something(db.Document):
some = db.StringField()
inserted = Something(some='whatever').save()
print(inserted)
for obj in Something.objects:
print(obj)
My config.py file contains:
# config.py
MONGODB_SETTINGS = {
'db': 'testdb',
'host': 'mongodb://<my_username>:<my_password>#<my_cluster_replica_1>.mongodb.net:27017,<my_cluster_replica_2>.mongodb.net:27017,<my_cluster_replica_3>.mongodb.net:27017/admin?ssl=true&replicaSet=<my_cluster>&authSource=admin',
}
But I can connect using pymongo using the following code.
from pymongo import MongoClient
uri = 'mongodb://<my_username>:<my_password>#<my_cluster_replica_1>.mongodb.net:27017,<my_cluster_replica_2>.mongodb.net:27017,<my_cluster_replica_3>.mongodb.net:27017/admin?ssl=true&replicaSet=<my_cluster>&authSource=admin'
client = MongoClient(uri)
db = client['testdb']
db.test_collection.insert({'some_key': 'some_value'})
for col in db.test_collection.find():
print(col)
# Prints {'some_key': 'some_value', '_id': ObjectId('57ec35d9312f911329e54d5e')}
I tried to find a solution but nobody seems to have come across the problem before. I am using MongoDB's Atlas solution to host the MongoDB cluster.
I figured out that it's a bug in flask-mongoengine version 0.8 and has beed reported here.

pymysql cannot connect with SSL

I am trying to connect to a MySQL database using python but I am getting a strange error. It is compounded by the fact that I can use the same connection values from the mysql console command and it connects with no problems.
Here is the exact code I am using:
import pymysql
from checks import AgentCheck
class DelayedJobCheck(AgentCheck):
def check(self, instance):
self.log.info("testing connection")
self.log.info(instance)
connection = pymysql.connect(**instance)
cur = cnx.cursor(buffered=True)
cur.execute("SHOW STATUS LIKE 'Ssl_cipher'")
print(cur.fetchone())
cur.close()
cnx.close()
self.gauge('hello.world', 1)
This is the error that I am getting:
Traceback (most recent call last):
File "/opt/datadog-agent/agent/checks/__init__.py", line 661, in run
self.check(copy.deepcopy(instance))
File "/opt/datadog-agent/agent/checks.d/delayed_job.py", line 10, in check
connection = pymysql.connect(**instance)
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/__init__.py", line 88, in Connect
return Connection(*args, **kwargs)
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/connections.py", line 644, in __init__
self._connect()
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/connections.py", line 869, in _connect
raise exc
OperationalError: (2003, u"Can't connect to MySQL server on '192.168.199.86' ([SSL: SSL_NEGATIVE_LENGTH] dh key too small (_ssl.c:590))")
I am running this code on a Ubuntu box and I though initially that it might be because the SSL CA is a self generated cert. So I followed the steps here But, it did not make any difference. Also I have verified that the process that is running this code has full access to the cert files
Any ideas what else might be causing this?
As the err info said dh key is too small, a larger one might help. Replace the default dh512.pem file with dh4096.pem
sudo wget "https://git.openssl.org/gitweb/?p=openssl.git;a=blob_plain;f=apps/dh4096.pem" -O dh4096.pem
Ref: http://www.alexrhino.net/jekyll/update/2015/07/14/dh-params-test-fail.html

error when using mysql.connector for python to connect database

I am newbie to python ,started with implementing small programs ,now trying with connecting database .I installed python 3.4 and mysql.connector 2.0.4 .
Below given code is what i used to connnect the database
#!"C:\python34\python.exe"
import sys
import mysql.connector
print("Content-Type: text/html;charset=utf-8")
print()
conn = mysql.connector.connect(host='localhost:8051',
database='test',
user='root',
password='tiger')
if conn.is_connected():
print('Connected to MySQL database')
But i am getting error as given below . not getting why this error are occurring ,because of setup environment is wrong or of some other reason
Please suggest
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\mysql\connector\network.py", line 448, in open_connection
socket.SOL_TCP)
File "C:\Python34\lib\socket.py", line 533, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11004] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#8>", line 2, in <module>
password='tiger',database='test')
File "C:\Python34\lib\site-packages\mysql\connector\__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line 95, in __init__
self.connect(**kwargs)
File "C:\Python34\lib\site-packages\mysql\connector\abstracts.py", line 719, in connect
self._open_connection()
File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line 209, in _open_connection
self._socket.open_connection()
File "C:\Python34\lib\site-packages\mysql\connector\network.py", line 464, in open_connection
errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:8051:3306' (11004 getaddrinfo failed)
The error message is quite clear:
Can't connect to MySQL server on 'localhost:8051:3306'
See the double port definition?
host='localhost:8051'
should most likey be
host='localhost', port='8051'
You are using the connection paramater wrong. I think you need to do this:
conn = mysql.connector.connect(host='localhost',
port=8051,
database='test',
user='root',
password='tiger')
Check out this doc for more detail.
The default Port for MySQL is 3306 , when you don't pass "port" argument to mysql.connector.connect it assumes you are using default port which is 3306 , if you use another port you should pass :
port=xxxx
to the constructor.
For me, I added all connector on my IDE.
mysql-connector
mysql-connector-async-dd
mysql-connector-python
mysql-connector-python-dd
mysql-connector-repackaged
then you can see your all database names here:
import mysql.connector
mydb = mysql.connector.connect(host='localhost',user='root', passwd = 'Root#1234')
mycursor = mydb.cursor()
mycursor.execute("show databases")
for i in mycursor:
print(i)

Categories

Resources