#!/usr/bin/env python # -*- coding: utf-8 -*- """ Generate Apache configuration based on templates found in templates/apache_config/** """ import os import sys import time import django from django.conf import settings from django.template import Context from django.template.loader import get_template from django.utils import timezone __TARGETS = ('local', 'production', 'staging') def generate_apache_conf(target='local', quiet=True, yes=True): config_tpl = get_template('apache_config/{}.conf'.format(target)) is_robot = os.path.isfile(os.path.join(settings.STATIC_ROOT, 'robots.txt')) is_favicon = os.path.isfile(os.path.join(settings.STATIC_ROOT, 'favicon.ico')) rendered = config_tpl.render(Context({ 'settings': settings, 'is_robot': is_robot, 'is_favicon': is_favicon, 'wsgi_path': os.path.join(settings.SITE_ROOT, *settings.WSGI_APPLICATION.split('.')[:-1]) + '.py', })) # Cleanup blanklines rendered_lines = rendered.split("\n") rendered = [] lp = None for i, l in enumerate(rendered_lines): if not lp == l.strip() == "": rendered.append(l) lp = l.strip() rendered = "\n".join(rendered) output_filename = '{}.conf'.format(target) output_path = os.path.join(settings.DJANGO_ROOT, 'apache', output_filename) if os.path.exists(output_path) and not (yes or quiet): r = raw_input("Config file «{}» already exists, overwrite ? [Y/n]".format(output_filename)) if r and r[0] not in ('Y', 'y'): output_filename = '{0}-{1}.conf'.format(target, int(time.time())) output_path = os.path.join(settings.DJANGO_ROOT, 'apache', output_filename) with file(output_path, 'w') as output_file: output_file.write(rendered) if not quiet: print "Saved target {0} as {1}".format(target, output_filename) def main(quiet=True, yes=True, targets=None): if not targets: targets = __TARGETS for target in targets: generate_apache_conf(target=target, quiet=quiet, yes=yes) # for tgt_conf in os.listdir(tpl_dir): # if os.path.isfile(os.path.join(tpl_dir, tgt_conf)) and not tgt_conf.startswith('base'): # generate_apache_conf(target=os.path.splitext(tgt_conf)[0]) if __name__ == "__main__": BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) sys.path.append(BASE_DIR) django.setup() args = sys.argv[:] args.pop(0) if '-h' in args: print """ usage generate_config.py [-y] [-q] [target, target, ] Params: -y Force 'yes' if overwrite confirmation needed (not echoed) -q Quiet, no output (implies -q) target The name of the target to render. May have more. Must be at the end of the command line """ sys.exit(0) main( quiet='-q' in args, yes='-y' in args, targets=[t for t in args if not t.startswith('-')] )