蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

下载 PyMongo 本机实验

PYTHON本地 Python 3.12、PyMongo 4.19 与独立 MongoDBpython-mongodb.py
python-mongodb.py126 行
"""蓝色天空网 mbsky.com · PyMongo 本机独立实例。"""
from argparse import ArgumentParser
from datetime import datetime, timezone
from pathlib import Path
import platform
import socket
import sys
from uuid import uuid4

import pymongo
from bson import BSON, ObjectId
from bson.codec_options import CodecOptions
from pymongo.errors import DuplicateKeyError, ServerSelectionTimeoutError

sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks


def connect(port, selection_timeout_ms=3000):
    return pymongo.MongoClient(
        "127.0.0.1",
        port,
        directConnection=True,
        connect=False,
        serverSelectionTimeoutMS=selection_timeout_ms,
    )


def verify_unreachable(check):
    with socket.socket() as unlistened:
        unlistened.bind(("127.0.0.1", 0))
        port = unlistened.getsockname()[1]
        with connect(port, 200) as client:
            check.eq("client handle exists without a server", type(client).__name__, "MongoClient")
            check.raises("ping reports unavailable server", ServerSelectionTimeoutError,
                         lambda: client.admin.command("ping"))


def verify_bson(check):
    stamp = datetime(2024, 2, 29, 12, tzinfo=timezone.utc)
    data = {"recorded": stamp, "payload": b"\x00\x02", "samples": [1, {"pass": True}]}
    encoded = BSON.encode(data)
    decoded = encoded.decode(codec_options=CodecOptions(tz_aware=True))
    check.eq("BSON preserves UTC datetime", decoded["recorded"].isoformat(), stamp.isoformat())
    check.eq("BSON preserves bytes and nested values", (decoded["payload"], decoded["samples"]),
             (b"\x00\x02", [1, {"pass": True}]))


def exercise(check, client, name):
    check.eq("server replies to ping", client.admin.command("ping")["ok"], 1.0)
    db = client[name]
    collection = db["inventory"]
    check.eq("database and collection names from handles", (db.name, collection.name), (name, "inventory"))
    check.eq("database absent after only creating handles", name in client.list_database_names(), False)
    check.eq("collection absent after only creating handles", db.list_collection_names(), [])
    check.raises("legacy database_names is removed", TypeError, lambda: client.database_names())
    check.raises("legacy collection_names is removed", TypeError, lambda: db.collection_names())

    try:
        created = db.create_collection("audit")
        check.eq("explicit create makes an empty collection visible",
                 ("audit" in db.list_collection_names(), created.count_documents({})), (True, 0))
        check.eq("explicit create makes the database visible", name in client.list_database_names(), True)
        check.eq("inventory still absent after creating different collection",
                 "inventory" in db.list_collection_names(), False)

        seed = collection.insert_one({"item": "marker", "units": 9})
        check.eq("insert returns acknowledged ObjectId", (seed.acknowledged, isinstance(seed.inserted_id, ObjectId)),
                 (True, True))
        check.eq("first insert creates the target collection",
                 sorted(db.list_collection_names()), ["audit", "inventory"])
        check.eq("read by returned inserted id", collection.find_one({"_id": seed.inserted_id})["item"], "marker")
        check.raises("duplicate id is rejected", DuplicateKeyError,
                     lambda: collection.insert_one({"_id": seed.inserted_id, "item": "duplicate"}))
        documents = [
            {"_id": "B2", "item": "北岸", "units": 4},
            {"_id": "A1", "item": "西门", "units": 7},
            {"_id": "C3", "item": "南站", "units": 7},
        ]
        check.eq("insert fixture ids", collection.insert_many(documents).inserted_ids, ["B2", "A1", "C3"])
        filter_by_id = {"_id": {"$in": ["B2", "A1", "C3"]}}
        cursor = collection.find({**filter_by_id, "units": {"$gte": 7}}, {"_id": 0, "item": 1})
        check.eq("find filters and projects", sorted(row["item"] for row in cursor), sorted(["西门", "南站"]))
        check.eq("no matches produce an empty cursor", list(collection.find({"_id": "missing"})), [])
        order = collection.find(filter_by_id, {"_id": 1}).sort([("units", -1), ("_id", 1)])
        check.eq("sort by quantity then id", [row["_id"] for row in order], ["A1", "C3", "B2"])

        updated = collection.update_one({"_id": "B2"}, {"$set": {"units": 6}})
        check.eq("update reports match and change", (updated.matched_count, updated.modified_count), (1, 1))
        check.eq("updated value is visible", collection.find_one({"_id": "B2"})["units"], 6)
        unchanged = collection.update_one({"_id": "B2"}, {"$set": {"units": 6}})
        check.eq("same value matches without modifying", (unchanged.matched_count, unchanged.modified_count), (1, 0))
        absent = collection.update_one({"_id": "missing"}, {"$set": {"units": 6}})
        check.eq("missing update matches zero", (absent.matched_count, absent.modified_count), (0, 0))

        deleted = collection.delete_one({"_id": "A1"})
        check.eq("delete reports one removal", deleted.deleted_count, 1)
        check.eq("deleted record no longer exists", collection.find_one({"_id": "A1"}), None)
        check.eq("repeated delete reports zero", collection.delete_one({"_id": "A1"}).deleted_count, 0)
    finally:
        client.drop_database(name)

    check.eq("experiment database is cleaned up", name in client.list_database_names(), False)


def main():
    parser = ArgumentParser(description="Use only a disposable local MongoDB server.")
    parser.add_argument("--port", type=int, required=True)
    args = parser.parse_args()
    if not 1024 <= args.port <= 65535 or args.port == 27017:
        parser.error("Specify a non-default port for a disposable local instance.")
    check = Checks()
    verify_bson(check)
    verify_unreachable(check)
    with connect(args.port) as client:
        name = "mbsky_lab_" + uuid4().hex
        exercise(check, client, name)
        server = client.server_info()["version"]
    check.finish("python-mongodb", python=platform.python_version(), platform=platform.platform(),
                 pymongo=pymongo.version, mongodb=server, database=name, loopback_port=args.port,
                 conditions="Dedicated unauthenticated MongoDB bound to IPv4 loopback with isolated data directory.")


if __name__ == "__main__":
    main()
本例需在 本地 Python 3.12、PyMongo 4.19 与独立 MongoDB 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 3.12、PyMongo 4.19 与独立 MongoDB

入口文件:projects/python-lab/python-mongodb.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-mongodb.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 3.12、PyMongo 4.19 与独立 MongoDB。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习