把 Django 管理命令用在可重跑的练习里
实际创建项目与应用、对比三种迁移模式,并验证管理账号、静态资源和测试命令。
学完这一章,你能够
- 实际创建项目与应用、对比三种迁移模式,并验证管理账号、静态资源和测试命令。
识别三个入口的配置边界
django-admin、python -m django 与 manage.py 都进入 Django 管理命令。前两者需要明确项目配置时可用 --settings,项目自己的 manage.py 默认指向本项目。先用 help 或 help 子命令读当前版本的参数。check 运行 Django 系统检查,不能代替业务测试。
startproject 生成项目配置及入口。startapp 生成应用骨架,注册到 INSTALLED_APPS 后才参与对应加载。若给目标目录,Django 会写入指定目录,先准备空目录并检查内容。
可通过 --template 传目录、压缩包或 URL。模板中的变量会渲染。--extension 选择要渲染的扩展名,--name 选择指定文件名。本站实测自编本地 ZIP、TXT 文件、单个 marker.conf,以及保留未列入渲染的原始变量。远程模板没有下载或执行。
从参数解析到实际服务
runserver 支持默认地址、单给端口和指定地址。本站用真实命令解析默认 127.0.0.1:8000、端口 8080 和 0.0.0.0:8080,最后一种没有对外监听。实际浏览器实验用随机回环端口。
--noreload 关闭自动重载,--insecure 在满足开发命令条件时让 staticfiles 提供静态资源,即使 DEBUG=False。它不是生产静态服务器。本站实际用两参数运行本机进程,核对静态 CSS 和导入依赖的字节。
让迁移账本与 SQLite 结构对照
makemigrations 生成模型差异修订,migrate 执行迁移。应用标签和目标版本可限定目标,依赖仍可能涉及其他应用。本机先用 catalog 0001 创建表,再真实生成添加 zone 的 0002。
--fake 只改迁移记录。本站核对账本已有 0002 而列仍未出现,再按步骤将账本退回 0001,真实执行 0002 后旧记录得到默认值。随意使用 fake 会让账本与结构分离。
--fake-initial 针对已有表的初始迁移,Django 检查对应表或初始 AddField 列是否存在。它不做完整结构或数据验证。本站用另一临时库预建同形表、放入一条旧记录,再核对旧行与标记。
用管理工具做具体操作
createsuperuser 可交互,也可用隔离环境变量配合 --noinput。命令生成的账号具有后台权限。shell 可在已加载应用的环境执行 ORM,本机用它读回 is_staff 和 is_superuser。
collectstatic 将发现的静态文件复制到 STATIC_ROOT。本站比较项目级 CSS 与应用级依赖的字节。test 运行独立测试库,本机执行模型精度与 URL 转换两个用例。不要把真实生产库当测试数据库。
常用命令
| 命令 | 作用 | 本站核对 |
| startproject | 创建项目入口与配置包。 | 默认目录及指定目录。 |
| startapp | 创建单个应用骨架。 | 默认目录、目标目录和本地模板。 |
| runserver | 运行开发服务。 | 解析参数并实际启动回环服务。 |
| makemigrations | 生成迁移文件。 | 生成了新增 zone 的 0002。 |
| migrate | 按目标推进或回退迁移。 | 实查 SQLite 列与账本。 |
| createsuperuser | 创建超级用户。 | 从 ORM 读回权限标志。 |
| shell | 在项目上下文运行 Python。 | 实际使用 -c 查询记录。 |
| collectstatic | 收集静态文件。 | 比较两项实际输出字节。 |
| test | 运行项目测试。 | 执行 apps.catalog 的两个测试。 |
startproject 参数
| 参数 | 作用 | 本机条件 |
| 项目名称 | 生成配置包的 Python 标识符。 | plaincoast。 |
| 目标目录 | 把项目文件写入指定现有目录。 | elsewhere。 |
| --template | 采用自定义项目骨架。 | 本站本地 ZIP。 |
| --extension | 将指定扩展名加入模板渲染范围。 | TXT 中的变量被替换。 |
| --name | 按文件名加入模板渲染。 | marker.conf 渲染,raw.conf 保留变量。 |
startapp 参数
| 参数 | 作用 | 本机条件 |
| 应用名称 | 新应用的 Python 标识符。 | plain_readings。 |
| 目标目录 | 将应用写入指定目录。 | app_destination。 |
| --template | 使用自编应用模板。 | 在本地 ZIP 中渲染 app_name。 |
runserver 参数
| 参数 | 作用 | 本机条件 |
| IP:端口 | 指定监听地址或只指定端口。 | 解析默认和两个变体。 |
| --noreload | 禁用自动重载。 | 实际回环服务按此方式启动。 |
| --insecure | 开发期强制处理静态文件。 | 读取 CSS 与子依赖。 |
migrate 参数
| 参数 | 作用 | 本机条件 |
| 应用标签 | 限定迁移目标,仍按依赖计划执行。 | catalog。 |
| 迁移版本 | 以指定修订为目标。 | 0001 与 0002。 |
| --fake | 只更新应用记录。 | 账本有记录而列未增加。 |
| --fake-initial | 对符合存在性检查的初始迁移记账。 | 预建表与旧行保留。 |
其他命令再对照
| 命令 | 实际输出 |
| createsuperuser | 创建隔离账户。 |
| shell | 查询超级用户属性。 |
| test | 测试运行器发现并执行两个用例。 |
| collectstatic | 输出实际项目级和应用级文件。 |
在临时库比较真实迁移与 --fake
展开查看收起
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))
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
完整开发工程
解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
第一个状态没有新列,应用修订后旧行读到 north。