"""Offline MongoDB URI parser (mongodb:// & mongodb+srv://), options & driver binding verifier (Ch10)."""
import json
import re
from urllib.parse import parse_qsl, unquote
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
VALID_READ_PREFS = {"primary", "primaryPreferred", "secondary", "secondaryPreferred", "nearest"}
def parse_mongo_uri(uri: str) -> dict:
if uri.startswith("mongodb+srv://"):
scheme = "mongodb+srv"
rest = uri[len("mongodb+srv://") :]
elif uri.startswith("mongodb://"):
scheme = "mongodb"
rest = uri[len("mongodb://") :]
else:
raise ValueError(f"Unsupported scheme: {uri}")
query_str = ""
if "?" in rest:
rest, query_str = rest.split("?", 1)
db_name = None
if "/" in rest:
authority, path = rest.split("/", 1)
db_name = unquote(path) if path else None
else:
authority = rest
username = password = None
if "@" in authority:
userinfo, hosts_part = authority.rsplit("@", 1)
if ":" in userinfo:
u, p = userinfo.split(":", 1)
username, password = unquote(u), unquote(p)
else:
username = unquote(userinfo)
else:
hosts_part = authority
hosts = []
for item in hosts_part.split(","):
if ":" in item:
h, p = item.rsplit(":", 1)
hosts.append((h, int(p)))
else:
hosts.append((item, None if scheme == "mongodb+srv" else 27017))
# Support modern '&' and legacy ';' option separators
norm_q = query_str.replace(";", "&")
options = dict(parse_qsl(norm_q, keep_blank_values=True))
return {
"scheme": scheme,
"username": username,
"password": password,
"hosts": hosts,
"database": db_name,
"options": options,
}
def case_standard_uri_syntax_parser():
u1 = parse_mongo_uri("mongodb://localhost")
u2 = parse_mongo_uri("mongodb://username:pass%40word@host1:27017,host2:27018,host3:27019/mydatabase?replicaSet=myReplicaSet")
u3 = parse_mongo_uri("mongodb+srv://cluster0.example.net/appdb?retryWrites=true&w=majority")
actual = {
"u1_default_host_port": u1["hosts"],
"u2_user_pwd": [u2["username"], u2["password"]],
"u2_host_count": len(u2["hosts"]),
"u2_db_and_rs": [u2["database"], u2["options"]["replicaSet"]],
"u3_srv_scheme_and_tls_implicit": [u3["scheme"], u3["hosts"][0][1] is None],
}
expected = {
"u1_default_host_port": [("localhost", 27017)],
"u2_user_pwd": ["username", "pass@word"],
"u2_host_count": 3,
"u2_db_and_rs": ["mydatabase", "myReplicaSet"],
"u3_srv_scheme_and_tls_implicit": ["mongodb+srv", True],
}
return {
"name": "standard_uri_syntax_parser",
"summary": "解析标准 mongodb:// 与 mongodb+srv:// URI,验证默认 27017 端口、密码百分号解码与多节点副本集种子列表。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_connection_options_validation():
u = parse_mongo_uri(
"mongodb://user:pwd@localhost:27017/mydatabase"
"?authSource=admin&ssl=true&readPreference=secondaryPreferred&connectTimeoutMS=5000&socketTimeoutMS=10000"
)
opts = u["options"]
actual = {
"authSource": opts["authSource"],
"ssl_enabled": opts["ssl"].lower() == "true",
"readPreference_valid": opts["readPreference"] in VALID_READ_PREFS,
"timeouts_ms": [int(opts["connectTimeoutMS"]), int(opts["socketTimeoutMS"])],
}
expected = {
"authSource": "admin",
"ssl_enabled": True,
"readPreference_valid": True,
"timeouts_ms": [5000, 10000],
}
return {
"name": "connection_options_validation",
"summary": "校验 authSource、ssl/tls、readPreference 五种读偏好及连接/套接字超时选项解析。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_legacy_vs_modern_uri_options():
legacy = parse_mongo_uri("mongodb://host1,host2,host3/?safe=true;w=2;wtimeoutMS=2000")
legacy_direct = parse_mongo_uri("mongodb://host1,host2,host3/?connect=direct;slaveOk=true")
def modernize(opts: dict) -> dict:
out = {}
if opts.get("slaveOk") == "true":
out["readPreference"] = "secondaryPreferred"
if opts.get("connect") == "direct":
out["directConnection"] = "true"
if "w" in opts:
out["w"] = opts["w"]
elif opts.get("safe") == "true":
out["w"] = "1"
if "wtimeoutMS" in opts:
out["wtimeoutMS"] = opts["wtimeoutMS"]
return out
actual = {
"legacy_write_concern_modernized": modernize(legacy["options"]),
"legacy_direct_slaveok_modernized": modernize(legacy_direct["options"]),
}
expected = {
"legacy_write_concern_modernized": {"w": "2", "wtimeoutMS": "2000"},
"legacy_direct_slaveok_modernized": {"readPreference": "secondaryPreferred", "directConnection": "true"},
}
return {
"name": "legacy_vs_modern_uri_options",
"summary": "核对历史连接参数(slaveOk、connect=direct、safe=true、分号分隔)与现代标准选项的等价映射。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_multilang_driver_uri_bindings():
uri = "mongodb://user:password@localhost:27017/mydatabase?authSource=admin"
parsed = parse_mongo_uri(uri)
drivers = {
"python_pymongo": "MongoClient",
"nodejs_mongoose": "mongoose.connect",
"php_mongodb": "MongoDB\\Client",
"java_driver": "MongoClients.create",
}
actual = {
"driver_count": len(drivers),
"shared_db_target": parsed["database"],
"shared_auth_source": parsed["options"]["authSource"],
}
expected = {
"driver_count": 4,
"shared_db_target": "mydatabase",
"shared_auth_source": "admin",
}
return {
"name": "multilang_driver_uri_bindings",
"summary": "验证 Python(PyMongo)、Node.js(Mongoose)、PHP(MongoDB\\Client) 与 Java 驱动共用标准 URI 连接契约。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mongod_connection_log_parser():
log_line = "2015-09-25T17:22:36.012+0800 I NETWORK [initandlisten] connection accepted from 127.0.0.1:37310 #1 (1 connection now open)"
m = re.search(r"connection accepted from ([\d.]+):(\d+) #(\d+) \((\d+) connection", log_line)
banner_uri = "mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.9"
parsed_banner = parse_mongo_uri(banner_uri)
actual = {
"client_ip": m.group(1),
"client_port": int(m.group(2)),
"conn_id": int(m.group(3)),
"open_count": int(m.group(4)),
"mongosh_direct": parsed_banner["options"]["directConnection"],
}
expected = {
"client_ip": "127.0.0.1",
"client_port": 37310,
"conn_id": 1,
"open_count": 1,
"mongosh_direct": "true",
}
return {
"name": "mongod_connection_log_parser",
"summary": "解析 mongod 服务端连接接入日志与 mongosh 启动横幅中的 directConnection 参数。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_standard_uri_syntax_parser(),
case_connection_options_validation(),
case_legacy_vs_modern_uri_options(),
case_multilang_driver_uri_bindings(),
case_mongod_connection_log_parser(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/mongodb-connections-lab/explore-connections.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-connections.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1735.zip
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip