蓝色天空.知识 · 实践 · 创造
我的收藏
ASP 教程目录 36章
ASP / LEARN BY DOING

ASP Content Rotator

核对 ASP 3.0 MSWC.ContentRotator 组件的 Content Schedule File 权重语法(%% #n)、ChooseContent 按权随机展示与 GetAllContent 全量输出。

学完这一章,你能够

  • 核对 ASP 3.0 MSWC.ContentRotator 组件的 Content Schedule File 权重语法(%% #n)、ChooseContent 按权随机展示与 GetAllContent 全量输出。

Content Rotator 组件定位与内容调度文件格式

`ASP Content Rotator`(ASP 3.0 起提供)通过 `Server.CreateObject("MSWC.ContentRotator")` 实例化,用于在访客进入或刷新页面时从纯文本内容调度文件(Content Schedule File)中轮换展示一段 HTML 内容片段。片段中可自由包含标题文本、图像标签、样式或超链接。

textads.txt 相对权重配置与方法输出行为

在调度文件(例如子目录 `text/textads.txt`)中,每段内容由以 `%%` 开头的分隔行引导,其后可附加可选权重 `#数字`(省略时默认权重为 `1`)及 `//` 注释。当三段内容的权重分别为 `#3`、`#3`、`#4`(权重总和为 10)时,页面分别有 3/10、3/10 与 4/10 的概率展示标题文本、笑脸图片或示例站点链接。

`ContentRotator` 提供 `ChooseContent` 与 `GetAllContent` 两个方法:前者依据相对权重返回单段内容,后者依次输出调度文件内的全部内容片段(如先输出标题 `This is a great day!!`,再输出图像项与站点链接项,并用 `<hr>` 分隔)。本地 CPython 3.12.14 离线验证脚本在临时目录中实测了 `%% #3/#3/#4` 权重解析、1000 次确定性随机抽样分布、`GetAllContent` 全量拼接以及省略 `#weight` 默认为 1 与 `//` 注释剥离。

Content Rotator(MSWC.ContentRotator)组件方法参考

方法作用说明典型调用
ChooseContent按内容调度文件中的相对权重随机抽取并返回一段 HTML 内容字符串。Response.Write(cr.ChooseContent("text/textads.txt"))
GetAllContent取回并返回调度文件中的全部内容片段(各片段间默认以水平线分隔),便于一次性校对。Response.Write(cr.GetAllContent("text/textads.txt"))

运行 MSWC.ContentRotator 权重调度解析、千次抽样分布与 GetAllContent 离线验证

含完整源码 · 165 行
展开查看收起
python
"""Offline Classic ASP Content Rotator (MSWC.ContentRotator) verification lab (IIS ASP absent)."""
import json
from pathlib import Path
import random
import tempfile


class MockContentRotator:
    """Offline model of ASP 3.0 MSWC.ContentRotator reading Content Schedule Files."""

    @staticmethod
    def parse_schedule(path: Path) -> list[tuple[int, str]]:
        entries: list[tuple[int, str]] = []
        current_weight: int | None = None
        current_lines: list[str] = []

        for raw in path.read_text(encoding="utf-8").splitlines():
            stripped = raw.strip()
            if stripped.startswith("%%"):
                if current_weight is not None:
                    entries.append((current_weight, "\n".join(current_lines).strip()))
                rest = stripped[2:].strip()
                # Strip optional // comment after header
                if "//" in rest:
                    rest = rest.split("//", 1)[0].strip()
                weight = 1
                if rest.startswith("#"):
                    token = rest[1:].split()[0]
                    weight = int(token)
                current_weight = weight
                current_lines = []
            elif current_weight is not None:
                current_lines.append(raw)

        if current_weight is not None:
            entries.append((current_weight, "\n".join(current_lines).strip()))
        return entries

    def ChooseContent(self, path: Path, rng: random.Random) -> str:
        entries = self.parse_schedule(path)
        weights = [w for w, _ in entries]
        snippets = [s for _, s in entries]
        return rng.choices(snippets, weights=weights, k=1)[0]

    def GetAllContent(self, path: Path) -> str:
        entries = self.parse_schedule(path)
        return "<hr>".join(s for _, s in entries)


TEXTADS_SAMPLE = """%% #3
<h2>This is a great day!!</h2>
%% #3
<img src="smiley.gif">
%% #4
<a href="https://example.com">Visit Example Portal</a>
"""

DEFAULT_WEIGHT_SAMPLE = """%% // optional comment without explicit weight
<p>Default weight item</p>
%% #2 // double weight item
<p>Weighted item</p>
"""


def main() -> None:
    cases = []

    with tempfile.TemporaryDirectory(prefix="asp_contentrotator_") as tmp:
        text_dir = Path(tmp) / "text"
        text_dir.mkdir()
        schedule_file = text_dir / "textads.txt"
        schedule_file.write_text(TEXTADS_SAMPLE, encoding="utf-8")

        cr = MockContentRotator()

        # Case 1: Schedule parsing and weight probability ratios (3/10, 3/10, 4/10)
        parsed = cr.parse_schedule(schedule_file)
        total_w = sum(w for w, _ in parsed)
        ratios = [round(w / total_w, 2) for w, _ in parsed]
        expected1 = {
            "entry_count": 3,
            "total_weight": 10,
            "ratios": [0.3, 0.3, 0.4],
        }
        actual1 = {
            "entry_count": len(parsed),
            "total_weight": total_w,
            "ratios": ratios,
        }
        cases.append({
            "name": "contentrotator_schedule_parse_weights",
            "summary": "Verify %% #weight parsing yields 3 HTML snippets with 3/10, 3/10, 4/10 probabilities.",
            "expected": expected1,
            "actual": actual1,
            "passed": actual1 == expected1,
        })

        # Case 2: ChooseContent seeded weighted distribution
        rng = random.Random(2026)
        counts = {s: 0 for _, s in parsed}
        for _ in range(1000):
            picked = cr.ChooseContent(schedule_file, rng)
            counts[picked] += 1
        c_list = [counts[s] for _, s in parsed]
        expected2 = {
            "total_draws": 1000,
            "first_near_300": True,
            "second_near_300": True,
            "third_near_400": True,
        }
        actual2 = {
            "total_draws": sum(c_list),
            "first_near_300": abs(c_list[0] - 300) <= 45,
            "second_near_300": abs(c_list[1] - 300) <= 45,
            "third_near_400": abs(c_list[2] - 400) <= 45,
        }
        cases.append({
            "name": "contentrotator_choose_content_distribution",
            "summary": "Verify ChooseContent selects snippets proportionally to #3/#3/#4 weights across 1000 draws.",
            "expected": expected2,
            "actual": actual2,
            "passed": actual2 == expected2,
        })

        # Case 3: GetAllContent returns every snippet separated by <hr>
        all_html = cr.GetAllContent(schedule_file)
        expected3 = (
            '<h2>This is a great day!!</h2><hr>'
            '<img src="smiley.gif"><hr>'
            '<a href="https://example.com">Visit Example Portal</a>'
        )
        cases.append({
            "name": "contentrotator_get_all_content",
            "summary": "Verify GetAllContent outputs all 3 scheduled HTML strings in order separated by <hr>.",
            "expected": expected3,
            "actual": all_html,
            "passed": all_html == expected3,
        })

        # Case 4: Optional #weight defaults to 1 and // comments are ignored
        default_file = text_dir / "default.txt"
        default_file.write_text(DEFAULT_WEIGHT_SAMPLE, encoding="utf-8")
        def_parsed = cr.parse_schedule(default_file)
        expected4 = [
            [1, "<p>Default weight item</p>"],
            [2, "<p>Weighted item</p>"],
        ]
        actual4 = [[w, s] for w, s in def_parsed]
        cases.append({
            "name": "contentrotator_default_weight_and_comments",
            "summary": "Verify omitted #weight defaults to 1 and // inline header comments are stripped.",
            "expected": expected4,
            "actual": actual4,
            "passed": actual4 == expected4,
        })

    print(json.dumps({
        "version": "CPython 3.12.14 offline Classic ASP / VBScript verifier (IIS ASP absent)",
        "cases": cases,
    }, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
验证 #3/#3/#4 概率比(0.3/0.3/0.4)、1000 次 ChooseContent 分布、GetAllContent 按序拼接以及省略权重默认 1 与 // 注释处理。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1425.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:ASP

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

下载课程关联工程包:ASP

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

AdRotator 专用于图片广告横幅,每条记录固定为图/链/替/权 4 行且支持点击重定向;Content Rotator 面向任意 HTML 文本片段,通过 %% #权重 分隔多行 HTML,且支持 GetAllContent 一次查看全部条目。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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