【Python】实现django-admin startproject --template

# start_project_from_template.py
import os
import sys

from jinja2 import Template

TEMPLATE_SUFFIX = '-tpl'
PROJECT_NAME = sys.argv[1]
IGNORE_DIRS = ['venv', '.idea', '.git']

try:
    ABS_PATH = os.path.abspath(sys.argv[2])
except KeyError:
    ABS_PATH = '.'


def replace_content(file_path, context):
    with open(file_path) as f:
        template = Template(f.read())
        content = template.render(context)

    with open(file_path, 'w') as f:
        f.write(content)

    old_name = file_path
    new_name = old_name.rstrip(TEMPLATE_SUFFIX)
    os.rename(old_name, new_name)
    print(f'{old_name} -> {new_name}')


def search_template_file_to_substitute(dir, context=None):
    if os.path.isfile(dir) and dir.endswith(TEMPLATE_SUFFIX):
        replace_content(dir, context)
    else:
        for root, dirs, files in os.walk(dir):
            for file in files:
                file_path = f'{root}{os.path.sep}{file}'
                if os.path.isfile(file_path) and file.endswith(TEMPLATE_SUFFIX):
                    replace_content(file_path, context)
                else:
                    search_template_file_to_substitute(file_path, context)


def render_template(project_path, context, ignore_dirs=None):
    ignore_dirs = ignore_dirs or []
    dirs = os.listdir(project_path)
    for dir in dirs:
        if dir not in ignore_dirs:
            search_template_file_to_substitute(f'{ABS_PATH}{os.path.sep}{dir}', context)

    main_app_path = f'{project_path}{os.path.sep}project_name'

    if os.path.exists(main_app_path):
        os.rename(main_app_path, f'{project_path}{os.path.sep}{context["project_name"]}')

    if os.path.exists(project_path):
        parent_path, project_path_name = os.path.split(project_path)
        os.rename(project_path, os.path.join(parent_path, context["project_name"]))


if __name__ == '__main__':
    # python start_project_from_template.py <project_name> <project_template_path>
    render_template(
        project_path=ABS_PATH,
        context={'project_name': PROJECT_NAME},
        ignore_dirs=IGNORE_DIRS
    )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值