构建Django项目的Makefile

大家好,在开发过程中,经常需要在终端中运行一些命令,比如:创建迁移、运行测试、linter 等,通常需要定期执行这些命令。

为此类命令提供快捷方式很有帮助,甚至更好地与项目的其他开发人员共享,可以使用 Makefile ,这是 Django 项目的有用命令列表。

安装

Poetry与 Dependabot存在一些问题 ,并且根本无法与 Renovate 一起使用,这里使用的pip-tools和单独的requirements.in还有requirements-dev.in,适用于本地和生产环境。

pip-install-dev:
    pip install --upgrade pip pip-tools
    pip-sync requirements.txt requirements-dev.txt

pip-install:
    pip install --upgrade pip pip-tools
    pip-sync requirements.txt

pip-update:
    pip install --upgrade pip pip-tools
    pip-compile requirements.in
    pip-compile requirements-dev.in
    pip-sync requirements.txt requirements-dev.txt

命令:

  • pip-install-dev:安装所有要求,包括本地。它是安装项目依赖的主要命令,所以把这个命令放在最上面。

  • pip-install- 不经常使用此命令,但仅使用生产依赖项运行代码可能会有所帮助。

  • pip-update更新 requirements.txt和 requirements-dev.txt,将新包添加到 requirements.in或者 requirements-dev.in.

运行项目

server:
    python manage.py migrate && python manage.py runserver

worker:
    python -m celery -A project_name worker --loglevel info

beat:
    python -m celery -A project_name beat --loglevel info

运行本地Web服务器和Celery这是显而易见的,另外可以在运行服务器时自动应用新的迁移。

运行linters

lint:
    flake8 palyanytsya
    mypy palyanytsya

black:
    python -m black palyanytsya

cleanimports:
    isort .
    autoflake -r -i --remove-all-unused-imports --ignore-init-module-imports project_name

clean-lint: cleanimports black lint

checkmigrations:
    python manage.py makemigrations --check --no-input --dry-run

命令:

  • lint:运行 flake8 linter 和 mypy 类型检查器。

  • black自动格式化代码 黑色 。

  • cleanimports: 运行 isort 并使用 Autoflake 删除未使用的 导入 。一定要设置 profile=black在其他设置中,以避免与 Black 发生冲突。

  • clean-lint: 运行上面的所有东西。您可以在承诺正确格式化代码之前运行此命令。

  • checkmigrations: 防止您在没有迁移的情况下提交模型更改。真的很酷的东西!

另外,使用 make lint && make checkmigrations在 CI pipeline和 git pre-commit hook中。还可以创建一个命令来设置这样的hook:

install-hooks: echo "make lint && make checkmigrations" > .git/hooks/pre-commit && chmod 777 .git/hooks/pre-commit

运行测试及编写消息

test:
    pytest -n 4 -x

使用 pytest-xdist,在multiprocess的模式下运行pytest。

messages:
    python manage.py makemessages --all --ignore=venv --extension html,py
    python manage.py translate_messages -s en -l uk -l es -u
    python manage.py compilemessages --ignore venv

搜集所有的字符串文字进行翻译 ,此外利用Django Autotranslate自动使用 Google Translate 翻译短语。

只要项目继续进行,就会出现新的本地命令,也许需要进入开发服务器以运行一些 python 代码。或者下载一个新的数据库转储(没有敏感数据)用于本地错误重现。最好将这些知识保留在代码库中,而不是存在脑海中,此外无需向同事解释如何执行完全相同的操作。

对于更复杂的任务,甚至可以创建一个 shell 脚本并从 Makefile 中调用,因此帮助其他开发人员找到这个新命令会更容易。

你可能感兴趣的:(django,python,后端)