"""Offline Python verification lab for PyCharm Chapter 17 (django)."""
import ast
import json
import re
import tempfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline PyCharm workflow verifier (desktop IDE not launched)"
def case_django_project_and_app_scaffold():
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "DjangoProject"
pkg = root / "DjangoProject"
app = root / "myapp"
tpl = root / "templates" / "myapp"
for d in (pkg, app / "migrations", tpl):
d.mkdir(parents=True)
files = [
root / "manage.py",
root / "requirements.txt",
pkg / "__init__.py",
pkg / "settings.py",
pkg / "urls.py",
pkg / "wsgi.py",
app / "__init__.py",
app / "admin.py",
app / "apps.py",
app / "models.py",
app / "tests.py",
app / "views.py",
app / "urls.py",
tpl / "post_list.html",
]
for f in files:
f.write_text("", encoding="utf-8")
commands = [
"python3 manage.py runserver",
"python manage.py runserver 8080",
"python manage.py migrate",
"python3 manage.py startapp myapp",
"python manage.py makemigrations",
]
expected = {
"project_pkg_has_dunder_init": True,
"app_core_files_count": 6,
"template_file_exists": True,
"cli_command_count": 5,
}
actual = {
"project_pkg_has_dunder_init": (pkg / "__init__.py").is_file(),
"app_core_files_count": sum(1 for name in ("admin.py", "apps.py", "models.py", "tests.py", "views.py", "urls.py") if (app / name).is_file()),
"template_file_exists": (tpl / "post_list.html").is_file(),
"cli_command_count": len(commands),
}
return {
"name": "django_project_and_app_scaffold",
"summary": "在临时目录生成标准 Django 项目与应用目录骨架(含 __init__.py 与 templates/myapp/)并核对管理命令",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_settings_and_url_routing_ast():
settings_src = (
"from pathlib import Path\n"
"BASE_DIR = Path('/workspace/DjangoProject')\n"
"INSTALLED_APPS = ['django.contrib.admin', 'myapp']\n"
"TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates']}]\n"
)
broken_urls = (
"from django.contrib import admin\n"
"from django.urls import path\n"
"urlpatterns = [\n"
" path('admin/', admin.site.urls),\n"
" path('myapp/', include('myapp.urls')),\n"
"]\n"
)
fixed_urls = broken_urls.replace("from django.urls import path", "from django.urls import path, include")
app_urls = (
"from django.urls import path\n"
"from . import views\n"
"urlpatterns = [path('', views.post_list, name='post_list')]\n"
)
def missing_include_import(src):
tree = ast.parse(src)
imported = {
alias.name
for n in ast.walk(tree)
if isinstance(n, ast.ImportFrom)
for alias in n.names
}
called = {
n.func.id
for n in ast.walk(tree)
if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
}
return "include" in called and "include" not in imported
ns = {}
exec(compile(ast.parse(settings_src), "<settings>", "exec"), ns)
app_urls_tree = ast.parse(app_urls)
expected = {
"myapp_registered": True,
"template_dirs_configured": True,
"detects_missing_include_bug": True,
"fixed_urls_imports_include": True,
"app_urls_valid_ast": True,
}
actual = {
"myapp_registered": "myapp" in ns["INSTALLED_APPS"],
"template_dirs_configured": str(ns["TEMPLATES"][0]["DIRS"][0]).endswith("templates"),
"detects_missing_include_bug": missing_include_import(broken_urls),
"fixed_urls_imports_include": not missing_include_import(fixed_urls),
"app_urls_valid_ast": any(isinstance(n, ast.Assign) for n in app_urls_tree.body),
}
return {
"name": "settings_and_url_routing_ast",
"summary": "通过 AST 校验 settings.py 配置项并检出根 urls.py 漏导 include 的常见错误与修复写法",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_model_and_view_ast_validation():
models_src = (
"from django.db import models\n\n"
"class Post(models.Model):\n"
" title = models.CharField(max_length=200)\n"
" content = models.TextField()\n"
" created_at = models.DateTimeField(auto_now_add=True)\n\n"
" def __str__(self):\n"
" return self.title\n"
)
views_src = (
"from django.shortcuts import render\n"
"from .models import Post\n\n"
"def post_list(request):\n"
" posts = Post.objects.all()\n"
" return render(request, 'myapp/post_list.html', {'posts': posts})\n"
)
mtree = ast.parse(models_src)
post_cls = next(n for n in mtree.body if isinstance(n, ast.ClassDef) and n.name == "Post")
fields = [n.targets[0].id for n in post_cls.body if isinstance(n, ast.Assign)]
methods = [n.name for n in post_cls.body if isinstance(n, ast.FunctionDef)]
vtree = ast.parse(views_src)
view_fn = next(n for n in vtree.body if isinstance(n, ast.FunctionDef) and n.name == "post_list")
render_calls = [
n for n in ast.walk(view_fn)
if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id == "render"
]
template_arg = render_calls[0].args[1].value if render_calls else ""
expected = {
"model_fields": ["title", "content", "created_at"],
"has_dunder_str": True,
"view_template": "myapp/post_list.html",
}
actual = {
"model_fields": fields,
"has_dunder_str": "__str__" in methods,
"view_template": template_arg,
}
return {
"name": "model_and_view_ast_validation",
"summary": "通过 AST 核对 Post 模型字段定义(title/content/created_at/__str__)与 post_list 视图模板路径",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_django_template_offline_render():
template_html = (
"<ul>\n"
"{% for post in posts %}\n"
"<li>{{ post.title }} - {{ post.created_at }}</li>\n"
"{% empty %}\n"
"<li>No posts available.</li>\n"
"{% endfor %}\n"
"</ul>"
)
def render_for_empty(tpl, posts):
m = re.search(
r"\{% for post in posts %\}(.*?)\{% empty %\}(.*?)\{% endfor %\}",
tpl,
flags=re.S,
)
loop_body, empty_body = m.group(1).strip(), m.group(2).strip()
if posts:
items = [
loop_body.replace("{{ post.title }}", p["title"]).replace("{{ post.created_at }}", p["created_at"])
for p in posts
]
inner = "\n".join(items)
else:
inner = empty_body
return tpl[: m.start()] + inner + tpl[m.end() :]
populated = render_for_empty(
template_html,
[{"title": "First Post", "created_at": "2026-12-01"}],
)
empty = render_for_empty(template_html, [])
expected = {
"populated_has_item": True,
"empty_fallback_triggered": True,
}
actual = {
"populated_has_item": "<li>First Post - 2026-12-01</li>" in populated,
"empty_fallback_triggered": "<li>No posts available.</li>" in empty,
}
return {
"name": "django_template_offline_render",
"summary": "离线渲染 post_list.html 模板的 for/empty 块,验证有数据与空列表回退输出",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_django_project_and_app_scaffold(),
case_settings_and_url_routing_ast(),
case_model_and_view_ast_validation(),
case_django_template_offline_render(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。
入口文件:projects/pycharm-django-lab/explore-django.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-django.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联17章) · 含当前章节或实例 · mbskycom202612a2240.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2243.zip