Issue
I tried to connect MongoDB using pymongo. However, I met the error of dnspython must be installed even after I installed pymongo and dnspython.
My code is:
import pymongo
USER = ''
PASSWORD = ''
client = pymongo.MongoClient(
"mongodb+srv://" + USER + ":" + PASSWORD + "@tbn-ph9ol.mongodb.net/test?retryWrites=true&w=majority")
db = client["tbn"]
collection = db["inputs"]
post = {"_id": 0,
"temperature": 37,
}
collection.insert_one(post)
Why can not the mongodb recognize that I have installed the pymongo and dnspython?
Solution
Your issue is that you do not have dnspython
installed in the environment that you are running in. If you did have dnspython installed, you will not get this error message.
This is easily proven using a scratch environment in docker; start a docker container with:
docker run --rm -it python:3.8.1-buster /bin/bash
Then at the shell run the following commands to create and run your program in a new venv with only pymongo installed:
cd "$(mktemp -d)"
python -m venv venv
. venv/bin/activate
pip install --upgrade pip
pip install pymongo
cat << EOF > test.py
import pymongo
USER = 'x'
PASSWORD = 'y'
client = pymongo.MongoClient(
"mongodb+srv://" + USER + ":" + PASSWORD + "@tbn-ph9ol.mongodb.net/test?retryWrites=true&w=majority")
db = client["tbn"]
collection = db["inputs"]
post = {"_id": 0,
"temperature": 37,
}
collection.insert_one(post)
EOF
pip freeze && python test.py
You should see the following output:
pymongo==3.10.1
Traceback (most recent call last):
File "test.py", line 5, in <module>
client = pymongo.MongoClient(
File "/tmp/tmp.vdpqnMOnFO/venv/lib/python3.8/site-packages/pymongo/mongo_client.py", line 619, in __init__
res = uri_parser.parse_uri(
File "/tmp/tmp.vdpqnMOnFO/venv/lib/python3.8/site-packages/pymongo/uri_parser.py", line 390, in parse_uri
raise ConfigurationError('The "dnspython" module must be '
pymongo.errors.ConfigurationError: The "dnspython" module must be installed to use mongodb+srv:// URIs
You will observe the error you are getting. Now add dnspython and run again:
pip install dnspython
pip freeze && python test.py
You will now see an authentication failed message as expacted as we don't have the right username and password. You can see from the pip freeze
command that dnspython is installed this time.
dnspython==1.16.0
pymongo==3.10.1
Traceback (most recent call last):
File "test.py", line 16, in <module>
collection.insert_one(post)
File "/tmp/tmp.vdpqnMOnFO/venv/lib/python3.8/site-packages/pymongo/collection.py", line 695, in insert_one
...
... <snip>
...
pymongo.errors.OperationFailure: Authentication failed.
Answered By - Belly Buster
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.