# 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
)
【Python】实现django-admin startproject --template
于 2023-02-10 11:28:12 首次发布