蓝色天空网mbsky.com · 知识 · 实践 · 创造Django · 本地阅读预览
教程 / Python / 数据科学 / Django

把 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

python · 阅读源码
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))
预期结果 · 待实际运行核验
  • 假迁移只更新账本。真实应用增加 zone 并保留旧行。已有表的初始迁移按存在性检查记账。
在临时库比较真实迁移与 --fake

所需环境:Windows、CPython 3.12.14、Django 5.2.19、SQLite 3.53.1、本机回环与隔离目录

当前源码 SHA256:f2a56dae5127febab7309c22faa53d816360353dbb5d60b0f38857f80f94f1ac

下载本站示例源码

完整开发工程

解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。

下载本站 Django 项目与管理命令工程

所需环境:Windows、CPython 3.12.14、Django 5.2.19、SQLite 3.53.1、本机回环与隔离目录

ZIP SHA256:e38852b7af0b4c082970f296b483e2004558d2c6ce73fa23c126d8acae2bb776

常见错误与边界

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

练习与解答

运行 python cli_exercise.py,比较 marked 和 applied 对应结果。

展开参考解答

第一个状态没有新列,应用修订后旧行读到 north。

规范与官方依据