PyMongo - can't connect to localhost? - python

I have tried running the following:
import pymongo
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client.test_database
collection = db.test_collection
collection.find_one()
but I get
ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused
Any suggestions on how to fix this? I am running this behind a corporate proxy, but have already set environment variables for that in .bashrc.
EDIT
If I run mongo from the terminal, I get
$ mongo
MongoDB shell version v4.0.13
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
2019-10-16T10:30:23.269+0100 E QUERY [js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect#src/mongo/shell/mongo.js:344:17
#(connect):2:6
exception: connect failed

Its look like you didn't run any mongo instance on your machine
run the command mongod -f <config_file> and then test it again (this may needs a sudo permissions)

Related

Mongod.service not found => Pop from an empty deque => Authentication failed

The Problem
I'm getting started with MongoDB on Python, I have a Ubuntu machine in my local network and MongoDB is installed there. When I try to connect with database using Python from Mac it throughs me an error. I searched about it and found out there is a .service called mongod.service that needs to be started along with mongodb.service. But when I try to start the mongod.service the it says the .service doesn't even exist. I tried both with IP and mongodb url, nothing works.
Ubuntu Terminal
$ sudo service mongod start
$ Failed to start mongod.service: Unit mongod.service not found.
$ sudo systemctl start mongod
$ Failed to start mongod.service: Unit mongod.service not found.
DataBase Link (a)
mongodb://user:password#192.168.0.106/database
Python Script (a)
#!/usr/bin/env python3
from pymongo import MongoClient
client = MongoClient('mongodb://user:password#192.168.0.106/database')
db = client['database']
collection = db['collection']
json = dict(message='hello world', token=0)
collection.insert_one(json)
macOS Terminal (a)
pymongo.errors.ServerSelectionTimeoutError: 192.168.0.106:27017: [Errno 61] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 60e140982a43032aef0dd634, topology_type: Single, servers: [<ServerDescription ('192.168.0.106', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('192.168.0.106:27017: [Errno 61] Connection refused')>]>
DataBase Link (b)
mongodb+srv://user:password#cluster0.h9fmz.mongodb.net/database?retryWrites=true&w=majority
Python Script (b)
#!/usr/bin/env python3
from pymongo import MongoClient
client = MongoClient('mongodb+srv://user:password#cluster0.h9fmz.mongodb.net/database?retryWrites=true&w=majority')
db = client['database']
collection = db['collection']
json = dict(message='hello world', token=0)
collection.insert_one(json)
macOS Terminal (b)
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/pymongo/pool.py", line 1278, in _get_socket
sock_info = self.sockets.popleft()
IndexError: pop from an empty deque
During handling of the above exception, another exception occurred:
.....
.....
.....
pymongo.errors.OperationFailure: bad auth : Authentication failed., full error: {'ok': 0, 'errmsg': 'bad auth : Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}
Note That
I'm providing the correct username and password for the database.
I'm using a machine on my local network, which is not a live server.
I've also tried the following commands but they did not solve anything.
Ubuntu Terminal
$ mongod --auth --port 27017
$ mongod --port 27017
$ sudo rm /var/lib/mongodb/mongod.lock
$ sudo mongod --repair
For accessing mongodb from another machine in local network. You will need to check the following:
There is no firewall restriction in the server machine or client machine. In case there is a firewall, you will need to add rule exceptions to allow this port to be accessible. Both incoming and outgoing. (Ubuntu firewall)
You will have to add bindIp config to the mongodb config in server machine. Refer to docs here. You will need to add something like this:
net:
bindIp: 0.0.0.0
port: 27017
Make sure you are able to connect using this ip: 192.168.0.106(server in local network) from the server machine itself. This will make sure the server is listening in this ip.
$ Failed to start mongod.service: Unit mongod.service not found.
The solution for this error could be found here
The mongo atlas error might be due to the following reasons:
You will have to create an database user in order to connect to mongodb.
you can find it under the left panel -> Database access -> Add user
This will be because of a mismatch with username and password. In case you have any special characters in your password you will have to url encode them.

ServerSelectionTimeoutError Pymongo

I'm trying out pymongo for the first time and I keep getting a ServerSelectionTimeoutError. When using mongo commandline to login I run a command as follows
$ mongo-3.0 --ssl test.net:27080/db_qa --sslAllowInvalidCertificates -u content -p
MongoDB shell version: 3.0.12
Enter password:
and I'm able to connect fine but with pymongo I get the error
pymongo.errors.ServerSelectionTimeoutError: test.net:27080: [Errno 60] Operation timed out
My code is as follows
from pymongo import MongoClient
client = MongoClient('mongodb://content:<password>#test.net:27080/db_qa')
client.server_info()
Your connection string is missing the options that your shell command line provides, namely ssl and option to allow invalid certificate.
You could add ?ssl=true&ssl_cert_reqs=CERT_NONE after the database name in the string you are passing to MongoClient or see other options for certificate handling on MongoClient page (scroll to "SSL configuration" section)
So what worked for me was my refreshing my current IP which changed under the "setup connection security" tab

Connecting to PostgreSQL database through Python code

I have a Ubuntu virtual machine using Vagrant, I set it up and run it using vagrant up and vagrant ssh and I create the database psql -d dbname -f somesqlqueries.sql.
Whenever I try to connect to this database through python by doing conn = psycopg2.connect("dbname=dbname") I get this error:
psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061)
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 5432?
Looking at solutions for this issue I changed postgresql.conf to have listen_address = '*' and still the same error occurs.
Also tried to turn off the firewall and run sudo ufw allow 5432/tcp and the error still persistent.

PyMongo MongoClient SSH Connection

I'm trying to establish a connection with a MongoDB database via an SSH connection programmatically from python. I can create a MongoClient object to connect locally but I can't see how to establish an SSH connection for my MongoClient to use.
How would I do this?
First make sure you have no local MongoDB running on your machine, then ssh to the server where MongoDB is running:
ssh -L 27017:MYHOST:27017 MYUSER#MYHOST
Replace MYUSER and MYHOST with your username and host. Then, in another terminal window, run the "mongo" shell from your local computer. By default it connects to localhost:27017, which you've port-forwarded to the remote host. The "mongo" shell should connect correctly.
Then, create a PyMongo connection normally in Python:
>>> from pymongo import MongoClient
>>> c = MongoClient()
>>> c.test.command('buildinfo')
...
More info about SSH tunneling here:
https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding
This is not MongoDB-specific at all, any network protocol can be tunneled with SSH port-forwarding.

How to define same MongoClient for local and docker application?

In order to communicate with MongoDB from Flask, I use the following code to define the connection :
CLIENT = pymongo.MongoClient('mongodb://localhost:27017/')
Everything works fine but once I'm trying to deploy my application on Docker I get the following error:
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused
To solve this problem, I can replace the previous code by:
import os
client = MongoClient(os.environ['DB_PORT_27017_TCP_ADDR'],27017)
But then it only works on Docker and not on my local machine.
How can I define the connection in order to make it work on both Docker and my local machine ?
You can specify that if DB_PORT_27017_TCP_ADDR environment variable is present, use that; else use localhost using something like this:
import os
client = MongoClient(os.environ.get('DB_PORT_27017_TCP_ADDR') or 'localhost', 27017)

Categories