from contextlib import closing
from hashlib import sha256
from pathlib import Path
from secrets import token_urlsafe
from tempfile import TemporaryDirectory
from zipfile import ZipFile
import json
import os
import shutil
import sqlite3
import subprocess
import sys
def check(name,operation,inputs,expected,actual):
assert expected==actual,(name,expected,actual)
return dict(name=name,operation=operation,input=inputs,expected=expected,actual=actual)
def invoke(root,env,*args):
result=subprocess.run([sys.executable,"-B",*args],cwd=root,env=env,capture_output=True,encoding="utf8",timeout=35)
assert result.returncode==0,(args,result.stdout,result.stderr)
return result.stdout+result.stderr
def scaffold(root,env):
def command(*args):
return invoke(root,env,"-m","django",*args)
help_text=command("help")
command("startproject","plaincoast")
destination=root/"elsewhere"
destination.mkdir()
command("startproject","chosen",str(destination))
command("startapp","plain_readings")
other=root/"targets/app_destination"
other.mkdir(parents=True)
command("startapp","shore_parts",str(other))
archive=root/"local-template.zip"
with ZipFile(archive,"w") as bundle:
bundle.writestr("example/subject.txt","{{ project_name }}")
bundle.writestr("example/marker.conf","{{ project_name }}")
bundle.writestr("example/raw.conf","{{ project_name }}")
command("startproject","localcoast","--template",str(archive),"--extension=txt","--name=marker.conf")
app_archive=root/"app-template.zip"
with ZipFile(app_archive,"w") as bundle:
bundle.writestr("example/about.py-tpl",'NAME="{{ app_name }}"')
command("startapp","templated_app","--template",str(app_archive))
file_names=["plaincoast/manage.py","plaincoast/plaincoast/asgi.py","plaincoast/plaincoast/wsgi.py",
"elsewhere/chosen/settings.py","plain_readings/models.py","plain_readings/apps.py",
"targets/app_destination/migrations/__init__.py","plain_readings/tests.py"]
generated=[(root/path).is_file() for path in file_names]
values=[(root/"localcoast"/name).read_text(encoding="utf8") for name in ("subject.txt","marker.conf","raw.conf")]
about=(root/"templated_app/about.py").read_text(encoding="utf8")
return check("Django CLI scaffolds projects and apps from defaults and local ZIP templates",
"Run CLI help, default and targeted scaffolds, and a local template ZIP with extension and exact filename",
["default","explicit directory","local ZIP","--extension=txt","--name=marker.conf"],
[True,True,[True]*len(file_names),["localcoast","localcoast","{{ project_name }}"],'NAME="templated_app"'],
["startproject" in help_text,"startapp" in help_text,generated,values,about])
def migrations(root,env,project):
base=root/"candidate"
base.mkdir()
for name in ("harbor","readings","apps","site_static","templates"):
shutil.copytree(project/name,base/name,ignore=shutil.ignore_patterns("__pycache__","*.pyc"))
shutil.copyfile(project/"manage.py",base/"manage.py")
db=root/"migrations.sqlite"
env=dict(env,DJANGO_LAB_DB=str(db))
def command(*args,**extra):
return invoke(base,dict(env,**extra),"manage.py",*args)
def rows(file,sql):
with closing(sqlite3.connect(file)) as connection:
return [list(row) for row in connection.execute(sql)]
command("migrate","catalog","0001","--noinput")
with closing(sqlite3.connect(db)) as connection,connection:
definition=connection.execute("select sql from sqlite_master where name='catalog_instrument'").fetchone()[0]
connection.execute("INSERT INTO catalog_instrument(name,cost,notes) VALUES('kept',12.5,'first')")
model=base/"apps/catalog/models.py"
original=model.read_text(encoding="utf8")
model.write_text(original.replace(" def __str__", " zone=models.CharField(max_length=12,default='north')\n\n def __str__"),
encoding="utf8")
command("makemigrations","catalog","--name","zone","--noinput")
revision,=(base/"apps/catalog/migrations").glob("0002*.py")
candidate=revision.read_bytes()
fake=command("migrate","catalog","0002","--fake","--noinput")
ledger="select name from django_migrations where app='catalog' order by name"
columns="select name from pragma_table_info('catalog_instrument') order by cid"
marked=rows(db,ledger)
unchanged=rows(db,columns)
command("migrate","catalog","0001","--fake","--noinput")
command("migrate","catalog","0002","--noinput")
applied=rows(db,"select name,zone from catalog_instrument")
copied=root/"preexisting.sqlite"
with closing(sqlite3.connect(copied)) as connection,connection:
connection.execute(definition)
connection.execute("INSERT INTO catalog_instrument(name,cost,notes) VALUES('preexisting',2.5,'older')")
init=command("migrate","catalog","0001","--fake-initial","--noinput",DJANGO_LAB_DB=str(copied))
initial_record=rows(copied,ledger)
existing=rows(copied,"select name from catalog_instrument")
return check("Django migration ledger differs from real schema changes",
"Generate a second revision, fake it, rewind only its ledger and apply it, then fake an existing initial table",
{"revision_sha256":sha256(candidate).hexdigest(),"prior_row":"kept","preexisting_row":"preexisting"},
[True,True,[["0001_initial"],["0002_zone"]],[["id"],["name"],["cost"],["notes"]],
[["kept","north"]],True,[["0001_initial"]],[["preexisting"]]],
[b"migrations.AddField" in candidate,"FAKED" in fake,marked,unchanged,applied,"FAKED" in init,initial_record,existing])
def utilities(root,env,project):
db=root/"utility.sqlite"
static=root/"static"
env=dict(env,DJANGO_LAB_DB=str(db),DJANGO_LAB_STATIC_ROOT=str(static),
DJANGO_SUPERUSER_USERNAME="harbor-admin",DJANGO_SUPERUSER_EMAIL="harbor@example.com",
DJANGO_SUPERUSER_PASSWORD=token_urlsafe(25))
def command(*args):
return invoke(project,env,"manage.py",*args)
command("check")
command("migrate","--noinput")
assert "Superuser created successfully" in command("createsuperuser","--noinput")
source=("from django.contrib.auth import get_user_model; "
"u=get_user_model().objects.get(username='harbor-admin'); print('RESULT',u.is_staff,u.is_superuser)")
shell=command("shell","-c",source)
command("collectstatic","--noinput")
paths=[("catalog.css","site_static/catalog.css"),("readings/palette.css","readings/static/readings/palette.css")]
copied=[(static/target).read_bytes()==(project/src).read_bytes() for target,src in paths]
tests=command("test","apps.catalog","--verbosity","2")
return check("Django management utilities create, query, collect and test",
"Run check, migrate, createsuperuser, shell, collectstatic and the authored test module",
["temporary user","project and app static files","apps.catalog"],[True,[True,True],True,True,True],
["RESULT True True" in shell,copied,"Ran 2 tests" in tests,"test_database_and_template" in tests,"OK" in tests])
def server_flags(project,env):
source="""import json,os
os.environ.setdefault("DJANGO_SETTINGS_MODULE","harbor.settings")
import django
django.setup()
from django.contrib.staticfiles.management.commands.runserver import Command
class Probe(Command):
def run(self, **options):
print(json.dumps([self.addr,self.port,options["use_reloader"],options["insecure_serving"]]))
for args in ([],["8080"],["0.0.0.0:8080","--noreload","--insecure"]):
Probe().run_from_argv(["manage.py","runserver",*args])
"""
actual=[json.loads(line) for line in invoke(project,env,"-c",source).splitlines() if line.startswith("[")]
return check("Django runserver parses default, port-only and explicit addresses",
"Execute the real CLI parser and stop immediately before starting its server",
[[],["8080"],["0.0.0.0:8080","--noreload","--insecure"]],
[["127.0.0.1","8000",True,False],["127.0.0.1","8080",True,False],["0.0.0.0","8080",False,True]],actual)
if __name__=="__main__":
with TemporaryDirectory(prefix="mbsky-django-blueprint-cli-") as tmp:
root=Path(tmp)
project=Path(__file__).resolve().parent
env=dict(os.environ,DJANGO_LAB_KEY=token_urlsafe(36))
print(json.dumps([scaffold(root,env),migrations(root,env,project),utilities(root,env,project),
server_flags(project,env)],ensure_ascii=False))
本例需在 Windows、CPython 3.12.14、Django 5.2.19、SQLite 3.53.1、本机回环与隔离目录 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、CPython 3.12.14、Django 5.2.19、SQLite 3.53.1、本机回环与隔离目录
入口文件:projects/django-blueprint/cli_exercise.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
cli_exercise.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、CPython 3.12.14、Django 5.2.19、SQLite 3.53.1、本机回环与隔离目录。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a164.zip
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a165.zip