PyMongo 3.6.1报InvalidURI空用户名错误,3.6.0正常求修复方案
InvalidURI: The empty string is not valid username错误 Hey Jeremy, I see your code worked perfectly in PyMongo 3.6.0 but started throwing that URI error in 3.6.1 — let’s break this down and fix it right away.
问题根源
PyMongo 3.6.1 tightened up its URI validation rules. In the 3.6.0 version, passing empty strings for username/password in the connection URI was allowed (even though it wasn’t great practice), but the newer version explicitly blocks empty strings as valid authentication credentials. Since your code pulls muser and mpwd from environment variables and defaults to empty strings when they’re missing, that’s exactly what’s triggering the error.
修复方案
Here are a few solid approaches based on your actual MongoDB setup:
1. 如果你的MongoDB不需要认证(比如测试环境)
Skip the auth parameters entirely in your connection string:
from pymongo import MongoClient from bson.objectid import ObjectId import os,pymongo client = MongoClient('mongodb://machine.company.com:27017/techautomation') db = client.techautomation
2. 动态构建URI(兼容有/无认证场景)
Check if you have valid credentials before building an authenticated URI:
from pymongo import MongoClient from bson.objectid import ObjectId import os,pymongo # 去掉默认空字符串,环境变量不存在时返回None dbuser = os.environ.get('muser') dbpass = os.environ.get('mpwd') # 只有当用户名和密码都存在时才用认证URI if dbuser and dbpass: uri = f'mongodb://{dbuser}:{dbpass}@machine.company.com:27017/techautomation' else: uri = 'mongodb://machine.company.com:27017/techautomation' client = MongoClient(uri) db = client.techautomation
3. 使用MongoClient参数传递认证信息(更推荐)
Instead of building the URI manually, pass auth details as parameters — this avoids URI parsing headaches entirely:
from pymongo import MongoClient from bson.objectid import ObjectId import os,pymongo dbuser = os.environ.get('muser') dbpass = os.environ.get('mpwd') client = MongoClient( host='machine.company.com', port=27017, username=dbuser, # 当dbuser为None时,PyMongo自动跳过认证 password=dbpass, authSource='techautomation' # 指定用于认证的数据库 ) db = client.techautomation
This approach is cleaner because PyMongo handles the auth logic automatically: if username or password is None, it won’t attempt to authenticate, which aligns perfectly with 3.6.1’s stricter validation rules.
内容的提问来源于stack exchange,提问作者Jeremyapple

