gpt4 book ai didi

python - pymongo.errors.ConfigurationError : The "dnspython" module must be installed to use mongodb+srv://URIs even after pymongo and dnspython installed

转载 作者:行者123 更新时间:2023-12-04 01:34:12 26 4
gpt4 key购买 nike

我尝试使用 pymongo 连接 MongoDB。但是遇到了dnspython必须安装的错误即使在我安装了 pymongo 和 dnspython 之后。

我的代码是:

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)

为什么mongodb不能识别我已经安装了pymongo和dnspython?

最佳答案

您的问题是您没有 dnspython安装在您正在运行的环境中。如果您确实安装了 dnspython,则不会收到此错误消息。

使用 docker 中的临时环境很容易证明这一点;使用以下命令启动 docker 容器:

docker run --rm -it python:3.8.1-buster /bin/bash

然后在 shell 中运行以下命令以在仅安装了 pymongo 的新 venv 中创建和运行您的程序:
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

您应该看到以下输出:
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

你会观察到你得到的错误。现在添加 dnspython 并再次运行:
pip install dnspython
pip freeze && python test.py

您现在将看到一条身份验证失败消息,因为我们没有正确的用户名和密码。你可以从 pip freeze看到这次安装dnspython的命令。
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.

关于python - pymongo.errors.ConfigurationError : The "dnspython" module must be installed to use mongodb+srv://URIs even after pymongo and dnspython installed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60118721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com