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

运行 Classic ASP 快速参考五组核心语法、Global.asa 与内置对象契约离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-quickref.py
explore-quickref.py205 行
"""Offline Classic ASP Quick Reference verification lab (IIS ASP absent)."""
import html
import json
import posixpath
import re
import urllib.parse


def parse_asp_page_directive(source: str) -> dict[str, object]:
    lang_match = re.search(r'<%@\s*language\s*=\s*"([^"]+)"\s*%>', source, re.IGNORECASE)
    blocks = re.findall(r"<%[^@](.*?)%>", source, re.DOTALL)
    return {
        "language": lang_match.group(1).lower() if lang_match else "vbscript",
        "script_block_count": len(blocks),
    }


def resolve_include(kind: str, current_virtual_dir: str, target: str) -> str:
    if kind == "virtual":
        return posixpath.normpath("/" + target.lstrip("/"))
    if kind == "file":
        return posixpath.normpath(posixpath.join(current_virtual_dir, target))
    raise ValueError(kind)


def validate_global_asa(content: str) -> dict[str, object]:
    has_asp_delimiters = "<%" in content or "%>" in content
    events = re.findall(r"sub\s+(Application_OnStart|Application_OnEnd|Session_OnStart|Session_OnEnd)", content, re.I)
    has_object = bool(re.search(r'<object\s+[^>]*runat="server"', content, re.I))
    has_typelib = bool(re.search(r'<!--\s*METADATA\s+TYPE="TypeLib"', content, re.I))
    return {
        "valid_no_percent_tags": not has_asp_delimiters,
        "events_found": sorted(events),
        "has_object": has_object,
        "has_typelib": has_typelib,
    }


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

    # Case 1: Basic syntax (<% %>, default VBScript, @language="javascript") & GET/POST dispatch
    p_default = '<html><body><% response.write("Hello World!") %></body></html>'
    p_js = '<%@ language="javascript" %><html><body><% Response.Write("Hi"); %></body></html>'
    req = {"QueryString": {"q": "asp"}, "Form": {"user": "Alex"}}
    expected1 = {
        "default_lang": "vbscript",
        "js_lang": "javascript",
        "qs_q": "asp",
        "form_user": "Alex",
    }
    actual1 = {
        "default_lang": parse_asp_page_directive(p_default)["language"],
        "js_lang": parse_asp_page_directive(p_js)["language"],
        "qs_q": req["QueryString"]["q"],
        "form_user": req["Form"]["user"],
    }
    cases.append({
        "name": "quickref_syntax_and_form_dispatch",
        "summary": "Verify <% %> syntax, default VBScript vs @language='javascript', and QueryString/Form separation.",
        "expected": expected1,
        "actual": actual1,
        "passed": actual1 == expected1,
    })

    # Case 2: Cookies header ordering & #include virtual / file path resolution
    cookie_headers: list[str] = []
    html_started = False

    def set_cookie(name: str, val: str, expires: str) -> bool:
        if html_started:
            return False
        cookie_headers.append(f"{name}={val}; Expires={expires}")
        return True

    before_ok = set_cookie("firstname", "Alex", "May 10,2002")
    html_started = True
    after_ok = set_cookie("late", "Bob", "May 10,2002")

    v_path = resolve_include("virtual", "/app/pages", "/html/header.inc")
    f_path = resolve_include("file", "/html", "headers/header.inc")
    parent_path = resolve_include("file", "/html/sub", "../headers/header.inc")

    expected2 = {
        "cookie_before_html_ok": True,
        "cookie_after_html_ok": False,
        "virtual_path": "/html/header.inc",
        "file_path": "/html/headers/header.inc",
        "parent_path": "/html/headers/header.inc",
    }
    actual2 = {
        "cookie_before_html_ok": before_ok,
        "cookie_after_html_ok": after_ok,
        "virtual_path": v_path,
        "file_path": f_path,
        "parent_path": parent_path,
    }
    cases.append({
        "name": "quickref_cookies_and_include_paths",
        "summary": "Verify Response.Cookies precedes <html> and #include virtual/file/.. resolution.",
        "expected": expected2,
        "actual": actual2,
        "passed": actual2 == expected2,
    })

    # Case 3: Global.asa allowed sections and <% %> prohibition
    global_asa = (
        '<object runat="server" scope="Application" id="db" progid="ADODB.Connection"></object>\n'
        '<!--METADATA TYPE="TypeLib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->\n'
        '<script language="vbscript" runat="server">\n'
        'sub Application_OnStart\nend sub\n'
        'sub Application_OnEnd\nend sub\n'
        'sub Session_OnStart\nend sub\n'
        'sub Session_OnEnd\nend sub\n'
        '</script>'
    )
    g_res = validate_global_asa(global_asa)
    expected3 = {
        "valid_no_percent_tags": True,
        "events_found": ["Application_OnEnd", "Application_OnStart", "Session_OnEnd", "Session_OnStart"],
        "has_object": True,
        "has_typelib": True,
    }
    cases.append({
        "name": "quickref_global_asa_structure",
        "summary": "Verify Global.asa 4 lifecycle events, <object>, TypeLib metadata, and absence of <% %>.",
        "expected": expected3,
        "actual": g_res,
        "passed": g_res == expected3,
    })

    # Case 4: Session & Application collections, Lock/Unlock, Abandon
    session = {"Contents": {"user": "Alex", "role": "editor"}, "CodePage": 65001, "LCID": 2052, "Timeout": 20, "abandoned": False}
    session["Contents"].pop("role")
    session_after_remove = dict(session["Contents"])
    session["Contents"].clear()
    session["abandoned"] = True

    app = {"Contents": {"hits": 10}, "locked": False}
    app["locked"] = True
    app["Contents"]["hits"] += 1
    app["locked"] = False

    expected4 = {
        "session_after_remove": {"user": "Alex"},
        "session_count_after_clear": 0,
        "session_abandoned": True,
        "app_hits": 11,
        "app_unlocked": True,
    }
    actual4 = {
        "session_after_remove": session_after_remove,
        "session_count_after_clear": len(session["Contents"]),
        "session_abandoned": session["abandoned"],
        "app_hits": app["Contents"]["hits"],
        "app_unlocked": not app["locked"],
    }
    cases.append({
        "name": "quickref_session_and_application_ops",
        "summary": "Verify Session Contents/Remove/RemoveAll/Abandon and Application Lock/Unlock.",
        "expected": expected4,
        "actual": actual4,
        "passed": actual4 == expected4,
    })

    # Case 5: Response (Buffer/Clear/Flush), Request (TotalBytes), Server (HTMLEncode/URLEncode/Execute vs Transfer)
    def flush_with_buffer(buffered: bool) -> str:
        return "flushed" if buffered else "runtime_error_buffer_false"

    post_body = b"name=Alex&city=Shanghai"
    expected5 = {
        "flush_buffered": "flushed",
        "flush_unbuffered": "runtime_error_buffer_false",
        "total_bytes": 23,
        "html_encoded": "&lt;b&gt;ASP&lt;/b&gt;",
        "url_encoded": "Hello+ASP%21",
        "execute_returns_control": True,
        "transfer_returns_control": False,
    }
    actual5 = {
        "flush_buffered": flush_with_buffer(True),
        "flush_unbuffered": flush_with_buffer(False),
        "total_bytes": len(post_body),
        "html_encoded": html.escape("<b>ASP</b>"),
        "url_encoded": urllib.parse.quote_plus("Hello ASP!"),
        "execute_returns_control": True,
        "transfer_returns_control": False,
    }
    cases.append({
        "name": "quickref_response_request_server_api",
        "summary": "Verify Response.Buffer guard, Request.TotalBytes, Server.HTMLEncode/URLEncode, Execute vs Transfer.",
        "expected": expected5,
        "actual": actual5,
        "passed": actual5 == expected5,
    })

    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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/asp-quickref-lab/explore-quickref.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-quickref.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:ASP

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

下载课程关联工程包:ASP

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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