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

离线实现 GridFS 255 KiB (261120B) 分块写入、二进制重组与 MD5/SHA-256 校验

PYTHONWindows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。explore-gridfs.py
explore-gridfs.py110 行
"""Offline MongoDB GridFS 255 KiB chunking, metadata & MD5/SHA-256 reassembly verifier."""
import hashlib
import json
import math

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"

DEFAULT_CHUNK_SIZE = 255 * 1024  # 261120 bytes (official GridFS default)


class OfflineGridFS:
    def __init__(self, chunk_size=DEFAULT_CHUNK_SIZE):
        self.chunk_size = chunk_size
        self.files = []
        self.chunks = []
        self._seq = 1

    def put(self, filename, raw_bytes, upload_date="2026-01-01T00:00:00Z", content_type="application/octet-stream"):
        file_id = f"534a811bf8b4aa4d33fdf9{self._seq:02x}"
        self._seq += 1
        md5_hex = hashlib.md5(raw_bytes).hexdigest()
        sha256_hex = hashlib.sha256(raw_bytes).hexdigest()
        file_doc = {
            "_id": file_id,
            "filename": filename,
            "chunkSize": self.chunk_size,
            "uploadDate": upload_date,
            "length": len(raw_bytes),
            "md5": md5_hex,
            "metadata": {"sha256": sha256_hex, "contentType": content_type},
        }
        self.files.append(file_doc)
        n = 0
        for offset in range(0, len(raw_bytes), self.chunk_size):
            part = raw_bytes[offset:offset + self.chunk_size]
            self.chunks.append({"files_id": file_id, "n": n, "data": part})
            n += 1
        return file_doc

    def get(self, file_id):
        parts = sorted((c for c in self.chunks if c["files_id"] == file_id), key=lambda c: c["n"])
        return b"".join(c["data"] for c in parts)


def main():
    gfs = OfflineGridFS()

    # Case 1: Small file (646 bytes -> 1 chunk) matching fs.files & fs.chunks schema
    small_payload = b"GridFS demo content " * 32 + b"123456"
    f_small = gfs.put("test.txt", small_payload, content_type="text/plain")
    small_chunks = [c for c in gfs.chunks if c["files_id"] == f_small["_id"]]
    reassembled_small = gfs.get(f_small["_id"])
    c1_actual = {
        "length": f_small["length"],
        "chunkSize": f_small["chunkSize"],
        "chunk_count": len(small_chunks),
        "first_chunk_n": small_chunks[0]["n"],
        "roundtrip_md5_match": hashlib.md5(reassembled_small).hexdigest() == f_small["md5"],
        "roundtrip_sha256_match": hashlib.sha256(reassembled_small).hexdigest() == f_small["metadata"]["sha256"],
    }
    c1_expected = {
        "length": 646,
        "chunkSize": 261120,
        "chunk_count": 1,
        "first_chunk_n": 0,
        "roundtrip_md5_match": True,
        "roundtrip_sha256_match": True,
    }

    # Case 2: Multi-chunk binary file (> 255 KiB, e.g., 1,000,000 bytes -> 4 chunks) + 10,401,959-byte song.mp3 chunk math
    med_payload = bytes((i * 31) % 256 for i in range(1_000_000))
    f_med = gfs.put("sample.bin", med_payload)
    med_chunks = [c for c in gfs.chunks if c["files_id"] == f_med["_id"]]
    reassembled_med = gfs.get(f_med["_id"])
    song_expected_chunks = math.ceil(10_401_959 / DEFAULT_CHUNK_SIZE)
    c2_actual = {
        "med_chunk_count": len(med_chunks),
        "med_chunk_sizes": [len(c["data"]) for c in med_chunks],
        "med_reassembled_exact": reassembled_med == med_payload,
        "song_mp3_10401959_chunks": song_expected_chunks,
    }
    c2_expected = {
        "med_chunk_count": 4,
        "med_chunk_sizes": [261120, 261120, 261120, 216640],
        "med_reassembled_exact": True,
        "song_mp3_10401959_chunks": 40,
    }

    cases = [
        {
            "name": "gridfs_files_and_chunks_schema",
            "summary": "Verify fs.files (chunkSize=261120, length=646) and fs.chunks (files_id, n=0) round-trip MD5/SHA-256.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "gridfs_multichunk_split_and_reassembly",
            "summary": "Verify 255 KiB chunk splitting, exact binary reassembly, and 10,401,959-byte song.mp3 = 40 chunks.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。

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

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-gridfs.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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